Programs & Examples On #Commodity

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Use { before $ sign. And also add addslashes function to escape special characters.

$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".addslashes($rows['user'])."'";

How to ALTER multiple columns at once in SQL Server

If i understood your question correctly you can add multiple columns in a table by using below mentioned query.

Query:

Alter table tablename add (column1 dataype, column2 datatype);

Biggest differences of Thrift vs Protocol Buffers?

Protocol Buffers seems to have a more compact representation, but that's only an impression I get from reading the Thrift whitepaper. In their own words:

We decided against some extreme storage optimizations (i.e. packing small integers into ASCII or using a 7-bit continuation format) for the sake of simplicity and clarity in the code. These alterations can easily be made if and when we encounter a performance-critical use case that demands them.

Also, it may just be my impression, but Protocol Buffers seems to have some thicker abstractions around struct versioning. Thrift does have some versioning support, but it takes a bit of effort to make it happen.

PHP Warning: Module already loaded in Unknown on line 0

You should have a /etc/php2/conf.d directory (At least on Ubuntu I do) containing a bunch of .ini files which all get loaded when php runs. These files can contain duplicate settings that conflict with settings in php.ini. In my PHP installation I notice a file conf.d/20-intl.ini with an extension=intl.so setting. I bet that's your conflict.

List of enum values in java

You can simply write

new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));

Reload activity in Android

i used this and it works fine without finish()

startActivity(getIntent());

Xcode 10: A valid provisioning profile for this executable was not found

I did try all the answers above and had no luck. After that I restart my iPhone and problem seems gone. I know it is so stupid but it worked. Answers above most probably solves the problem but if not try to restart your iOS device.

How to remove blank lines from a Unix file

You can sed's -i option to edit in-place without using temporary file:

 sed -i '/^$/d' file

Apply function to each element of a list

Or, alternatively, you can take a list comprehension approach:

>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']

Most popular screen sizes/resolutions on Android phones

The vast majority of current android 2.1+ phone screens are 480x800 (or in the case of motodroid oddities, 480x854)

However, this doesn't mean this should be your only concern. You need to make it looking good on tablets, and smaller or 4:3 ratio smaller screens.

RelativeLayout is your friend!

Why a function checking if a string is empty always returns true?

I just write my own function, is_string for type checking and strlen to check the length.

function emptyStr($str) {
    return is_string($str) && strlen($str) === 0;
}

print emptyStr('') ? "empty" : "not empty";
// empty

Here's a small test repl.it

EDIT: You can also use the trim function to test if the string is also blank.

is_string($str) && strlen(trim($str)) === 0;    

How to downgrade tensorflow, multiple versions possible?

Pay attention: you cannot install arbitrary versions of tensorflow, they have to correspond to your python installation, which isn't conveyed by most of the answers here. This is also true for the current wheels like https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl (from this answer above). For this example, the cp35-cp35m hints that it is for Python 3.5.x

A huge list of different wheels/compatibilities can be found here on github. By using this, you can downgrade to almost every availale version in combination with the respective for python. For example:

pip install tensorflow==2.0.0

(note that previous to installing Python 3.7.8 alongside version 3.8.3 in my case, you would get

ERROR: Could not find a version that satisfies the requirement tensorflow==2.0.0 (from versions: 2.2.0rc1, 2.2.0rc2, 2.2.0rc3, 2.2.0rc4, 2.2.0, 2.3.0rc0, 2.3.0rc1)
ERROR: No matching distribution found for tensorflow==2.0.0

this also holds true for other non-compatible combinations.)

This should also be useful for legacy CPU without AVX support or GPUs with a compute capability that's too low.


If you only need the most recent releases (which it doesn't sound like in your question) a list of urls for the current wheel packages is available on this tensorflow page. That's from this SO-answer.

Note: This link to a list of different versions didn't work for me.

How do I simulate a hover with a touch in touch enabled browsers?

Try this:

<script>
document.addEventListener("touchstart", function(){}, true);
</script>

And in your CSS:

element:hover, element:active {
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-user-select: none;
-webkit-touch-callout: none /*only to disable context menu on long press*/
}

With this code you don't need an extra .hover class!

how to change class name of an element by jquery

$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');

Your code has two problems:

  1. The selector .IsBestAnswe does not match what you thought
  2. It's addClass(), not addclass().

Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer') part to add only:

$('.IsBestAnswer').addClass('bestanswer');

You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer vs. bestanswer).

SQL selecting rows by most recent date with two unique columns

So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".

Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row

SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( 
    SELECT chargeId,MAX(serviceMonth) AS serviceMonth
    FROM invoice
    GROUP BY chargeId) x 
    JOIN invoice t ON x.chargeId =t.chargeId
    AND x.serviceMonth = t.serviceMonth

day of the week to day number (Monday = 1, Tuesday = 2)

What about using idate()? idate()

$integer = idate('w', $timestamp);

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

When I added module: 'jsr305' as an additional exclude statement, it all worked out fine for me.

 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
exclude module: 'jsr305'

})

How to get the public IP address of a user in C#

For Web Applications ( ASP.NET MVC and WebForm )

/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
    var context = System.Web.HttpContext.Current;
    string ip = String.Empty;

    if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
        ip = context.Request.UserHostAddress;

    if (ip == "::1")
        ip = "127.0.0.1";

    return ip;
}

For Windows Applications ( Windows Form, Console, Windows Service , ... )

    static void Main(string[] args)
    {
        HTTPGet req = new HTTPGet();
        req.Request("http://checkip.dyndns.org");
        string[] a = req.ResponseBody.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3=a2.Split('<');
        string a4 = a3[0];
        Console.WriteLine(a4);
        Console.ReadLine();
    }

Understanding inplace=True

When inplace=True is passed, the data is renamed in place (it returns nothing), so you'd use:

df.an_operation(inplace=True)

When inplace=False is passed (this is the default value, so isn't necessary), performs the operation and returns a copy of the object, so you'd use:

df = df.an_operation(inplace=False) 

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

Python: list of lists

Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:

listoflists.append((list[:], list[0]))

However, list is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that doesn't use list as a variable name, and makes a copy:

listoflists = []
a_list = []
for i in range(0,10):
    a_list.append(i)
    if len(a_list)>3:
        a_list.remove(a_list[0])
        listoflists.append((list(a_list), a_list[0]))
print listoflists

Note that I demonstrated two different ways to make a copy of a list above: [:] and list().

The first, [:], is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.

The second, list(), is using the actual list type constructor to create a new list which has contents equal to the first list. (I didn't use it in the first example because you were overwriting that name in your code - which is a good example of why you don't want to do that!)

CSS - Syntax to select a class within an id

Here's two options. I prefer the navigationAlt option since it involves less work in the end:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <style type="text/css">_x000D_
    #navigation li {_x000D_
      color: green;_x000D_
    }_x000D_
    #navigation li .navigationLevel2 {_x000D_
      color: red;_x000D_
    }_x000D_
    #navigationAlt {_x000D_
      color: green;_x000D_
    }_x000D_
    #navigationAlt ul {_x000D_
      color: red;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <ul id="navigation">_x000D_
    <li>Level 1 item_x000D_
      <ul>_x000D_
        <li class="navigationLevel2">Level 2 item</li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
  <ul id="navigationAlt">_x000D_
    <li>Level 1 item_x000D_
      <ul>_x000D_
        <li>Level 2 item</li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

unix sort descending order

If you only want to sort only on the 5th field then use -k5,5.

Also, use the -t command line switch to specify the delimiter to tab. Try this:

sort  -k5,5 -r -n -t \t filename

or if the above doesn't work (with the tab) this:

sort  -k5,5 -r -n -t $'\t' filename

The man page for sort states:

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

Finally, this SO question Unix Sort with Tab Delimiter might be helpful.

TLS 1.2 not working in cURL

Replace following

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');

With

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);

Should work flawlessly.

How to sort by column in descending order in Spark SQL?

It's in org.apache.spark.sql.DataFrame for sort method:

df.sort($"col1", $"col2".desc)

Note $ and .desc inside sort for the column to sort the results by.

Moving from position A to position B slowly with animation

Use jquery animate and give it a long duration say 2000

$("#Friends").animate({ 
        top: "-=30px",
      }, duration );

The -= means that the animation will be relative to the current top position.

Note that the Friends element must have position set to relative in the css:

#Friends{position:relative;}

How do I decompile a .NET EXE into readable C# source code?

Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.

ADDED: My latest favourite is JetBrains' dotPeek.

Counting array elements in Perl

Edit: Hash versus Array

As cincodenada correctly pointed out in the comment, ysth gave a better answer: I should have answered your question with another question: "Do you really want to use a Perl array? A hash may be more appropriate."

An array allocates memory for all possible indices up to the largest used so-far. In your example, you allocate 24 cells (but use only 3). By contrast, a hash only allocates space for those fields that are actually used.

Array solution: scalar grep

Here are two possible solutions (see below for explanation):

print scalar(grep {defined $_} @a), "\n";  # prints 3
print scalar(grep $_, @a), "\n";            # prints 3

Explanation: After adding $a[23], your array really contains 24 elements --- but most of them are undefined (which also evaluates as false). You can count the number of defined elements (as done in the first solution) or the number of true elements (second solution).

What is the difference? If you set $a[10]=0, then the first solution will count it, but the second solution won't (because 0 is false but defined). If you set $a[3]=undef, none of the solutions will count it.

Hash solution (by yst)

As suggested by another solution, you can work with a hash and avoid all the problems:

$a{0}  = 1;
$a{5}  = 2;
$a{23} = 3;
print scalar(keys %a), "\n";  # prints 3

This solution counts zeros and undef values.

c# replace \" characters

Were you trying it like this:

string text = GetTextFromSomewhere();
text.Replace("\\", "");
text.Replace("\"", "");

? If so, that's the problem - Replace doesn't change the original string, it returns a new string with the replacement performed... so you'd want:

string text = GetTextFromSomewhere();
text = text.Replace("\\", "").Replace("\"", "");

Note that this will replace each backslash and each double-quote character; if you only wanted to replace the pair "backslash followed by double-quote" you'd just use:

string text = GetTextFromSomewhere();
text = text.Replace("\\\"", "");

(As mentioned in the comments, this is because strings are immutable in .NET - once you've got a string object somehow, that string will always have the same contents. You can assign a reference to a different string to a variable of course, but that's not actually changing the contents of the existing string.)

Is there a simple, elegant way to define singletons?

class Singleton(object[,...]):

    staticVar1 = None
    staticVar2 = None

    def __init__(self):
        if self.__class__.staticVar1==None :
            # create class instance variable for instantiation of class
            # assign class instance variable values to class static variables
        else:
            # assign class static variable values to class instance variables

What does "var" mean in C#?

It declares a type based on what is assigned to it in the initialisation.

A simple example is that the code:

var i = 53;

Will examine the type of 53, and essentially rewrite this as:

int i = 53;

Note that while we can have:

long i = 53;

This won't happen with var. Though it can with:

var i = 53l; // i is now a long

Similarly:

var i = null; // not allowed as type can't be inferred.
var j = (string) null; // allowed as the expression (string) null has both type and value.

This can be a minor convenience with complicated types. It is more important with anonymous types:

var i = from x in SomeSource where x.Name.Length > 3 select new {x.ID, x.Name};
foreach(var j in i)
  Console.WriteLine(j.ID.ToString() + ":" + j.Name);

Here there is no other way of defining i and j than using var as there is no name for the types that they hold.

Cannot call getSupportFragmentManager() from activity

Instead of

extends Fragment

use

extends android.support.v4.app.Fragment 

This works for me. for *API14 and above

Jquery Ajax, return success/error from mvc.net controller

When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:

return StatusCode(500, "My error");

Or

return StatusCode((int)HttpStatusCode.InternalServerError, "My error");

Or

Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });

Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error: in client side (ajax).

you can have ajax call like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
       success: function (response)  {
            console.log("Custom message : " + response.responseText);
        }, //Is Called when Status Code is 200[OK] or other Http success code
        error: function (jqXHR, textStatus, errorThrown)  {
            console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
        }, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
        })

Additionally you can handle different HTTP errors from jQuery side like:

$.ajax({
        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        },
        statusCode: {
            500: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            501: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            }
        })

statusCode: is useful when you want to call different functions for different status codes that you return from server.

You can see list of different Http Status codes here:Wikipedia

Additional resources:

  1. Returning Server-Side Errors from AJAX Calls
  2. Returning a JsonResult within the Error function of JQuery Ajax
  3. Handling Ajax errors with jQuery

How to force child div to be 100% of parent div's height without specifying parent's height?

I know it's been a looong time since the question was made, but I found an easy solution and thought someone could use it (sorry about the poor english). Here it goes:

CSS

.main, .sidebar {
    float: none;
    padding: 20px;
    vertical-align: top;
}
.container {
    display: table;
}
.main {
    width: 400px;
    background-color: LightSlateGrey;
    display: table-cell;
}
.sidebar {
    width: 200px;
    display: table-cell;
    background-color: Tomato;
}

HTML

<div class="container clearfix">
    <div class="sidebar">
        simple text here
    </div>
    <div class="main">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam congue, tortor in mattis mattis, arcu erat pharetra orci, at vestibulum lorem ante a felis. Integer sit amet est ac elit vulputate lobortis. Vestibulum in ipsum nulla. Aenean erat elit, lacinia sit amet adipiscing quis, aliquet at erat. Vivamus massa sem, cursus vel semper non, dictum vitae mi. Donec sed bibendum ante.
    </div>
</div>

Simple example. Note that you can turn into responsiveness.

Removing items from a list

You need to use Iterator and call remove() on iterator instead of using for loop.

git with IntelliJ IDEA: Could not read from remote repository

I had this problem with a fork from some online course. I cloned my fork and ran into a permissions error. I couldn't understand why it was insisting I was my user from my other company. But as the previous commenter mentioned I had the Clone git repositories using ssh setting checked and I had forgotten to add an ssh key to my new account. So I did and then still couldn't push because I got THIS error. The way I solved it was to push using the Github Desktop client.

Takeaways:

  1. When you open a new GitHub account make sure to add an ssh key to it
  2. Use different ssh keys for different accounts
  3. In general I run into some GitHub issue on IntelliJ at least once or twice for every project. Make sure you have a copy of GitHub desktop and load your projects into it. It can and will help you with lots of problems you may run into with Intellij - not just this one. It's actually a really nice GUI client and free!
  4. It probably makes sense to do what @yabin suggests and use the native client on a Mac

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Please follow these steps.

1) Declare following variable in .h file.

  {      
         CGFloat animatedDistance;
  }

2) Declare following constants in .m file.

  static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
  static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
  static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
  static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
  static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;

3) Use UITextField delegate to move up/down keyboard.

  -(void) textFieldDidBeginEditing:(UITextField *)textField
  { 
         if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
         {
               CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
               CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];

               CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
               CGFloat numerator =
    midline - viewRect.origin.y
    - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
               CGFloat denominator =
    (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
    * viewRect.size.height;
               CGFloat heightFraction = numerator / denominator;

               if (heightFraction < 0.0)
               {
                     heightFraction = 0.0;
               }
               else if (heightFraction > 1.0)
               {
                     heightFraction = 1.0;
               }

               UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
               if (orientation == UIInterfaceOrientationPortrait)
               {
                     animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
               }
               else
               {
                     animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
               }

               CGRect viewFrame = self.view.frame;
               viewFrame.origin.y -= animatedDistance;

               [UIView beginAnimations:nil context:NULL];
               [UIView setAnimationBeginsFromCurrentState:YES];
               [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

               [self.view setFrame:viewFrame];

               [UIView commitAnimations];
       }
  }

  -(void) textFieldDidEndEditing:(UITextField *)textField
  {
       if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
       {
             CGRect viewFrame = self.view.frame;
             viewFrame.origin.y += animatedDistance;

             [UIView beginAnimations:nil context:NULL];
             [UIView setAnimationBeginsFromCurrentState:YES];
             [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];

             [self.view setFrame:viewFrame];

             [UIView commitAnimations];
       }
 }

Explain the different tiers of 2 tier & 3 tier architecture?

In a modern two-tier architecture, the server holds both the application and the data. The application resides on the server rather than the client, probably because the server will have more processing power and disk space than the PC.

In a three-tier architecture, the data and applications are split onto seperate servers, with the server-side distributed between a database server and an application server. The client is a front end, simply requesting and displaying data. Reason being that each server will be dedicated to processing either data or application requests, hence a more manageable system and less contention for resources will occur.

You can refer to Difference between three tier vs. n-tier

How to combine two byte arrays

The simplest method (inline, assuming a and b are two given arrays):

byte[] c = (new String(a, cch) + new String(b, cch)).getBytes(cch);

This, of course, works with more than two summands and uses a concatenation charset, defined somewhere in your code:

static final java.nio.charset.Charset cch = java.nio.charset.StandardCharsets.ISO_8859_1;

Or, in more simple form, without this charset:

byte[] c = (new String(a, "l1") + new String(b, "l1")).getBytes("l1");

But you need to suppress UnsupportedEncodingException which is unlikely to be thrown.


The fastest method:

public static byte[] concat(byte[] a, byte[] b) {
    int lenA = a.length;
    int lenB = b.length;
    byte[] c = Arrays.copyOf(a, lenA + lenB);
    System.arraycopy(b, 0, c, lenA, lenB);
    return c;
}

Writing a large resultset to an Excel file using POI

I updated BigGridDemo to support multiple sheets.

BigExcelWriterImpl.java

package com.gdais.common.apache.poi.bigexcelwriter;

import static com.google.common.base.Preconditions.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;

public class BigExcelWriterImpl implements BigExcelWriter {

private static final String XML_ENCODING = "UTF-8";

@Nonnull
private final File outputFile;

@Nullable
private final File tempFileOutputDir;

@Nullable
private File templateFile = null;

@Nullable
private XSSFWorkbook workbook = null;

@Nonnull
private LinkedHashMap<String, XSSFSheet> addedSheets = new LinkedHashMap<String, XSSFSheet>();

@Nonnull
private Map<XSSFSheet, File> sheetTempFiles = new HashMap<XSSFSheet, File>();

BigExcelWriterImpl(@Nonnull File outputFile) {
    this.outputFile = outputFile;
    this.tempFileOutputDir = outputFile.getParentFile();
}

@Override
public BigExcelWriter createWorkbook() {
    workbook = new XSSFWorkbook();
    return this;
}

@Override
public BigExcelWriter addSheets(String... sheetNames) {
    checkState(workbook != null, "workbook must be created before adding sheets");

    for (String sheetName : sheetNames) {
        XSSFSheet sheet = workbook.createSheet(sheetName);
        addedSheets.put(sheetName, sheet);
    }

    return this;
}

@Override
public BigExcelWriter writeWorkbookTemplate() throws IOException {
    checkState(workbook != null, "workbook must be created before writing template");
    checkState(templateFile == null, "template file already written");

    templateFile = File.createTempFile(FilenameUtils.removeExtension(outputFile.getName())
            + "-template", ".xlsx", tempFileOutputDir);
    System.out.println(templateFile);
    FileOutputStream os = new FileOutputStream(templateFile);
    workbook.write(os);
    os.close();

    return this;
}

@Override
public SpreadsheetWriter createSpreadsheetWriter(String sheetName) throws IOException {
    if (!addedSheets.containsKey(sheetName)) {
        addSheets(sheetName);
    }

    return createSpreadsheetWriter(addedSheets.get(sheetName));
}

@Override
public SpreadsheetWriter createSpreadsheetWriter(XSSFSheet sheet) throws IOException {
    checkState(!sheetTempFiles.containsKey(sheet), "writer already created for this sheet");

    File tempSheetFile = File.createTempFile(
            FilenameUtils.removeExtension(outputFile.getName())
                    + "-sheet" + sheet.getSheetName(), ".xml", tempFileOutputDir);

    Writer out = null;
    try {
        out = new OutputStreamWriter(new FileOutputStream(tempSheetFile), XML_ENCODING);
        SpreadsheetWriter sw = new SpreadsheetWriterImpl(out);

        sheetTempFiles.put(sheet, tempSheetFile);
        return sw;
    } catch (RuntimeException e) {
        if (out != null) {
            out.close();
        }
        throw e;
    }
}

private static Function<XSSFSheet, String> getSheetName = new Function<XSSFSheet, String>() {

    @Override
    public String apply(XSSFSheet sheet) {
        return sheet.getPackagePart().getPartName().getName().substring(1);
    }
};

@Override
public File completeWorkbook() throws IOException {
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(outputFile);
        ZipOutputStream zos = new ZipOutputStream(out);

        Iterable<String> sheetEntries = Iterables.transform(sheetTempFiles.keySet(),
                getSheetName);
        System.out.println("Sheet Entries: " + sheetEntries);
        copyTemplateMinusEntries(templateFile, zos, sheetEntries);

        for (Map.Entry<XSSFSheet, File> entry : sheetTempFiles.entrySet()) {
            XSSFSheet sheet = entry.getKey();
            substituteSheet(entry.getValue(), getSheetName.apply(sheet), zos);
        }
        zos.close();
        out.close();

        return outputFile;
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

private static void copyTemplateMinusEntries(File templateFile,
        ZipOutputStream zos, Iterable<String> entries) throws IOException {

    ZipFile templateZip = new ZipFile(templateFile);

    @SuppressWarnings("unchecked")
    Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) templateZip.entries();
    while (en.hasMoreElements()) {
        ZipEntry ze = en.nextElement();
        if (!Iterables.contains(entries, ze.getName())) {
            System.out.println("Adding template entry: " + ze.getName());
            zos.putNextEntry(new ZipEntry(ze.getName()));
            InputStream is = templateZip.getInputStream(ze);
            copyStream(is, zos);
            is.close();
        }
    }
}

private static void substituteSheet(File tmpfile, String entry,
        ZipOutputStream zos)
        throws IOException {
    System.out.println("Adding sheet entry: " + entry);
    zos.putNextEntry(new ZipEntry(entry));
    InputStream is = new FileInputStream(tmpfile);
    copyStream(is, zos);
    is.close();
}

private static void copyStream(InputStream in, OutputStream out) throws IOException {
    byte[] chunk = new byte[1024];
    int count;
    while ((count = in.read(chunk)) >= 0) {
        out.write(chunk, 0, count);
    }
}

@Override
public Workbook getWorkbook() {
    return workbook;
}

@Override
public ImmutableList<XSSFSheet> getSheets() {
    return ImmutableList.copyOf(addedSheets.values());
}

}

SpreadsheetWriterImpl.java

package com.gdais.common.apache.poi.bigexcelwriter;

import java.io.IOException;
import java.io.Writer;
import java.util.Calendar;

import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.util.CellReference;

class SpreadsheetWriterImpl implements SpreadsheetWriter {

private static final String XML_ENCODING = "UTF-8";

private final Writer _out;
private int _rownum;

SpreadsheetWriterImpl(Writer out) {
    _out = out;
}

@Override
public SpreadsheetWriter closeFile() throws IOException {
    _out.close();

    return this;
}

@Override
public SpreadsheetWriter beginSheet() throws IOException {
    _out.write("<?xml version=\"1.0\" encoding=\""
            + XML_ENCODING
            + "\"?>"
            +
            "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
    _out.write("<sheetData>\n");

    return this;
}

@Override
public SpreadsheetWriter endSheet() throws IOException {
    _out.write("</sheetData>");
    _out.write("</worksheet>");

    closeFile();
    return this;
}

/**
 * Insert a new row
 * 
 * @param rownum
 *            0-based row number
 */
@Override
public SpreadsheetWriter insertRow(int rownum) throws IOException {
    _out.write("<row r=\"" + (rownum + 1) + "\">\n");
    this._rownum = rownum;

    return this;
}

/**
 * Insert row end marker
 */
@Override
public SpreadsheetWriter endRow() throws IOException {
    _out.write("</row>\n");

    return this;
}

@Override
public SpreadsheetWriter createCell(int columnIndex, String value, int styleIndex)
        throws IOException {
    String ref = new CellReference(_rownum, columnIndex).formatAsString();
    _out.write("<c r=\"" + ref + "\" t=\"inlineStr\"");
    if (styleIndex != -1) {
        _out.write(" s=\"" + styleIndex + "\"");
    }
    _out.write(">");
    _out.write("<is><t>" + value + "</t></is>");
    _out.write("</c>");

    return this;
}

@Override
public SpreadsheetWriter createCell(int columnIndex, String value) throws IOException {
    createCell(columnIndex, value, -1);

    return this;
}

@Override
public SpreadsheetWriter createCell(int columnIndex, double value, int styleIndex)
        throws IOException {
    String ref = new CellReference(_rownum, columnIndex).formatAsString();
    _out.write("<c r=\"" + ref + "\" t=\"n\"");
    if (styleIndex != -1) {
        _out.write(" s=\"" + styleIndex + "\"");
    }
    _out.write(">");
    _out.write("<v>" + value + "</v>");
    _out.write("</c>");

    return this;
}

@Override
public SpreadsheetWriter createCell(int columnIndex, double value) throws IOException {
    createCell(columnIndex, value, -1);

    return this;
}

@Override
public SpreadsheetWriter createCell(int columnIndex, Calendar value, int styleIndex)
        throws IOException {
    createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex);

    return this;
}

@Override
public SpreadsheetWriter createCell(int columnIndex, Calendar value)
        throws IOException {
    createCell(columnIndex, value, -1);

    return this;
}
}

creating json object with variables

Try this to see how you can create a object from strings.

var firstName = "xx";
var lastName  = "xy";
var phone     = "xz";
var adress    = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);

Windows batch script launch program and exit console

%ComSpec% /c %systemroot%\notepad.exe

How to use glob() to find files recursively?

If the files are on a remote file system or inside an archive, you can use an implementation of the fsspec AbstractFileSystem class. For example, to list all the files in a zipfile:

from fsspec.implementations.zip import ZipFileSystem
fs = ZipFileSystem("/tmp/test.zip")
fs.glob("/**")  # equivalent: fs.find("/")

or to list all the files in a publicly available S3 bucket:

from s3fs import S3FileSystem
fs_s3 = S3FileSystem(anon=True)
fs_s3.glob("noaa-goes16/ABI-L1b-RadF/2020/045/**")  # or use fs_s3.find

you can also use it for a local filesystem, which may be interesting if your implementation should be filesystem-agnostic:

from fsspec.implementations.local import LocalFileSystem
fs = LocalFileSystem()
fs.glob("/tmp/test/**")

Other implementations include Google Cloud, Github, SFTP/SSH, Dropbox, and Azure. For details, see the fsspec API documentation.

Where do alpha testers download Google Play Android apps?

You need to publish the app before it becomes available for testing.

if you publish the app and the apk is only in "alpha testing" section then it is NOT available to general public, only for activated testers in the alpha section.

EDIT: One additional note: "normal" users will not find your app on Google Play, but also the activated tester can not find the application by using the search box.

Only the direct link to the application package will work. (only for the activated testers).

Virtualbox shared folder permissions

The issue is that the shared folder's permissions are set to not allow symbolic links by default. You can enable them in a few easy steps.

  1. Shut down the virtual machine.
  2. Note your machine name at Machine > Settings > General > Name
  3. Note your shared folder name at 'Machine > Settings > Shared Folders`
  4. Find your VirtualBox root directory and execute the following command. VBoxManage setextradata "" VBoxInternal2/SharedFoldersEnableSymlinksCreate/ 1
  5. Start up the virtual machine and the shared folder will now allow symbolic links.

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

I think there was some bugs in previous App-Compat lib for child Fragment. I tried @Vidar Wahlberg and @Matt's ans they did not work for me. After updating the appcompat library my code run perfectly without any extra effort.

What static analysis tools are available for C#?

Axivion Bauhaus Suite is a static analysis tool that works with C# (as well as C, C++ and Java).

It provides the following capabilities:

  • Software Architecture Visualization (inlcuding dependencies)
  • Enforcement of architectural rules e.g. layering, subsystems, calling rules
  • Clone Detection - highlighting copy and pasted (and modified code)
  • Dead Code Detection
  • Cycle Detection
  • Software Metrics
  • Code Style Checks

These features can be run on a one-off basis or as part of a Continuous Integration process. Issues can be highlighted on a per project basis or per developer basis when the system is integrated with a source code control system.

Pretty printing XML in Python

I wrote a solution to walk through an existing ElementTree and use text/tail to indent it as one typically expects.

def prettify(element, indent='  '):
    queue = [(0, element)]  # (level, element)
    while queue:
        level, element = queue.pop(0)
        children = [(level + 1, child) for child in list(element)]
        if children:
            element.text = '\n' + indent * (level+1)  # for child open
        if queue:
            element.tail = '\n' + indent * queue[0][0]  # for sibling open
        else:
            element.tail = '\n' + indent * (level-1)  # for parent close
        queue[0:0] = children  # prepend so children come before siblings

android button selector

Create custom_selector.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/unselected" android:state_pressed="true" />
   <item android:drawable="@drawable/selected" />
</selector>

Create selected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/selected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Create unselected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/unselected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Add following colors for selected/unselected state in color.xml of values folder

<color name="selected">#a8cf45</color>
<color name="unselected">#ff8cae3b</color>

you can check complete solution from here

Regular expression to match a word or its prefix

Square brackets are meant for character class, and you're actually trying to match any one of: s, |, s (again), e, a, s (again), o and n.

Use parentheses instead for grouping:

(s|season)

or non-capturing group:

(?:s|season)

Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either works, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.

Google Play on Android 4.0 emulator


Playstore + Google Play Services In Linux(Ubuntu 14.04)


Download Google apps (GoogleLoginService.apk , GoogleServicesFramework.apk )

from here http://www.securitylearn.net/2013/08/31/google-play-store-on-android-emulator/

and Download ( Phonesky.apk) from here https://basketbuild.com/filedl/devs?dev=dankoman&dl=dankoman/Phonesky.apk

GO TO ANDROID SDK LOCATION>>

cd -Android SDK's tools Location-

TO RUN EMULATOR>>

Android/Sdk/tools$ ./emulator64-x86 -avd Kitkat -partition-size 566 -no-audio -no-boot-anim

SET PERMISSIONS>>

cd Android/Sdk/platform-tools platform-tools$ adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system

platform-tools$ adb shell chmod 777 /system/app

platform-tools$ adb push /home/nazmul/Downloads/GoogleLoginService.apk /system/app/.

PUSH PLAY APKS >>

platform-tools$ adb push /home/nazmul/Downloads/GoogleServicesFramework.apk /system/app/. platform-tools$ adb push /home/nazmul/Downloads/Phonesky.apk /system/app/. platform-tools$ adb shell rm /system/app/SdkSetup*

sending email via php mail function goes to spam

One thing that I have observed is likely the email address you're providing is not a valid email address at the domain. like [email protected]. The email should be existing at Google Domain. I had alot of issues before figuring that out myself... Hope it helps.

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

How to detect page zoom level in all modern browsers?

Didn't test this for IE, but if you make an element elem with

min-width: 100%

then

window.document.width / elem.clientWidth

will give you your browser zoom level (including the document.body.style.zoom factor).

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is not restricted to Tomcat’s Java process, but passed to all JVM processes running on the same machine.

Use CATALINA_OPTS if you specifically want to pass JVM arguments to Tomcat's servlet engine.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

biggest integer that can be stored in a double

9007199254740992 (that's 9,007,199,254,740,992) with no guarantees :)

Program

#include <math.h>
#include <stdio.h>

int main(void) {
  double dbl = 0; /* I started with 9007199254000000, a little less than 2^53 */
  while (dbl + 1 != dbl) dbl++;
  printf("%.0f\n", dbl - 1);
  printf("%.0f\n", dbl);
  printf("%.0f\n", dbl + 1);
  return 0;
}

Result

9007199254740991
9007199254740992
9007199254740992

Copy a variable's value into another

For strings or input values you could simply use this:

var a = $('#some_hidden_var').val(),
b = a.substr(0);

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Reset local repository branch to be just like remote repository HEAD

Provided that the remote repository is origin, and that you're interested in branch_name:

git fetch origin
git reset --hard origin/<branch_name>

Also, you go for reset the current branch of origin to HEAD.

git fetch origin
git reset --hard origin/HEAD

How it works:

git fetch origin downloads the latest from remote without trying to merge or rebase anything.

Then the git reset resets the <branch_name> branch to what you just fetched. The --hard option changes all the files in your working tree to match the files in origin/branch_name.

How to remove square brackets from list in Python?

if you have numbers in list, you can use map to apply str to each element:

print ', '.join(map(str, LIST))

^ map is C code so it's faster than str(i) for i in LIST

What does the explicit keyword mean?

Suppose, you have a class String:

class String {
public:
    String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

Now, if you try:

String mystring = 'x';

The character 'x' will be implicitly converted to int and then the String(int) constructor will be called. But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as explicit:

class String {
public:
    explicit String (int n); //allocate n bytes
    String(const char *p); // initialize sobject with string p
};

How do you set up use HttpOnly cookies in PHP

A more elegant solution since PHP >=7.0

session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);

session_start

session_start options

Windows batch: sleep

timeout /t 10 /nobreak > NUL

/t specifies the time to wait in seconds

/nobreak won't interrupt the timeout if you press a key (except CTRL-C)

> NUL will suppress the output of the command

Play a Sound with Python

After the play() command add a delay of say 10 secs or so, it'll work

import pygame

import time

pygame.init()

pygame.mixer.music.load("test.wav")

pygame.mixer.music.play()

time.sleep(10)

This also plays .mp3 files.

clientHeight/clientWidth returning different values on different browsers

Paul A is right about why the discrepancy exists but the solution offered by Ngm is wrong (in the sense of JQuery).

The equivalent of clientHeight and clientWidth in jquery (1.3) is

$(window).width(), $(window).height()

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

You can run this command in your project directory. Basically it just cleans the build and gradle.

   cd android && rm -R .gradle && cd app && rm -R build

In my case, I was using react-native using this as a script in package.json

"scripts": { "clean-android": "cd android && rm -R .gradle && cd app && rm -R build" }

MySQL: Fastest way to count number of rows

Try this:

SELECT
    table_rows "Rows Count"
FROM
    information_schema.tables
WHERE
    table_name="Table_Name"
AND
    table_schema="Database_Name";

What's the best way to test SQL Server connection programmatically?

Here is my version based on the @peterincumbria answer:

using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
return await dbContext.Database.CanConnectAsync(cToken);

I'm using Observable for polling health checking by interval and handling return value of the function. try-catch is not needed here because: enter image description here

Possible to extend types in Typescript?

What you are trying to achieve is equivalent to

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.

What is the best workaround for the WCF client `using` block issue?

What is this?

This is the CW version of the accepted answer but with (what I consider complete) Exception handling included.

The accepted answer references this website that is no longer around. To save you trouble, I am including the most relevant parts here. In addition, I modified it slightly to include exception retry handling to handle those pesky network timeouts.

Simple WCF Client Usage

Once you generate your client side proxy, this is all you need to implement it.

Service<IOrderService>.Use(orderService=>
{
  orderService.PlaceOrder(request);
});

ServiceDelegate.cs

Add this file to your solution. No changes are needed to this file, unless you want to alter the number of retries or what exceptions you want to handle.

public delegate void UseServiceDelegate<T>(T proxy);

public static class Service<T>
{
    public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>(""); 

    public static void Use(UseServiceDelegate<T> codeBlock)
    {
        IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
        bool success = false;


       Exception mostRecentEx = null;
       int millsecondsToSleep = 1000;

       for(int i=0; i<5; i++)  // Attempt a maximum of 5 times 
       {
           try
           {
               codeBlock((T)proxy);
               proxy.Close();
               success = true; 
               break;
           }

           // The following is typically thrown on the client when a channel is terminated due to the server closing the connection.
           catch (ChannelTerminatedException cte)
           {
              mostRecentEx = cte;
               proxy.Abort();
               //  delay (backoff) and retry 
               Thread.Sleep(millsecondsToSleep  * (i + 1)); 
           }

           // The following is thrown when a remote endpoint could not be found or reached.  The endpoint may not be found or 
           // reachable because the remote endpoint is down, the remote endpoint is unreachable, or because the remote network is unreachable.
           catch (EndpointNotFoundException enfe)
           {
              mostRecentEx = enfe;
               proxy.Abort();
               //  delay (backoff) and retry 
               Thread.Sleep(millsecondsToSleep * (i + 1)); 
           }

           // The following exception that is thrown when a server is too busy to accept a message.
           catch (ServerTooBusyException stbe)
           {
              mostRecentEx = stbe;
               proxy.Abort();

               //  delay (backoff) and retry 
               Thread.Sleep(millsecondsToSleep * (i + 1)); 
           }
           catch (TimeoutException timeoutEx)
           {
               mostRecentEx = timeoutEx;
               proxy.Abort();

               //  delay (backoff) and retry 
               Thread.Sleep(millsecondsToSleep * (i + 1)); 
           } 
           catch (CommunicationException comException)
           {
               mostRecentEx = comException;
               proxy.Abort();

               //  delay (backoff) and retry 
               Thread.Sleep(millsecondsToSleep * (i + 1)); 
           }
           catch(Exception )
           {
                // rethrow any other exception not defined here
                // You may want to define a custom Exception class to pass information such as failure count, and failure type
                proxy.Abort();
                throw ;  
           }
       }
       if (success == false && mostRecentEx != null) 
       { 
           proxy.Abort();
           throw new Exception("WCF call failed after 5 retries.", mostRecentEx );
       }

    }
}

PS: I've made this post a community wiki. I won't collect "points" from this answer, but prefer you upvote it if you agree with the implementation, or edit it to make it better.

How do I change the language of moment.js?

For those working in asynchronous environments, moment behaves unexpectedly when loading locales on demand.

Instead of

await import('moment/locale/en-ca');
moment.locale('en-ca');

reverse the order

moment.locale('en-ca');
await import('moment/locale/en-ca');

It seems like the locales are loaded into the current selected locale, overriding any previously set locale information. So switching the locale first, then loading the locale information does not cause this issue.

LinearLayout not expanding inside a ScrollView

The solution is to use

android:fillViewport="true"

on Scroll view and moreover try to use

"wrap_content" instead of "fill_parent" as "fill_parent"

is deprecated now.

how to disable DIV element and everything inside

The following css statement disables click events

pointer-events:none;

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

Gradle project refresh failed after Android Studio update

This might be too late to answer. But this may help someone.

In my case there was problem of JDK path.

I just set proper JDK path for Android Studio 2.1

File -> Project Structure -> From Left Side Panel "SDK Location" -> JDK Location -> Click to select JDK Path

How to change a particular element of a C++ STL vector

Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.

You have four ways of accessing a specific item in a vector:

  • Using the [] operator
  • Using the member function at(...)
  • Using an iterator in combination with a given offset
  • Using std::for_each from the algorithm header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.

In the following examples I will be using the following vector as a lab rat and explaining the first three methods:

static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));

This creates a vector as seen below:

1 2 3 4

First let's look at the [] way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the [] operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:

v[10] = 9;

This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100 instead of 234, which is somewhat connected to that very location where you retrieve an item from you vector.

A much better way is to use at(...). This will automatically check for out of bounds behaviour and break throwing an std::out_of_range. So in the case when we have

v.at(10) = 9;

We will get:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)

The third way is similar to the [] operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:

std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9;  // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...

As you can see we can also do

*(it+10) = 9;

which is again an invalid memory access. This is basically the same as using at(0 + offset) but without the out of bounds error checking.

I would advice using at(...) whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the [] operator.

Label on the left side instead above an input field

I am sure you would've already found your answer... here is the solution I derived at.

That's my CSS.

.field, .actions {
    margin-bottom: 15px;
  }
  .field label {
    float: left;
    width: 30%;
    text-align: right;
    padding-right: 10px;
    margin: 5px 0px 5px 0px;
  }
  .field input {
    width: 70%;
    margin: 0px;
  }

And my HTML...

<h1>New customer</h1>
<div class="container form-center">
    <form accept-charset="UTF-8" action="/customers" class="new_customer" id="new_customer" method="post">
    <div style="margin:0;padding:0;display:inline"></div>

  <div class="field">
    <label for="customer_first_name">First name</label>
    <input class="form-control" id="customer_first_name" name="customer[first_name]" type="text" />
  </div>
  <div class="field">
    <label for="customer_last_name">Last name</label>
    <input class="form-control" id="customer_last_name" name="customer[last_name]" type="text" />
  </div>
  <div class="field">
    <label for="customer_addr1">Addr1</label>
    <input class="form-control" id="customer_addr1" name="customer[addr1]" type="text" />
  </div>
  <div class="field">
    <label for="customer_addr2">Addr2</label>
    <input class="form-control" id="customer_addr2" name="customer[addr2]" type="text" />
  </div>
  <div class="field">
    <label for="customer_city">City</label>
    <input class="form-control" id="customer_city" name="customer[city]" type="text" />
  </div>
  <div class="field">
    <label for="customer_pincode">Pincode</label>
    <input class="form-control" id="customer_pincode" name="customer[pincode]" type="text" />
  </div>
  <div class="field">
    <label for="customer_homephone">Homephone</label>
    <input class="form-control" id="customer_homephone" name="customer[homephone]" type="text" />
  </div>
  <div class="field">
    <label for="customer_mobile">Mobile</label>
    <input class="form-control" id="customer_mobile" name="customer[mobile]" type="text" />
  </div>
  <div class="actions">
    <input class="btn btn-primary btn-large btn-block" name="commit" type="submit" value="Create Customer" />
  </div>
</form>
</div>

You can see the working example here... http://jsfiddle.net/s6Ujm/

PS: I am a beginner too, pro designers... feel free share your reviews.

ResourceDictionary in a separate assembly

For UWP:

<ResourceDictionary Source="ms-appx:///##Namespace.External.Assembly##/##FOLDER##/##FILE##.xaml" />

Angular 2 Unit Tests: Cannot find name 'describe'

In my case, the solution was to remove the typeRoots in my tsconfig.json.

As you can read in the TypeScript doc

If typeRoots is specified, only packages under typeRoots will be included.

BOOLEAN or TINYINT confusion

As of MySql 5.1 version reference

BIT(M) =  approximately (M+7)/8 bytes, 
BIT(1) =  (1+7)/8 = 1 bytes (8 bits)

=========================================================================

TINYINT(1) take 8 bits.

https://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html#data-types-storage-reqs-numeric

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Can I change a column from NOT NULL to NULL without dropping it?

Sure you can.

ALTER TABLE myTable ALTER COLUMN myColumn int NULL

Just substitute int for whatever datatype your column is.

How to remove an item from an array in AngularJS scope?

Angular have a built-in function called arrayRemove, in your case the method can simply be:

arrayRemove($scope.persons, person)

How do I check if a variable exists?

for objects/modules, you can also

'var' in dir(obj)

For example,

>>> class Something(object):
...     pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False

Understanding unique keys for array children in React.js

I was running into this error message because of <></> being returned for some items in the array when instead null needs to be returned.

Handling errors in Promise.all

Promise.all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.

Some libraries have something called Promise.when, which I understand would instead wait for all promises in the array to either resolve or reject, but I'm not familiar with it, and it's not in ES6.

Your code

I agree with others here that your fix should work. It should resolve with an array that may contain a mix of successful values and errors objects. It's unusual to pass error objects in the success-path but assuming your code is expecting them, I see no problem with it.

The only reason I can think of why it would "not resolve" is that it's failing in code you're not showing us and the reason you're not seeing any error message about this is because this promise chain is not terminated with a final catch (as far as what you're showing us anyway).

I've taken the liberty of factoring out the "existing chain" from your example and terminating the chain with a catch. This may not be right for you, but for people reading this, it's important to always either return or terminate chains, or potential errors, even coding errors, will get hidden (which is what I suspect happened here):

Promise.all(state.routes.map(function(route) {
  return route.handler.promiseHandler().catch(function(err) {
    return err;
  });
}))
.then(function(arrayOfValuesOrErrors) {
  // handling of my array containing values and/or errors. 
})
.catch(function(err) {
  console.log(err.message); // some coding error in handling happened
});

How can I get my Android device country code without using GPS?

I have created a utility function (tested once on a device where I was getting an incorrect country code based on locale).

Reference: CountryCodePicker.java

fun getDetectedCountry(context: Context, defaultCountryIsoCode: String): String {

    detectSIMCountry(context)?.let {
        return it
    }

    detectNetworkCountry(context)?.let {
        return it
    }

    detectLocaleCountry(context)?.let {
        return it
    }

    return defaultCountryIsoCode
}

private fun detectSIMCountry(context: Context): String? {
    try {
        val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        Log.d(TAG, "detectSIMCountry: ${telephonyManager.simCountryIso}")
        return telephonyManager.simCountryIso
    }
    catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

private fun detectNetworkCountry(context: Context): String? {
    try {
        val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        Log.d(TAG, "detectNetworkCountry: ${telephonyManager.simCountryIso}")
        return telephonyManager.networkCountryIso
    }
    catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

private fun detectLocaleCountry(context: Context): String? {
    try {
        val localeCountryISO = context.getResources().getConfiguration().locale.getCountry()
        Log.d(TAG, "detectNetworkCountry: $localeCountryISO")
        return localeCountryISO
    }
    catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

How to do a num_rows() on COUNT query in codeigniter?

num_rows on your COUNT() query will literally ALWAYS be 1. It is an aggregate function without a GROUP BY clause, so all rows are grouped together into one. If you want the value of the count, you should give it an identifier SELECT COUNT(*) as myCount ..., then use your normal method of accessing a result (the first, only result) and get it's 'myCount' property.

HtmlSpecialChars equivalent in Javascript?

Reversed one:

function decodeHtml(text) {
    return text
        .replace(/&amp;/g, '&')
        .replace(/&lt;/ , '<')
        .replace(/&gt;/, '>')
        .replace(/&quot;/g,'"')
        .replace(/&#039;/g,"'");
}

Convert string in base64 to image and save on filesystem in Python

You can use Pillow.

pip install Pillow



image = base64.b64decode(str(base64String))       
fileName = 'test.jpeg'

imagePath = FILE_UPLOAD_DIR + fileName

img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
return fileName

reference for complete source code: https://abhisheksharma.online/convert-base64-blob-to-image-file-in-python/

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

There is also th:classappend.

<a href="" class="baseclass" th:classappend="${isAdmin} ? adminclass : userclass"></a>

If isAdmin is true, then this will result in:

<a href="" class="baseclass adminclass"></a>

Developing C# on Linux

Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.

As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.

Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

You can use Floern's solution. You may also want to disable the input while you set the color to gray. http://www.w3schools.com/tags/att_input_disabled.asp

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

It seems daft, but I think when you use the same bind variable twice you have to set it twice:

cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");

Certainly that's true with Native Dynamic SQL in PL/SQL:

SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name'
  3     using 'KING';
  4  end;
  5  /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound


SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name' 
  3     using 'KING', 'KING';
  4  end;
  5  /

PL/SQL procedure successfully completed.

Calling Member Functions within Main C++

declare it "static" like this:

static void MyClass::printInformation() { return; }

Internet Access in Ubuntu on VirtualBox

I had a similar issue in windows 7 + ubuntu 12.04 as guest. I resolved by

  • open 'network and sharing center' in windows
  • right click 'nw-bridge' -> 'properties'
  • Select "virtual box host only network" for the option "select adapters you want to use to connect computers on your local network"
  • go to virtual box.. select the network type as NAT.

List of All Folders and Sub-folders

find . -type d > list.txt

Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the . to that other path.

If you want to exclude certain directories, you can filter them out with a negative condition:

find . -type d ! -name "~snapshot" > list.txt

How to preventDefault on anchor tags?

Borrowing from tennisgent's answer. I like that you don't have to create a custom directive to add on all the links. However, I couldnt get his to work in IE8. Here's what finally worked for me (using angular 1.0.6).

Notice that 'bind' allows you to use jqLite provided by angular so no need to wrap with full jQuery. Also required the stopPropogation method.

.directive('a', [
    function() {
        return {
            restrict: 'E',
            link: function(scope, elem, attrs) {

                elem.bind('click', function(e){
                    if (attrs.ngClick || attrs.href === '' || attrs.href == '#'){
                        e.preventDefault();
                        e.stopPropagation();
                    }
                })
            }
        };
    }
])

Can't change z-index with JQuery

zIndex is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index.

you forgot .css("attr","value"). use ' or " in both, attr and val. so, .css("z-index","3000");

Ubuntu: OpenJDK 8 - Unable to locate package

I was having the same issue and tried all of the solutions on this page but none of them did the trick.

What finally worked was adding the universe repo to my repo list. To do that run the following command

sudo add-apt-repository universe

After running the above command I was able to run

sudo apt install openjdk-8-jre

without an issue and the package was installed.

Hope this helps someone.

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

The way to check a HDFS directory's size?

With this you will get size in GB

hdfs dfs -du PATHTODIRECTORY | awk '/^[0-9]+/ { print int($1/(1024**3)) " [GB]\t" $2 }'

Why do I get a warning icon when I add a reference to an MEF plugin project?

For both of (or all of) the projects that you want to use together:

Right click on the project > Properties > Application > Target .NET framework

Make sure that both of (or all of) your projects are using the same .NET framework version.

How to generate unique IDs for form labels in React?

Following up as of 2019-04-04, this seems to be able to be accomplished with the React Hooks' useState:

import React, { useState } from 'react'
import uniqueId from 'lodash/utility/uniqueId'

const Field = props => {
  const [ id ] = useState(uniqueId('myprefix-'))

  return (
    <div>
      <label htmlFor={id}>{props.label}</label>
      <input id={id} type="text"/>
    </div>
  )      
}

export default Field

As I understand it, you ignore the second array item in the array destructuring that would allow you to update id, and now you've got a value that won't be updated again for the life of the component.

The value of id will be myprefix-<n> where <n> is an incremental integer value returned from uniqueId. If that's not unique enough for you, consider making your own like

function gen4() {
  return Math.random().toString(16).slice(-4)
}

function simpleUniqueId(prefix) {
  return (prefix || '').concat([
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4(),
    gen4()
  ].join(''))
}

or check out the library I published with this here: https://github.com/rpearce/simple-uniqueid. There are also hundreds or thousands of other unique ID things out there, but lodash's uniqueId with a prefix should be enough to get the job done.


Update 2019-07-10

Thanks to @Huong Hk for pointing me to hooks lazy initial state, the sum of which is that you can pass a function to useState that will only be run on the initial mount.

// before
const [ id ] = useState(uniqueId('myprefix-'))

// after
const [ id ] = useState(() => uniqueId('myprefix-'))

How to convert date format to DD-MM-YYYY in C#

The problem is that you're trying to convert a string, so first you should cast your variable to date and after that apply something like
string date = variableConvertedToDate.ToString("dd-MM-yyyy")
or
string date = variableConvertedToDate.ToShortDateString() in this case result is dd/MM/yyyy.

Vue js error: Component template should contain exactly one root element

Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

The right approach is

<template>
  <div> <!-- The root -->
    <p></p> 
    <p></p>
  </div>
</template>

The wrong approach

<template> <!-- No root Element -->
    <p></p> 
    <p></p>
</template>

Multi Root Components

The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.

As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this anymore and everything is passed with context.

Here is how you can create a simple functional component.

Vue.component('my-component', {
    // you must set functional as true
  functional: true,
  // Props are optional
  props: {
    // ...
  },
  // To compensate for the lack of an instance,
  // we are now provided a 2nd context argument.
  render: function (createElement, context) {
    // ...
  }
})

Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.

<template>
 <ul>
     <NavBarRoutes :routes="persistentNavRoutes"/>
     <NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
     <NavBarRoutes v-else :routes="loggedOutNavRoutes" />
 </ul>
</template>

Now if we take a look at NavBarRoutes template

<template>
 <li
 v-for="route in routes"
 :key="route.name"
 >
 <router-link :to="route">
 {{ route.title }}
 </router-link>
 </li>
</template>

We cant do some thing like this we will be violating single root component restriction

Solution Make this component functional and use render

{
functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  <li key={route.name}>
    <router-link to={route}>
      {route.title}
    </router-link>
  </li>
 )
}

Here you have it you have created a multi root component, Happy coding

Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/

How to Convert datetime value to yyyymmddhhmmss in SQL server?

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

How to use clock() in C++

clock() returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:

clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;

System.Net.WebException: The operation has timed out

proxy issue can cause this. IIS webconfig put this in

<defaultProxy useDefaultCredentials="true" enabled="true">
          <proxy usesystemdefault="True" />
        </defaultProxy>

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

The name 'controlname' does not exist in the current context

Solution option #2 offered above works for windows forms applications and not web aspx application. I got similar error in web application, I resolved this by deleting a file where I had a user control by the same name, this aspx file was actually a backup file and was not referenced anywhere in the process, but still it caused the error because the name of user control registered on the backup file was named exactly same on the aspx file which was referenced in process flow. So I deleted the backup file and built solution, build succeeded.

Hope this helps some one in similar scenario.

Vijaya Laxmi.

How to do a SOAP wsdl web services call from the command line

For Windows users looking for a PowerShell alternative, here it is (using POST). I've split it up onto multiple lines for readability.

$url = 'https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc'
$headers = @{
    'Content-Type' = 'text/xml';
    'SOAPAction' = 'http://api.eyeblaster.com/IAuthenticationService/ClientLogin'
}
$envelope = @'
    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
        <Body>
            <yourEnvelopeContentsHere/>
        </Body>
    </Envelope>
'@     # <--- This line must not be indented

Invoke-WebRequest -Uri $url -Headers $headers -Method POST -Body $envelope

Does mobile Google Chrome support browser extensions?

You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.

I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.

To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.

edit

Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.

I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...

and it works in chrome whatever platform I am currently logged on to.

C# create simple xml file

I'd recommend serialization,

public class Person
{
      public  string FirstName;
      public  string MI;
      public  string LastName;
}

static void Serialize()
{
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine();
      System.Console.WriteLine(" --- Press any key to continue --- ");
      System.Console.ReadKey();
}

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("Java"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("C#"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

And if it needs to be fast, use XmlWriter:

public static void WriteXML()
{
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("books");

        for (int i = 0; i < 100; ++i)
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("item", "Book "+ (i+1).ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
    } // End Using writer 

}

And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
{
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
    {
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
            {
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
            }

        } // Whend 

    } // End Using xmlReader

    System.Console.ReadKey();
}

And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

I had the same problem. I uninstalled the 6.8.14 and installed back older version 5.6.8, and it worked.

Error: Cannot find module 'webpack'

Seems to be a common Windows problem. This fixed it for me:

Nodejs cannot find installed module on Windows?

"Add an environment variable called NODE_PATH and set it to %USERPROFILE%\Application Data\npm\node_modules (Windows XP), %AppData%\npm\node_modules (Windows 7), or wherever npm ends up installing the modules on your Windows flavor. To be done with it once and for all, add this as a System variable in the Advanced tab of the System Properties dialog (run control.exe sysdm.cpl,System,3)."

Note that you can't actually use another environment variable within the value of NODE_PATH. That is, don't just copy and paste that string above, but set it to an actual resolved path like C:\Users\MYNAME\AppData\Roaming\npm\node_modules

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

How can you dynamically create variables via a while loop?

NOTE: This should be considered a discussion rather than an actual answer.

An approximate approach is to operate __main__ in the module you want to create variables. For example there's a b.py:

#!/usr/bin/env python
# coding: utf-8


def set_vars():
    import __main__
    print '__main__', __main__
    __main__.B = 1

try:
    print B
except NameError as e:
    print e

set_vars()

print 'B: %s' % B

Running it would output

$ python b.py
name 'B' is not defined
__main__ <module '__main__' from 'b.py'>
B: 1

But this approach only works in a single module script, because the __main__ it import will always represent the module of the entry script being executed by python, this means that if b.py is involved by other code, the B variable will be created in the scope of the entry script instead of in b.py itself. Assume there is a script a.py:

#!/usr/bin/env python
# coding: utf-8

try:
    import b
except NameError as e:
    print e

print 'in a.py: B', B

Running it would output

$ python a.py
name 'B' is not defined
__main__ <module '__main__' from 'a.py'>
name 'B' is not defined
in a.py: B 1

Note that the __main__ is changed to 'a.py'.

Get form data in ReactJS

An easy way to deal with refs:

_x000D_
_x000D_
class UserInfo extends React.Component {_x000D_
_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
    this.handleSubmit = this.handleSubmit.bind(this);_x000D_
  }_x000D_
_x000D_
  handleSubmit(e) {_x000D_
    e.preventDefault();_x000D_
    _x000D_
    const formData = {};_x000D_
    for (const field in this.refs) {_x000D_
      formData[field] = this.refs[field].value;_x000D_
    }_x000D_
    console.log('-->', formData);_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
        <div>_x000D_
          <form onSubmit={this.handleSubmit}>_x000D_
            <input ref="phone" className="phone" type='tel' name="phone"/>_x000D_
            <input ref="email" className="email" type='tel' name="email"/>_x000D_
            <input type="submit" value="Submit"/>_x000D_
          </form>_x000D_
        </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
export default UserInfo;
_x000D_
_x000D_
_x000D_

Regular expression to find URLs within a string

This is a simplest one. which work for me fine.

%(http|ftp|https|www)(://|\.)[A-Za-z0-9-_\.]*(\.)[a-z]*%

What are the differences between a program and an application?

My understanding is this:

  • A computer program is a set of instructions that can be executed on a computer.
  • An application is software that directly helps a user perform tasks.
  • The two intersect, but are not synonymous. A program with a user-interface is an application, but many programs are not applications.

Each for object?

_x000D_
_x000D_
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
  console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

//output
a: 1
b: 2

Why is "forEach not a function" for this object?

When I tried to access the result from

Object.keys(a).forEach(function (key){ console.log(a[key]); });

it was plain text result with no key-value pairs Here is an example

var fruits = {
    apple: "fruits/apple.png",
    banana: "fruits/banana.png",
    watermelon: "watermelon.jpg",
    grapes: "grapes.png",
    orange: "orange.jpg"
}

Now i want to get all links in a separated array , but with this code

    function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
    console.log('\"'+obJect[x]+'\"');
});
}

the result of :

linksOfPics(fruits)



"fruits/apple.png"
 "fruits/banana.png"
 "watermelon.jpg"
 "grapes.png"
 "orange.jpg"
undefined

I figured out this one which solves what I'm looking for

  console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]

How to filter (key, value) with ng-repeat in AngularJs?

My solution would be create custom filter and use it:

app.filter('with', function() {
  return function(items, field) {
        var result = {};
        angular.forEach(items, function(value, key) {
            if (!value.hasOwnProperty(field)) {
                result[key] = value;
            }
        });
        return result;
    };
});

And in html:

 <div ng-repeat="(k,v) in items | with:'secId'">
        {{k}} {{v.pos}}
 </div>

convert '1' to '0001' in JavaScript

This is a clever little trick (that I think I've seen on SO before):

var str = "" + 1
var pad = "0000"
var ans = pad.substring(0, pad.length - str.length) + str

JavaScript is more forgiving than some languages if the second argument to substring is negative so it will "overflow correctly" (or incorrectly depending on how it's viewed):

That is, with the above:

  • 1 -> "0001"
  • 12345 -> "12345"

Supporting negative numbers is left as an exercise ;-)

Happy coding.

Test if a variable is a list or tuple

if type(x) is list:
    print 'a list'
elif type(x) is tuple:
    print 'a tuple'
else:
    print 'neither a tuple or a list'

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

How to convert const char* to char* in C?

To be safe you don't break stuff (for example when these strings are changed in your code or further up), or crash you program (in case the returned string was literal for example like "hello I'm a literal string" and you start to edit it), make a copy of the returned string.

You could use strdup() for this, but read the small print. Or you can of course create your own version if it's not there on your platform.

CSS Classes & SubClasses

Just need to add a space:

.area2 .item
{
    ...
}

Is it possible to pull just one file in Git?

Here is a slightly easier method I just came up with when researching this:

git fetch {remote}
git checkout FETCH_HEAD -- {file}

Clear variable in python

I used a few options mentioned above :

del self.left

or setting value to None using

self.left = None

It's important to know the differences and put a few exception handlers in place when you use set the value to None. If you're printing the value of the conditional statements using a template, say,

print("The value of the variable is {}".format(self.left))

you might see the value of the variable printing "The value of the variable is None". Thus, you'd have to put a few exception handlers there :

if self.left:
    #Then only print stuff

The above command will only print values if self.left is not None

Quick way to retrieve user information Active Directory

You can call UserPrincipal.FindByIdentity inside System.DirectoryServices.AccountManagement:

using System.DirectoryServices.AccountManagement;

using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
    var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');
});

Also note that return true; is redundant in your logic, so it can be removed.

How to create a multiline UITextfield?

use UITextView instead of UITextField

Change bootstrap navbar collapse breakpoint without using LESS

This is what did the trick for me:

@media only screen and (min-width:769px) and (max-width:1000px){
.navbar-collapse.collapse {
    display: none !important;
}
.navbar-collapse.collapse.in {
    display: block !important;
}
.navbar-header .collapse, .navbar-toggle {
    display:block !important;
}

.NET Format a string with fixed spaces

Thanks for the discussion, this method also works (VB):

Public Function StringCentering(ByVal s As String, ByVal desiredLength As Integer) As String
    If s.Length >= desiredLength Then Return s
    Dim firstpad As Integer = (s.Length + desiredLength) / 2
    Return s.PadLeft(firstpad).PadRight(desiredLength)
End Function
  1. StringCentering() takes two input values and it returns a formatted string.
  2. When length of s is greater than or equal to deisredLength, the function returns the original string.
  3. When length of s is smaller than desiredLength, it will be padded both ends.
  4. Due to character spacing is integer and there is no half-space, we can have an uneven split of space. In this implementation, the greater split goes to the leading end.
  5. The function requires .NET Framework due to PadLeft() and PadRight().
  6. In the last line of the function, binding is from left to right, so firstpad is applied followed by the desiredLength pad.

Here is the C# version:

public string StringCentering(string s, int desiredLength)
{
    if (s.Length >= desiredLength) return s;
    int firstpad = (s.Length + desiredLength) / 2;
    return s.PadLeft(firstpad).PadRight(desiredLength);
}

To aid understanding, integer variable firstpad is used. s.PadLeft(firstpad) applies the (correct number of) leading white spaces. The right-most PadRight(desiredLength) has a lower binding finishes off by applying trailing white spaces.

How to add System.Windows.Interactivity to project?

I got it via the Prism.WPF NuGet-Package. (it includes Windows.System.Interactivity)

Python string.replace regular expression

You are looking for the re.sub function.

import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced 

will print axample atring

Combining "LIKE" and "IN" for SQL Server

No, MSSQL doesn't allow such queries. You should use col LIKE '...' OR col LIKE '...' etc.

How to take backup of a single table in a MySQL database?

You can either use mysqldump from the command line:

mysqldump -u username -p password dbname tablename > "path where you want to dump"

You can also use MySQL Workbench:

Go to left > Data Export > Select Schema > Select tables and click on Export

Most efficient way to see if an ArrayList contains an object in Java

Even if the equals method were comparing those two fields, then logically, it would be just the same code as you doing it manually. OK, it might be "messy", but it's still the correct answer

How to make CSS width to fill parent?

So after research the following is discovered:

For a div#bar setting display:block; width: auto; causes the equivalent of outerWidth:100%;

For a table#bar you need to wrap it in a div with the rules stated below. So your structure becomes:

<div id="foo">
 <div id="barWrap" style="border....">
  <table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">

This way the table takes up the parent div 100%, and #barWrap is used to add borders/margin/padding to the #bar table. Note that you will need to set the background of the whole thing in #barWrap and have #bar's background be transparent or the same as #barWrap.

For textarea#bar and input#bar you need to do the same thing as table#bar, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.

How to create PDFs in an Android app?

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

What is the Oracle equivalent of SQL Server's IsNull() function?

Instead of ISNULL(), use NVL().

T-SQL:

SELECT ISNULL(SomeNullableField, 'If null, this value') FROM SomeTable

PL/SQL:

SELECT NVL(SomeNullableField, 'If null, this value') FROM SomeTable

What is a mixin, and why are they useful?

OP mentioned that he/she never heard of mixin in C++, perhaps that is because they are called Curiously Recurring Template Pattern (CRTP) in C++. Also, @Ciro Santilli mentioned that mixin is implemented via abstract base class in C++. While abstract base class can be used to implement mixin, it is an overkill as the functionality of virtual function at run-time can be achieved using template at compile time without the overhead of virtual table lookup at run-time.

The CRTP pattern is described in detail here

I have converted the python example in @Ciro Santilli's answer into C++ using template class below:

    #include <iostream>
    #include <assert.h>

    template <class T>
    class ComparableMixin {
    public:
        bool operator !=(ComparableMixin &other) {
            return ~(*static_cast<T*>(this) == static_cast<T&>(other));
        }
        bool operator <(ComparableMixin &other) {
            return ((*(this) != other) && (*static_cast<T*>(this) <= static_cast<T&>(other)));
        }
        bool operator >(ComparableMixin &other) {
            return ~(*static_cast<T*>(this) <= static_cast<T&>(other));
        }
        bool operator >=(ComparableMixin &other) {
            return ((*static_cast<T*>(this) == static_cast<T&>(other)) || (*(this) > other));
        }
        protected:
            ComparableMixin() {}
    };

    class Integer: public ComparableMixin<Integer> {
    public:
     Integer(int i) {
         this->i = i;
     }
     int i;
     bool operator <=(Integer &other) {
         return (this->i <= other.i);
     }
     bool operator ==(Integer &other) {
         return (this->i == other.i);
     }
    };

int main() {

    Integer i(0) ;
    Integer j(1) ;
    //ComparableMixin<Integer> c; // this will cause compilation error because constructor is protected.
    assert (i < j );
    assert (i != j);
    assert (j >  i);
    assert (j >= i);

    return 0;
}

EDIT: Added protected constructor in ComparableMixin so that it can only be inherited and not instantiated. Updated the example to show how protected constructor will cause compilation error when an object of ComparableMixin is created.

Include files from parent or other directory

I can't believe none of the answers pointed to the function dirname() (available since PHP 4).

Basically, it returns the full path for the referenced object. If you use a file as a reference, the function returns the full path of the file. If the referenced object is a folder, the function will return the parent folder of that folder.

https://www.php.net/manual/en/function.dirname.php

For the current folder of the current file, use $current = dirname(__FILE__);.

For a parent folder of the current folder, simply use $parent = dirname(__DIR__);.

Where is debug.keystore in Android Studio

On Windows,

All you need to do is goto command prompt and cd C:\Program Files\Java\jdk-10.0.2\bin>where jdk-10.0.2 or full path can be different in your case. once you are in the bin, enter this code keytool -keystore C:\Users\GB\.android/debug.keystore -list -v where C:\Users\GB\.android/debug.keystore is path to keystore in my case.

You will get results like this.

enter image description here

jQuery remove options from select

It works on either option tag or text field:

$("#idname option[value='option1']").remove();

What is the difference between IEnumerator and IEnumerable?

IEnumerable and IEnumerator are both interfaces. IEnumerable has just one method called GetEnumerator. This method returns (as all methods return something including void) another type which is an interface and that interface is IEnumerator. When you implement enumerator logic in any of your collection class, you implement IEnumerable (either generic or non generic). IEnumerable has just one method whereas IEnumerator has 2 methods (MoveNext and Reset) and a property Current. For easy understanding consider IEnumerable as a box that contains IEnumerator inside it (though not through inheritance or containment). See the code for better understanding:

class Test : IEnumerable, IEnumerator
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    public object Current
    {
        get { throw new NotImplementedException(); }
    }

    public bool MoveNext()
    {
        throw new NotImplementedException();
    }

    public void Reset()
    {
        throw new NotImplementedException();
    }
}

How to check for a Null value in VB.NET

If Not editTransactionRow.pay_id AndAlso String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
    stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If

Detect Windows version in .net

How about using a Registry to get the name.

"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" has a value ProductName since Windows XP.

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();

[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string moduleName);

[DllImport("kernel32")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

[DllImport("kernel32.dll")]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);

public static bool Is64BitOperatingSystem()
{
    // Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.
    if (IntPtr.Size == 8)
        return true;
    // Check if this process is an x86 process running on an x64 environment.
    IntPtr moduleHandle = GetModuleHandle("kernel32");
    if (moduleHandle != IntPtr.Zero)
    {
        IntPtr processAddress = GetProcAddress(moduleHandle, "IsWow64Process");
        if (processAddress != IntPtr.Zero)
        {
            bool result;
            if (IsWow64Process(GetCurrentProcess(), out result) && result)
                return true;
        }
    }
    // The environment must be an x86 environment.
    return false;
}

private static string HKLM_GetString(string key, string value)
{
    try
    {
        RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(key);
        return registryKey?.GetValue(value).ToString() ?? String.Empty;
    }
    catch
    {
        return String.Empty;
    }
}

public static string GetWindowsVersion()
{
    string osArchitecture;
    try
    {
        osArchitecture = Is64BitOperatingSystem() ? "64-bit" : "32-bit";
    }
    catch (Exception)
    {
        osArchitecture = "32/64-bit (Undetermined)";
    }
    string productName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
    string csdVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");
    string currentBuild = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuild");
    if (!string.IsNullOrEmpty(productName))
    {
        return
            $"{productName}{(!string.IsNullOrEmpty(csdVersion) ? " " + csdVersion : String.Empty)} {osArchitecture} (OS Build {currentBuild})";
    }
    return String.Empty;
}

If you are using .NET Framework 4.0 or above. You can remove the Is64BitOperatingSystem() method and use Environment.Is64BitOperatingSystem.

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;

Efficient way to remove ALL whitespace from String?

Building on Henks answer I have created some test methods with his answer and some added, more optimized, methods. I found the results differ based on the size of the input string. Therefore, I have tested with two result sets. In the fastest method, the linked source has a even faster way. But, since it is characterized as unsafe I have left this out.

Long input string results:

  1. InPlaceCharArray: 2021 ms (Sunsetquest's answer) - (Original source)
  2. String split then join: 4277ms (Kernowcode's answer)
  3. String reader: 6082 ms
  4. LINQ using native char.IsWhitespace: 7357 ms
  5. LINQ: 7746 ms (Henk's answer)
  6. ForLoop: 32320 ms
  7. RegexCompiled: 37157 ms
  8. Regex: 42940 ms

Short input string results:

  1. InPlaceCharArray: 108 ms (Sunsetquest's answer) - (Original source)
  2. String split then join: 294 ms (Kernowcode's answer)
  3. String reader: 327 ms
  4. ForLoop: 343 ms
  5. LINQ using native char.IsWhitespace: 624 ms
  6. LINQ: 645ms (Henk's answer)
  7. RegexCompiled: 1671 ms
  8. Regex: 2599 ms

Code:

public class RemoveWhitespace
{
    public static string RemoveStringReader(string input)
    {
        var s = new StringBuilder(input.Length); // (input.Length);
        using (var reader = new StringReader(input))
        {
            int i = 0;
            char c;
            for (; i < input.Length; i++)
            {
                c = (char)reader.Read();
                if (!char.IsWhiteSpace(c))
                {
                    s.Append(c);
                }
            }
        }

        return s.ToString();
    }

    public static string RemoveLinqNativeCharIsWhitespace(string input)
    {
        return new string(input.ToCharArray()
            .Where(c => !char.IsWhiteSpace(c))
            .ToArray());
    }

    public static string RemoveLinq(string input)
    {
        return new string(input.ToCharArray()
            .Where(c => !Char.IsWhiteSpace(c))
            .ToArray());
    }

    public static string RemoveRegex(string input)
    {
        return Regex.Replace(input, @"\s+", "");
    }

    private static Regex compiled = new Regex(@"\s+", RegexOptions.Compiled);
    public static string RemoveRegexCompiled(string input)
    {
        return compiled.Replace(input, "");
    }

    public static string RemoveForLoop(string input)
    {
        for (int i = input.Length - 1; i >= 0; i--)
        {
            if (char.IsWhiteSpace(input[i]))
            {
                input = input.Remove(i, 1);
            }
        }
        return input;
    }

    public static string StringSplitThenJoin(this string str)
    {
        return string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
    }

    public static string RemoveInPlaceCharArray(string input)
    {
        var len = input.Length;
        var src = input.ToCharArray();
        int dstIdx = 0;
        for (int i = 0; i < len; i++)
        {
            var ch = src[i];
            switch (ch)
            {
                case '\u0020':
                case '\u00A0':
                case '\u1680':
                case '\u2000':
                case '\u2001':
                case '\u2002':
                case '\u2003':
                case '\u2004':
                case '\u2005':
                case '\u2006':
                case '\u2007':
                case '\u2008':
                case '\u2009':
                case '\u200A':
                case '\u202F':
                case '\u205F':
                case '\u3000':
                case '\u2028':
                case '\u2029':
                case '\u0009':
                case '\u000A':
                case '\u000B':
                case '\u000C':
                case '\u000D':
                case '\u0085':
                    continue;
                default:
                    src[dstIdx++] = ch;
                    break;
            }
        }
        return new string(src, 0, dstIdx);
    }
}

Tests:

[TestFixture]
public class Test
{
    // Short input
    //private const string input = "123 123 \t 1adc \n 222";
    //private const string expected = "1231231adc222";

    // Long input
    private const string input = "123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222123 123 \t 1adc \n 222";
    private const string expected = "1231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc2221231231adc222";

    private const int iterations = 1000000;

    [Test]
    public void RemoveInPlaceCharArray()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.RemoveInPlaceCharArray(input);
        }

        stopwatch.Stop();
        Console.WriteLine("InPlaceCharArray: " + stopwatch.ElapsedMilliseconds + " ms");
        Assert.AreEqual(expected, s);
    }

    [Test]
    public void RemoveStringReader()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.RemoveStringReader(input);
        }

        stopwatch.Stop();
        Console.WriteLine("String reader: " + stopwatch.ElapsedMilliseconds + " ms");
        Assert.AreEqual(expected, s);
    }

    [Test]
    public void RemoveLinqNativeCharIsWhitespace()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.RemoveLinqNativeCharIsWhitespace(input);
        }

        stopwatch.Stop();
        Console.WriteLine("LINQ using native char.IsWhitespace: " + stopwatch.ElapsedMilliseconds + " ms");
        Assert.AreEqual(expected, s);
    }

    [Test]
    public void RemoveLinq()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.RemoveLinq(input);
        }

        stopwatch.Stop();
        Console.WriteLine("LINQ: " + stopwatch.ElapsedMilliseconds + " ms");
        Assert.AreEqual(expected, s);
    }

    [Test]
    public void RemoveRegex()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.RemoveRegex(input);
        }

        stopwatch.Stop();
        Console.WriteLine("Regex: " + stopwatch.ElapsedMilliseconds + " ms");

        Assert.AreEqual(expected, s);
    }

    [Test]
    public void RemoveRegexCompiled()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.RemoveRegexCompiled(input);
        }

        stopwatch.Stop();
        Console.WriteLine("RegexCompiled: " + stopwatch.ElapsedMilliseconds + " ms");

        Assert.AreEqual(expected, s);
    }

    [Test]
    public void RemoveForLoop()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.RemoveForLoop(input);
        }

        stopwatch.Stop();
        Console.WriteLine("ForLoop: " + stopwatch.ElapsedMilliseconds + " ms");

        Assert.AreEqual(expected, s);
    }

    [TestMethod]
    public void StringSplitThenJoin()
    {
        string s = null;
        var stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            s = RemoveWhitespace.StringSplitThenJoin(input);
        }

        stopwatch.Stop();
        Console.WriteLine("StringSplitThenJoin: " + stopwatch.ElapsedMilliseconds + " ms");

        Assert.AreEqual(expected, s);
    }
}

Edit: Tested a nice one liner from Kernowcode.

Converting string to Date and DateTime

$d = new DateTime('10-16-2003');

$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16

Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.

Check date between two other dates spring data jpa

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

Excel VBA - select a dynamic cell range

If you want to select a variable range containing all headers cells:

Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")

'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST

sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select

...as long as there's no other content on that row.

EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference.

Simple DateTime sql query

Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :

  1. Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.

  2. Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

You're probably missing some dependencies.

Locate the dependencies you're missing with mvn dependency:tree, then install them manually, and build your project with the -o (offline) option.

Where can I find error log files?

On CentoS with cPanel installed my logs were in:

/usr/local/apache/logs/error_log

To watch: tail -f /usr/local/apache/logs/error_log

How to save password when using Subversion from the console

Please note the following paragraph from the ~/.subversion/servers file:

Both 'store-passwords' and 'store-auth-creds' can now be specified in the 'servers' file in your config directory. Anything specified in this section is overridden by settings specified in the 'servers' file.

It is at least for SVN version 1.6.12. So keep in mind to edit the servers file also as it overrides ~/.subversion/config.

Binding arrow keys in JS/jQuery

Instead of using return false; as in the examples above, you can use e.preventDefault(); which does the same but is easier to understand and read.

Cannot implicitly convert type 'int?' to 'int'.

Check the declaration of your variable. It must be like that

public Nullable<int> x {get; set;}
public Nullable<int> y {get; set;}
public Nullable<int> z {get { return x*y;} }

I hope it is useful for you

json call with C#

Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this. Link 1 and Link 2

Code that works(unit tested)

           //Get Example
            var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "GET";

            var username = "usernameForYourApi";
            var password = "passwordForYourApi";

            var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
            var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
            using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
            }


            //Post Example
            var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
            httpWebRequestPost.ContentType = "application/json";
            httpWebRequestPost.Method = "POST";
            bytes = Encoding.UTF8.GetBytes(username + ":" + password);
            httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));

            //POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
            //json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
            // fill File model with some test data
            CSharpComplexClass fileModel = new CSharpComplexClass();
            fileModel.CarrierID = 2;
            fileModel.InvoiceFileDate = DateTime.Now;
            fileModel.EntryMethodID = EntryMethod.Manual;
            fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
            fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
            string json = new JavaScriptSerializer().Serialize(fileModel);
            Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
            byte[] byteArray = Encoding.UTF8.GetBytes(json);
            httpWebRequestPost.ContentLength = byteArray.Length;
            // Get the request stream.  
            Stream dataStream = httpWebRequestPost.GetRequestStream();
            // Write the data to the request stream.  
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.  
            dataStream.Close();
            // Get the response.  
            WebResponse response = httpWebRequestPost.GetResponse();
            // Display the status.  
            //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
            // Get the stream containing content returned by the server.  
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.  
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.  
            string responseFromServer = reader.ReadToEnd();
            Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);

References in my test script task inside BIDS 2008(having SP1 and 3.5 framework) enter image description here

Plot multiple lines in one graph

Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:

tab<-read.delim(text="
Company 2011 2013
Company1 300 350
Company2 320 430
Company3 310 420
",as.is=TRUE,sep=" ",row.names=1)

tab<-t(tab)

plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n")
lines(tab[,2],type="b",col="black",lty=2,lwd=2)
lines(tab[,3],type="b",col="blue",lty=3,lwd=2)
grid()
legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2)
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

R multiple lines plot

Makefile If-Then Else and Loops

Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

What is the correct way to free memory in C#

  1. Yes
  2. What do you mean by the same? It will be re-executed every time the method is run.
  3. Yes, the .Net garbage collector uses an algorithm that starts with any global/in-scope variables, traverses them while following any reference it finds recursively, and deletes any object in memory deemed to be unreachable. see here for more detail on Garbage Collection
  4. Yes, the memory from all variables declared in a method is released when the method exits as they are all unreachable. In addition, any variables that are declared but never used will be optimized out by the compiler, so in reality your Foo variable will never ever take up memory.
  5. the using statement simply calls dispose on an IDisposable object when it exits, so this is equivalent to your second bullet point. Both will indicate that you are done with the object and tell the GC that you are ready to let go of it. Overwriting the only reference to the object will have a similar effect.

How to redirect stderr and stdout to different files in the same line in script?

Multiple commands' output can be redirected. This works for either the command line or most usefully in a bash script. The -s directs the password prompt to the screen.

Hereblock cmds stdout/stderr are sent to seperate files and nothing to display.

sudo -s -u username <<'EOF' 2>err 1>out
ls; pwd;
EOF

Hereblock cmds stdout/stderr are sent to a single file and display.

sudo -s -u username <<'EOF' 2>&1 | tee out
ls; pwd;
EOF

Hereblock cmds stdout/stderr are sent to separate files and stdout to display.

sudo -s -u username <<'EOF' 2>err | tee out
ls; pwd;
EOF

Depending on who you are(whoami) and username a password may or may not be required.

How do I create a folder in a GitHub repository?

First you have to clone the repository to you local machine

git clone github_url local_directory

Then you can create local folders and files inside your local_directory, and add them to the repository using:

git add file_path

You can also add everything using:

git add .

Note that Git does not track empty folders. A workaround is to create a file inside the empty folder you want to track. I usually name that file empty, but it can be whatever name you choose.

Finally, you commit and push back to GitHub:

git commit
git push

For more information on Git, check out the Pro Git book.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

First of all, please vote and comment on the API request on the .NET repo.

Here's my optimized version of the ObservableRangeCollection (optimized version of James Montemagno's one).

It performs very fast and is meant to reuse existing elements when possible and avoid unnecessary events, or batching them into one, when possible. The ReplaceRange method replaces/removes/adds the required elements by the appropriate indices and batches the possible events.

Tested on Xamarin.Forms UI with great results for very frequent updates to the large collection (5-7 updates per second).

Note: Since WPF is not accustomed to work with range operations, it will throw a NotSupportedException, when using the ObservableRangeCollection from below in WPF UI-related work, such as binding it to a ListBox etc. (you can still use the ObservableRangeCollection<T> if not bound to UI).
However you can use the WpfObservableRangeCollection<T> workaround.
The real solution would be creating a CollectionView that knows how to deal with range operations, but I still didn't have the time to implement this.

RAW Code - open as Raw, then do Ctrl+A to select all, then Ctrl+C to copy.

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;

namespace System.Collections.ObjectModel
{
  /// <summary>
  /// Implementation of a dynamic data collection based on generic Collection&lt;T&gt;,
  /// implementing INotifyCollectionChanged to notify listeners
  /// when items get added, removed or the whole list is refreshed.
  /// </summary>
  public class ObservableRangeCollection<T> : ObservableCollection<T>
  {
    //------------------------------------------------------
    //
    //  Private Fields
    //
    //------------------------------------------------------

    #region Private Fields    
    [NonSerialized]
    private DeferredEventsCollection _deferredEvents;
    #endregion Private Fields


    //------------------------------------------------------
    //
    //  Constructors
    //
    //------------------------------------------------------

    #region Constructors
    /// <summary>
    /// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
    /// </summary>
    public ObservableRangeCollection() { }

    /// <summary>
    /// Initializes a new instance of the ObservableCollection class that contains
    /// elements copied from the specified collection and has sufficient capacity
    /// to accommodate the number of elements copied.
    /// </summary>
    /// <param name="collection">The collection whose elements are copied to the new list.</param>
    /// <remarks>
    /// The elements are copied onto the ObservableCollection in the
    /// same order they are read by the enumerator of the collection.
    /// </remarks>
    /// <exception cref="ArgumentNullException"> collection is a null reference </exception>
    public ObservableRangeCollection(IEnumerable<T> collection) : base(collection) { }

    /// <summary>
    /// Initializes a new instance of the ObservableCollection class
    /// that contains elements copied from the specified list
    /// </summary>
    /// <param name="list">The list whose elements are copied to the new list.</param>
    /// <remarks>
    /// The elements are copied onto the ObservableCollection in the
    /// same order they are read by the enumerator of the list.
    /// </remarks>
    /// <exception cref="ArgumentNullException"> list is a null reference </exception>
    public ObservableRangeCollection(List<T> list) : base(list) { }

    #endregion Constructors

    //------------------------------------------------------
    //
    //  Public Methods
    //
    //------------------------------------------------------

    #region Public Methods

    /// <summary>
    /// Adds the elements of the specified collection to the end of the <see cref="ObservableCollection{T}"/>.
    /// </summary>
    /// <param name="collection">
    /// The collection whose elements should be added to the end of the <see cref="ObservableCollection{T}"/>.
    /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.
    /// </param>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void AddRange(IEnumerable<T> collection)
    {
      InsertRange(Count, collection);
    }

    /// <summary>
    /// Inserts the elements of a collection into the <see cref="ObservableCollection{T}"/> at the specified index.
    /// </summary>
    /// <param name="index">The zero-based index at which the new elements should be inserted.</param>
    /// <param name="collection">The collection whose elements should be inserted into the List<T>.
    /// The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param>                
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is not in the collection range.</exception>
    public void InsertRange(int index, IEnumerable<T> collection)
    {
      if (collection == null)
        throw new ArgumentNullException(nameof(collection));
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (index > Count)
        throw new ArgumentOutOfRangeException(nameof(index));

      if (collection is ICollection<T> countable)
      {
        if (countable.Count == 0)
        {
          return;
        }
      }
      else if (!ContainsAny(collection))
      {
        return;
      }

      CheckReentrancy();

      //expand the following couple of lines when adding more constructors.
      var target = (List<T>)Items;
      target.InsertRange(index, collection);

      OnEssentialPropertiesChanged();

      if (!(collection is IList list))
        list = new List<T>(collection);

      OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, list, index));
    }


    /// <summary> 
    /// Removes the first occurence of each item in the specified collection from the <see cref="ObservableCollection{T}"/>.
    /// </summary>
    /// <param name="collection">The items to remove.</param>        
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void RemoveRange(IEnumerable<T> collection)
    {
      if (collection == null)
        throw new ArgumentNullException(nameof(collection));

      if (Count == 0)
      {
        return;
      }
      else if (collection is ICollection<T> countable)
      {
        if (countable.Count == 0)
          return;
        else if (countable.Count == 1)
          using (IEnumerator<T> enumerator = countable.GetEnumerator())
          {
            enumerator.MoveNext();
            Remove(enumerator.Current);
            return;
          }
      }
      else if (!(ContainsAny(collection)))
      {
        return;
      }

      CheckReentrancy();

      var clusters = new Dictionary<int, List<T>>();
      var lastIndex = -1;
      List<T> lastCluster = null;
      foreach (T item in collection)
      {
        var index = IndexOf(item);
        if (index < 0)
        {
          continue;
        }

        Items.RemoveAt(index);

        if (lastIndex == index && lastCluster != null)
        {
          lastCluster.Add(item);
        }
        else
        {
          clusters[lastIndex = index] = lastCluster = new List<T> { item };
        }
      }

      OnEssentialPropertiesChanged();

      if (Count == 0)
        OnCollectionReset();
      else
        foreach (KeyValuePair<int, List<T>> cluster in clusters)
          OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster.Value, cluster.Key));

    }

    /// <summary>
    /// Iterates over the collection and removes all items that satisfy the specified match.
    /// </summary>
    /// <remarks>The complexity is O(n).</remarks>
    /// <param name="match"></param>
    /// <returns>Returns the number of elements that where </returns>
    /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
    public int RemoveAll(Predicate<T> match)
    {
      return RemoveAll(0, Count, match);
    }

    /// <summary>
    /// Iterates over the specified range within the collection and removes all items that satisfy the specified match.
    /// </summary>
    /// <remarks>The complexity is O(n).</remarks>
    /// <param name="index">The index of where to start performing the search.</param>
    /// <param name="count">The number of items to iterate on.</param>
    /// <param name="match"></param>
    /// <returns>Returns the number of elements that where </returns>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="match"/> is null.</exception>
    public int RemoveAll(int index, int count, Predicate<T> match)
    {
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (count < 0)
        throw new ArgumentOutOfRangeException(nameof(count));
      if (index + count > Count)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (match == null)
        throw new ArgumentNullException(nameof(match));

      if (Count == 0)
        return 0;

      List<T> cluster = null;
      var clusterIndex = -1;
      var removedCount = 0;

      using (BlockReentrancy())
      using (DeferEvents())
      {
        for (var i = 0; i < count; i++, index++)
        {
          T item = Items[index];
          if (match(item))
          {
            Items.RemoveAt(index);
            removedCount++;

            if (clusterIndex == index)
            {
              Debug.Assert(cluster != null);
              cluster.Add(item);
            }
            else
            {
              cluster = new List<T> { item };
              clusterIndex = index;
            }

            index--;
          }
          else if (clusterIndex > -1)
          {
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster, clusterIndex));
            clusterIndex = -1;
            cluster = null;
          }
        }

        if (clusterIndex > -1)
          OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, cluster, clusterIndex));
      }

      if (removedCount > 0)
        OnEssentialPropertiesChanged();

      return removedCount;
    }

    /// <summary>
    /// Removes a range of elements from the <see cref="ObservableCollection{T}"/>>.
    /// </summary>
    /// <param name="index">The zero-based starting index of the range of elements to remove.</param>
    /// <param name="count">The number of elements to remove.</param>
    /// <exception cref="ArgumentOutOfRangeException">The specified range is exceeding the collection.</exception>
    public void RemoveRange(int index, int count)
    {
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (count < 0)
        throw new ArgumentOutOfRangeException(nameof(count));
      if (index + count > Count)
        throw new ArgumentOutOfRangeException(nameof(index));

      if (count == 0)
        return;

      if (count == 1)
      {
        RemoveItem(index);
        return;
      }

      //Items will always be List<T>, see constructors
      var items = (List<T>)Items;
      List<T> removedItems = items.GetRange(index, count);

      CheckReentrancy();

      items.RemoveRange(index, count);

      OnEssentialPropertiesChanged();

      if (Count == 0)
        OnCollectionReset();
      else
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removedItems, index));
    }

    /// <summary> 
    /// Clears the current collection and replaces it with the specified collection,
    /// using the default <see cref="EqualityComparer{T}"/>.
    /// </summary>             
    /// <param name="collection">The items to fill the collection with, after clearing it.</param>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void ReplaceRange(IEnumerable<T> collection)
    {
      ReplaceRange(0, Count, collection, EqualityComparer<T>.Default);
    }

    /// <summary>
    /// Clears the current collection and replaces it with the specified collection,
    /// using the specified comparer to skip equal items.
    /// </summary>
    /// <param name="collection">The items to fill the collection with, after clearing it.</param>
    /// <param name="comparer">An <see cref="IEqualityComparer{T}"/> to be used
    /// to check whether an item in the same location already existed before,
    /// which in case it would not be added to the collection, and no event will be raised for it.</param>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
    public void ReplaceRange(IEnumerable<T> collection, IEqualityComparer<T> comparer)
    {
      ReplaceRange(0, Count, collection, comparer);
    }

    /// <summary>
    /// Removes the specified range and inserts the specified collection,
    /// ignoring equal items (using <see cref="EqualityComparer{T}.Default"/>).
    /// </summary>
    /// <param name="index">The index of where to start the replacement.</param>
    /// <param name="count">The number of items to be replaced.</param>
    /// <param name="collection">The collection to insert in that location.</param>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    public void ReplaceRange(int index, int count, IEnumerable<T> collection)
    {
      ReplaceRange(index, count, collection, EqualityComparer<T>.Default);
    }

    /// <summary>
    /// Removes the specified range and inserts the specified collection in its position, leaving equal items in equal positions intact.
    /// </summary>
    /// <param name="index">The index of where to start the replacement.</param>
    /// <param name="count">The number of items to be replaced.</param>
    /// <param name="collection">The collection to insert in that location.</param>
    /// <param name="comparer">The comparer to use when checking for equal items.</param>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception>
    /// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is out of range.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
    /// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
    public void ReplaceRange(int index, int count, IEnumerable<T> collection, IEqualityComparer<T> comparer)
    {
      if (index < 0)
        throw new ArgumentOutOfRangeException(nameof(index));
      if (count < 0)
        throw new ArgumentOutOfRangeException(nameof(count));
      if (index + count > Count)
        throw new ArgumentOutOfRangeException(nameof(index));

      if (collection == null)
        throw new ArgumentNullException(nameof(collection));
      if (comparer == null)
        throw new ArgumentNullException(nameof(comparer));

      if (collection is ICollection<T> countable)
      {
        if (countable.Count == 0)
        {
          RemoveRange(index, count);
          return;
        }
      }
      else if (!ContainsAny(collection))
      {
        RemoveRange(index, count);
        return;
      }

      if (index + count == 0)
      {
        InsertRange(0, collection);
        return;
      }

      if (!(collection is IList<T> list))
        list = new List<T>(collection);

      using (BlockReentrancy())
      using (DeferEvents())
      {
        var rangeCount = index + count;
        var addedCount = list.Count;

        var changesMade = false;
        List<T>
            newCluster = null,
            oldCluster = null;


        int i = index;
        for (; i < rangeCount && i - index < addedCount; i++)
        {
          //parallel position
          T old = this[i], @new = list[i - index];
          if (comparer.Equals(old, @new))
          {
            OnRangeReplaced(i, newCluster, oldCluster);
            continue;
          }
          else
          {
            Items[i] = @new;

            if (newCluster == null)
            {
              Debug.Assert(oldCluster == null);
              newCluster = new List<T> { @new };
              oldCluster = new List<T> { old };
            }
            else
            {
              newCluster.Add(@new);
              oldCluster.Add(old);
            }

            changesMade = true;
          }
        }

        OnRangeReplaced(i, newCluster, oldCluster);

        //exceeding position
        if (count != addedCount)
        {
          var items = (List<T>)Items;
          if (count > addedCount)
          {
            var removedCount = rangeCount - addedCount;
            T[] removed = new T[removedCount];
            items.CopyTo(i, removed, 0, removed.Length);
            items.RemoveRange(i, removedCount);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed, i));
          }
          else
          {
            var k = i - index;
            T[] added = new T[addedCount - k];
            for (int j = k; j < addedCount; j++)
            {
              T @new = list[j];
              added[j - k] = @new;
            }
            items.InsertRange(i, added);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, added, i));
          }

          OnEssentialPropertiesChanged();
        }
        else if (changesMade)
        {
          OnIndexerPropertyChanged();
        }
      }
    }

    #endregion Public Methods


    //------------------------------------------------------
    //
    //  Protected Methods
    //
    //------------------------------------------------------

    #region Protected Methods

    /// <summary>
    /// Called by base class Collection&lt;T&gt; when the list is being cleared;
    /// raises a CollectionChanged event to any listeners.
    /// </summary>
    protected override void ClearItems()
    {
      if (Count == 0)
        return;

      CheckReentrancy();
      base.ClearItems();
      OnEssentialPropertiesChanged();
      OnCollectionReset();
    }

    /// <summary>
    /// Called by base class Collection&lt;T&gt; when an item is set in list;
    /// raises a CollectionChanged event to any listeners.
    /// </summary>
    protected override void SetItem(int index, T item)
    {
      if (Equals(this[index], item))
        return;

      CheckReentrancy();
      T originalItem = this[index];
      base.SetItem(index, item);

      OnIndexerPropertyChanged();
      OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
    }

    /// <summary>
    /// Raise CollectionChanged event to any listeners.
    /// Properties/methods modifying this ObservableCollection will raise
    /// a collection changed event through this virtual method.
    /// </summary>
    /// <remarks>
    /// When overriding this method, either call its base implementation
    /// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
    /// </remarks>
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
      if (_deferredEvents != null)
      {
        _deferredEvents.Add(e);
        return;
      }
      base.OnCollectionChanged(e);
    }

    protected virtual IDisposable DeferEvents() => new DeferredEventsCollection(this);

    #endregion Protected Methods


    //------------------------------------------------------
    //
    //  Private Methods
    //
    //------------------------------------------------------

    #region Private Methods

    /// <summary>
    /// Helper function to determine if a collection contains any elements.
    /// </summary>
    /// <param name="collection">The collection to evaluate.</param>
    /// <returns></returns>
    private static bool ContainsAny(IEnumerable<T> collection)
    {
      using (IEnumerator<T> enumerator = collection.GetEnumerator())
        return enumerator.MoveNext();
    }

    /// <summary>
    /// Helper to raise Count property and the Indexer property.
    /// </summary>
    private void OnEssentialPropertiesChanged()
    {
      OnPropertyChanged(EventArgsCache.CountPropertyChanged);
      OnIndexerPropertyChanged();
    }

    /// <summary>
    /// /// Helper to raise a PropertyChanged event for the Indexer property
    /// /// </summary>
    private void OnIndexerPropertyChanged() =>
      OnPropertyChanged(EventArgsCache.IndexerPropertyChanged);

    /// <summary>
    /// Helper to raise CollectionChanged event to any listeners
    /// </summary>
    private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index) =>
      OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));

    /// <summary>
    /// Helper to raise CollectionChanged event with action == Reset to any listeners
    /// </summary>
    private void OnCollectionReset() =>
      OnCollectionChanged(EventArgsCache.ResetCollectionChanged);

    /// <summary>
    /// Helper to raise event for clustered action and clear cluster.
    /// </summary>
    /// <param name="followingItemIndex">The index of the item following the replacement block.</param>
    /// <param name="newCluster"></param>
    /// <param name="oldCluster"></param>
    //TODO should have really been a local method inside ReplaceRange(int index, int count, IEnumerable<T> collection, IEqualityComparer<T> comparer),
    //move when supported language version updated.
    private void OnRangeReplaced(int followingItemIndex, ICollection<T> newCluster, ICollection<T> oldCluster)
    {
      if (oldCluster == null || oldCluster.Count == 0)
      {
        Debug.Assert(newCluster == null || newCluster.Count == 0);
        return;
      }

      OnCollectionChanged(
          new NotifyCollectionChangedEventArgs(
              NotifyCollectionChangedAction.Replace,
              new List<T>(newCluster),
              new List<T>(oldCluster),
              followingItemIndex - oldCluster.Count));

      oldCluster.Clear();
      newCluster.Clear();
    }

    #endregion Private Methods

    //------------------------------------------------------
    //
    //  Private Types
    //
    //------------------------------------------------------

    #region Private Types
    private sealed class DeferredEventsCollection : List<NotifyCollectionChangedEventArgs>, IDisposable
    {
      private readonly ObservableRangeCollection<T> _collection;
      public DeferredEventsCollection(ObservableRangeCollection<T> collection)
      {
        Debug.Assert(collection != null);
        Debug.Assert(collection._deferredEvents == null);
        _collection = collection;
        _collection._deferredEvents = this;
      }

      public void Dispose()
      {
        _collection._deferredEvents = null;
        foreach (var args in this)
          _collection.OnCollectionChanged(args);
      }
    }

    #endregion Private Types

  }

  /// <remarks>
  /// To be kept outside <see cref="ObservableCollection{T}"/>, since otherwise, a new instance will be created for each generic type used.
  /// </remarks>
  internal static class EventArgsCache
  {
    internal static readonly PropertyChangedEventArgs CountPropertyChanged = new PropertyChangedEventArgs("Count");
    internal static readonly PropertyChangedEventArgs IndexerPropertyChanged = new PropertyChangedEventArgs("Item[]");
    internal static readonly NotifyCollectionChangedEventArgs ResetCollectionChanged = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
  }
}

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

If you enter the URL in a browser and then look at the source code of the page you will see that an XML document is returned.

The reason why that URL would work in a browser but not in the android manager might be that you are required to specify a proxy server. In Eclipse (3.5.2) the proxy settings can be found here: "Window" -> "Preferences" -> "General" -> "Network Connections"

Recursive Fibonacci

int fib(int x) 
{
    if (x == 0)
      return 0;
    else if (x == 1 || x == 2) 
      return 1;
    else 
      return (fib(x - 1) + fib(x - 2));
}

Node.js EACCES error when listening on most ports

I got this error on my mac because it ran the apache server by default using the same port as the one used by the node server which in my case was the port 80. All I had to do is stop it with sudo apachectl stop

Hope this helps someone.

In WPF, what are the differences between the x:Name and Name attributes?

x:Name and Name are referencing different namespaces.

x:name is a reference to the x namespace defined by default at the top of the Xaml file.

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Just saying Name uses the default below namespace.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

x:Name is saying use the namespace that has the x alias. x is the default and most people leave it but you can change it to whatever you like

xmlns:foo="http://schemas.microsoft.com/winfx/2006/xaml"

so your reference would be foo:name

Define and Use Namespaces in WPF


OK lets look at this a different way. Say you drag and drop an button onto your Xaml page. You can reference this 2 ways x:name and name. All xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" and xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" are is references to multiple namespaces. Since xaml holds the Control namespace(not 100% on that) and presentation holds the FrameworkElement AND the Button class has a inheritance pattern of:

Button : ButtonBase
ButtonBase : ContentControl, ICommandSource
ContentControl : Control, IAddChild
Control : FrameworkElement
FrameworkElement : UIElement, IFrameworkInputElement, 
                    IInputElement, ISupportInitialize, IHaveResources

So as one would expect anything that inherits from FrameworkElement would have access to all its public attributes. so in the case of Button it is getting its Name attribute from FrameworkElement, at the very top of the hierarchy tree. So you can say x:Name or Name and they will both be accessing the getter/setter from the FrameworkElement.

MSDN Reference

WPF defines a CLR attribute that is consumed by XAML processors in order to map multiple CLR namespaces to a single XML namespace. The XmlnsDefinitionAttribute attribute is placed at the assembly level in the source code that produces the assembly. The WPF assembly source code uses this attribute to map the various common namespaces, such as System.Windows and System.Windows.Controls, to the http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace.

So the assembly attributes will look something like:

PresentationFramework.dll - XmlnsDefinitionAttribute:

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Data")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Navigation")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Shapes")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Documents")]

[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation", "System.Windows.Controls")]  

Use CSS3 transitions with gradient backgrounds

In the following, an anchor tag has a child and a grandchild. The grandchild has the far background gradient. The child in the near background is transparent, but has the gradient to transition to. On hover, the child's opacity is transitioned from 0 to 1, over a period of 1 second.

Here is the CSS:

.bkgrndfar {
  position:absolute;
  top:0;
  left:0;
  z-index:-2;
  height:100%;
  width:100%;
  background:linear-gradient(#eee, #aaa);
}

.bkgrndnear {
  position:absolute;
  top:0;
  left:0;
  height:100%;
  width:100%;
  background:radial-gradient(at 50% 50%, blue 1%, aqua 100%);
  opacity:0;
  transition: opacity 1s;
}

a.menulnk {
  position:relative;
  text-decoration:none;
  color:#333;
  padding: 0 20px;
  text-align:center;
  line-height:27px;
  float:left;
}

a.menulnk:hover {
  color:#eee;
  text-decoration:underline;
}

/* This transitions child opacity on parent hover */
a.menulnk:hover .bkgrndnear {
  opacity:1;
}

And, this is the HTML:

<a href="#" class="menulnk">Transgradient
<div class="bkgrndfar">
  <div class="bkgrndnear">
  </div>
</div>
</a>

The above is only tested in the latest version of Chrome. These are the before hover, halfway on-hover and fully transitioned on-hover images:

Before Halfway After

Error in spring application context schema

What I did with spring-data-jpa-1.3 was adding a version to xsd and lowered it to 1.2. Then the error message disappears. Like this

<beans
        xmlns="http://www.springframework.org/schema/beans"
        ...
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    ...
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd">

Seems like it was fixed for for 1.2 but then appears again in 1.3.

SSRS the definition of the report is invalid

I got this error on a report I copied from another project and changed the data source. I solved it by opening the properties of my dataset, going to the Parameters section, and literally just reselecting all the parameters in the right column, like I just clicked the dropdown and selected the same column. Then I hit preview, and it worked!

Combine several images horizontally with Python

Just adding to the solutions already suggested. Assumes same height, no resizing.

import sys
import glob
from PIL import Image
Image.MAX_IMAGE_PIXELS = 100000000  # For PIL Image error when handling very large images

imgs    = [ Image.open(i) for i in list_im ]

widths, heights = zip(*(i.size for i in imgs))
total_width = sum(widths)
max_height = max(heights)

new_im = Image.new('RGB', (total_width, max_height))

# Place first image
new_im.paste(imgs[0],(0,0))

# Iteratively append images in list horizontally
hoffset=0
for i in range(1,len(imgs),1):
    **hoffset=imgs[i-1].size[0]+hoffset  # update offset**
    new_im.paste(imgs[i],**(hoffset,0)**)

new_im.save('output_horizontal_montage.jpg')

How do I get the current timezone name in Postgres 9.3?

It seems to work fine in Postgresql 9.5:

SELECT current_setting('TIMEZONE');

How to create a remote Git repository from a local one?

In order to initially set up any Git server, you have to export an existing repository into a new bare repository — a repository that doesn’t contain a working directory. This is generally straightforward to do. In order to clone your repository to create a new bare repository, you run the clone command with the --bare option. By convention, bare repository directories end in .git, like so:

$ git clone --bare my_project my_project.git
Initialized empty Git repository in /opt/projects/my_project.git/

This command takes the Git repository by itself, without a working directory, and creates a directory specifically for it alone.

Now that you have a bare copy of your repository, all you need to do is put it on a server and set up your protocols. Let’s say you’ve set up a server called git.example.com that you have SSH access to, and you want to store all your Git repositories under the /opt/git directory. You can set up your new repository by copying your bare repository over:

$ scp -r my_project.git [email protected]:/opt/git

At this point, other users who have SSH access to the same server which has read-access to the /opt/git directory can clone your repository by running

$ git clone [email protected]:/opt/git/my_project.git

If a user SSHs into a server and has write access to the /opt/git/my_project.git directory, they will also automatically have push access. Git will automatically add group write permissions to a repository properly if you run the git init command with the --shared option.

$ ssh [email protected]
$ cd /opt/git/my_project.git
$ git init --bare --shared

It is very easy to take a Git repository, create a bare version, and place it on a server to which you and your collaborators have SSH access. Now you’re ready to collaborate on the same project.

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

Spring Boot 1.4 Use this for Javascript HTML Json all compressions.

server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,text/css,application/javascript

Accessing bash command line args $@ vs $*

This example let may highlight the differ between "at" and "asterix" while we using them. I declared two arrays "fruits" and "vegetables"

fruits=(apple pear plumm peach melon)            
vegetables=(carrot tomato cucumber potatoe onion)

printf "Fruits:\t%s\n" "${fruits[*]}"            
printf "Fruits:\t%s\n" "${fruits[@]}"            
echo + --------------------------------------------- +      
printf "Vegetables:\t%s\n" "${vegetables[*]}"    
printf "Vegetables:\t%s\n" "${vegetables[@]}"    

See the following result the code above:

Fruits: apple pear plumm peach melon
Fruits: apple
Fruits: pear
Fruits: plumm
Fruits: peach
Fruits: melon
+ --------------------------------------------- +
Vegetables: carrot tomato cucumber potatoe onion
Vegetables: carrot
Vegetables: tomato
Vegetables: cucumber
Vegetables: potatoe
Vegetables: onion

Mathematical functions in Swift

You can use them right inline:

var square = 9.4
var floored = floor(square)
var root = sqrt(floored)

println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")

adb shell command to make Android package uninstall dialog appear

I assume that you enable developer mode on your android device and you are connected to your device and you have shell access (adb shell).

Once this is done you can uninstall application with this command pm uninstall --user 0 <package.name>. 0 is root id -this way you don't need too root your device.

Here is an example how I did on my Huawei P110 lite

# gain shell access
$ adb shell

# check who you are
$ whoami
shell

# obtain user id
$ id
uid=2000(shell) gid=2000(shell)

# list packages
$ pm list packages | grep google                                                                                                                                                         
package:com.google.android.youtube
package:com.google.android.ext.services
package:com.google.android.googlequicksearchbox
package:com.google.android.onetimeinitializer
package:com.google.android.ext.shared
package:com.google.android.apps.docs.editors.sheets
package:com.google.android.configupdater
package:com.google.android.marvin.talkback
package:com.google.android.apps.tachyon
package:com.google.android.instantapps.supervisor
package:com.google.android.setupwizard
package:com.google.android.music
package:com.google.android.apps.docs
package:com.google.android.apps.maps
package:com.google.android.webview
package:com.google.android.syncadapters.contacts
package:com.google.android.packageinstaller
package:com.google.android.gm
package:com.google.android.gms
package:com.google.android.gsf
package:com.google.android.tts
package:com.google.android.partnersetup
package:com.google.android.videos
package:com.google.android.feedback
package:com.google.android.printservice.recommendation
package:com.google.android.apps.photos
package:com.google.android.syncadapters.calendar
package:com.google.android.gsf.login
package:com.google.android.backuptransport
package:com.google.android.inputmethod.latin

# uninstall gmail app
pm uninstall --user 0 com.google.android.gms

Print in new line, java

System.out.print(values[i] + " ");
//in one number be printed

How to hide console window in python?

Some additional info. for situations that'll need the win32gui solution posted by Mohsen Haddadi earlier in this thread:

As of python 361, win32gui & win32con are not part of the python std library. To use them, pywin32 package will need to be installed; now possible via pip.

More background info on pywin32 package is at: How to use the win32gui module with Python?.

Also, to apply discretion while closing a window so as to not inadvertently close any window in the foreground, the resolution could be extended along the lines of the following:

try     :

    import win32gui, win32con;

    frgrnd_wndw = win32gui.GetForegroundWindow();
    wndw_title  = win32gui.GetWindowText(frgrnd_wndw);
    if wndw_title.endswith("python.exe"):
        win32gui.ShowWindow(frgrnd_wndw, win32con.SW_HIDE);
    #endif
except  :
    pass

How to make EditText not editable through XML in Android?

They made "editable" deprecated but didn't provide a working corresponding one in inputType.

By the way, does inputType="none" has any effect? Using it or not does not make any difference as far as I see.

For example, the default editText is said to be single line. But you have to select an inputType for it to be single line. And if you select "none", it is still multiline.

How to load assemblies in PowerShell?

Here are some blog posts with numerous examples of ways to load assemblies in PowerShell v1, v2 and v3.

The ways include:

  • dynamically from a source file
  • dynamically from an assembly
  • using other code types, i.e. F#

v1.0 How To Load .NET Assemblies In A PowerShell Session
v2.0 Using CSharp (C#) code in PowerShell scripts 2.0
v3.0 Using .NET Framework Assemblies in Windows PowerShell

Change header background color of modal of twitter bootstrap

Add this class to your css file to override the bootstrap class.modal-header

.modal-header {
   background:#0480be;
}

It's important try to never edit Bootstrap CSS, in order to be able to update from the repo and not loose the changes made or break something in futures releases.

How can I get the length of text entered in a textbox using jQuery?

var myLength = $("#myTextbox").val().length;

Convert multiple rows into one with comma as separator

You can use this query to do the above task:

DECLARE @test NVARCHAR(max)  
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test
SELECT field2 = @test 

For detail and step by step explanation visit the following link http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html

How to make a page redirect using JavaScript?

Use:

window.location = "http://my.url.here";

Here's some quick-n-dirty code that uses jQuery to do what you want. I highly recommend using jQuery. It'll make things a lot more easier for you, especially since you're new to JavaScript.

<select id = "pricingOptions" name = "pricingOptions">
    <option value = "500">Option A</option>
    <option value = "1000">Option B</option>
</select>

<script type = "text/javascript" language = "javascript">
    jQuery(document).ready(function() {
        jQuery("#pricingOptions").change(function() {
            if(this.options[this.selectedIndex].value == "500") {
                window.location = "http://example.com/foo.php?option=500";
            }
        });
    });
</script>

Add all files to a commit except a single file?

Use git add -A to add all modified and newly added files at once.

Example

git add -A
git reset -- main/dontcheckmein.txt

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

How to get the Parent's parent directory in Powershell?

I've solved that like this:

$RootPath = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent

How to detect Adblock on my website?

I've only tested with AdBlock... if the ads.js file solution won't work for you, this may..

Somewhere in your <body> add:

<div class="ads-wrapper adTop adUnit"></div>

then you can detect if AdBlock is enabled after DOM ready and then trigger whatever you intend to do:

var adBlockDetected = null;
$(document).ready(function() {
    setTimeout(function() {
        adBlockDetected = !$('.ads-wrapper').length > 0 || !$('.ads-wrapper').is(':visible');

        if (adBlockDetected) {
            $(document).trigger('adblock-detected');
        }
    }, 1000); // give adblock time to do what it does best
});

$(document).on('adblock-detected', function() {
    // ... your code here
});