Programs & Examples On #Divx

Read/Write 'Extended' file properties (C#)

Here is a solution for reading - not writing - the extended properties based on what I found on this page and at help with shell32 objects.

To be clear this is a hack. It looks like this code will still run on Windows 10 but will hit on some empty properties. Previous version of Windows should use:

        var i = 0;
        while (true)
            if (String.IsNullOrEmpty(header)) break;

On Windows 10 we assume that there are about 320 properties to read and simply skip the empty entries:

    private Dictionary<string, string> GetExtendedProperties(string filePath)
        var directory = Path.GetDirectoryName(filePath);
        var shell = new Shell32.Shell();
        var shellFolder = shell.NameSpace(directory);
        var fileName = Path.GetFileName(filePath);
        var folderitem = shellFolder.ParseName(fileName);
        var dictionary = new Dictionary<string, string>();
        var i = -1;
        while (++i < 320)
            var header = shellFolder.GetDetailsOf(null, i);
            if (String.IsNullOrEmpty(header)) continue;
            var value = shellFolder.GetDetailsOf(folderitem, i);
            if (!dictionary.ContainsKey(header)) dictionary.Add(header, value);
            Console.WriteLine(header +": " + value);
        return dictionary;

As mentioned you need to reference the Com assembly Interop.Shell32.

If you get an STA related exception, you will find the solution here:

Exception when using Shell32 to get File extended properties

I have no idea what those properties names would be like on a foreign system and couldn't find information about which localizable constants to use in order to access the dictionary. I also found that not all the properties from the Properties dialog were present in the dictionary returned.

BTW this is terribly slow and - at least on Windows 10 - parsing dates in the string retrieved would be a challenge so using this seems to be a bad idea to start with.

On Windows 10 you should definitely use the Windows.Storage library which contains the SystemPhotoProperties, SystemMusicProperties etc.

And finally, I posted a much better solution that uses WindowsAPICodePack there

PHP to search within txt file and echo the whole line

Using file() and strpos():

// What to look for
$search = 'foo';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false)
    echo $line;

When tested on this file:


It outputs:


To show text if the text is not found, use something like this:

$search = 'foo';
$lines = file('file.txt');
// Store true when the text is found
$found = false;
foreach($lines as $line)
  if(strpos($line, $search) !== false)
    $found = true;
    echo $line;
// If the text was not found, show a message
  echo 'No match found';

Here I'm using the $found variable to find out if a match was found.

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

How to use Select2 with JSON via Ajax request?

Tthe problems may be caused by incorrect mapping. Are you sure you have your result set in "data"? In my example, the backend code returns results under "items" key, so the mapping should look like:

results: $.map(data.items, function (item) {

and not:

 results: $.map(data, function (item) {

Save and load weights in keras

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here:

The snippets to save & load can be found below:, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.'my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here

Java Generics With a Class & an Interface - Together

You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
    T t;

Proper MIME type for OTF fonts

I just did some research on IANA official list. I believe the answer given here 'font/xxx' is incorrect as there is no 'font' type in the MIME standard.

Based on the RFCs and IANA, this appears to be the current state of the play as at May 2013:

These three are official and assigned by IANA:

  • svg as "image/svg+xml"
  • woff as "application/font-woff"
  • eot as "application/"

These are not not official/assigned, and so must use the 'x-' syntax:

  • ttf as "application/x-font-ttf"
  • otf as "application/x-font-opentype"

The application/font-woff appears new and maybe only official since Jan 2013. So "application/x-font-woff" might be safer/more compatible in the short term.

TCPDF ERROR: Some data has already been output, can't send PDF file

I had this but unlike the OP I couldn't see any output before the TCPDF error message.

Turns out there was a UTF8 BOM (byte-order-mark) at the very start of my script, before the <?php tag so before I had any chance to call ob_start(). And there was also a UTF8 BOM before the TCPDF error message.

Radio buttons not checked in jQuery


This worked for me

Javascript get Object property Name

If you know for sure that there's always going to be exactly one key in the object, then you can use Object.keys:

theTypeIs = Object.keys(myVar)[0];

Convert PEM to PPK file format

To SSH connectivity to AWS EC2 instance, You don't need to convert the .PEM file to PPK file even on windows machine, Simple SSH using 'git bash' tool. No need to download and convert these softwares - Hope this will save your time of downloading and converting keys and get you more time on EC2 things.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

public String getDaySuffix(int inDay)
  String s = String.valueOf(inDay);

  if (s.endsWith("1"))
    return "st";
  else if (s.endsWith("2"))
    return "nd";
  else if (s.endsWith("3"))
    return "rd";
    return "th";

JavaScript hashmap equivalent

Here is an easy and convenient way of using something similar to the Java map:

var map = {
              'map_name_1': map_value_1,
              'map_name_2': map_value_2,
              'map_name_3': map_value_3,
              'map_name_4': map_value_4

And to get the value:

alert(map['map_name_1']);    // Gives the value of map_value_1

... etc. ...

How do you handle a form change in jQuery?

var formStr = JSON.stringify($("#form").serializeArray());
function Submit(){
   var newformStr = JSON.stringify($("#form").serializeArray());
   if (formStr != newformStr){
   else {

Determine if an element has a CSS class with jQuery

 $('.segment-name').click(function () {
        //class exist

How does HttpContext.Current.User.Identity.Name know which usernames exist?

For windows authentication

select your project.

Press F4

Disable "Anonymous Authentication" and enable "Windows Authentication"

enter image description here

Could not find a version that satisfies the requirement <package>

Although it doesn't really answers this specific question. Others got the same error message with this mistake.

For those who like me initial forgot the -r: Use pip install -r requirements.txt the -r is essential for the command.

The original answer:

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   * @example
   * import { map, filter, scan } from 'rxjs/operators';
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

SQL: Insert all records from one table to another table without specific the columns

SQL 2008 allows you to forgo specifying column names in your SELECT if you use SELECT INTO rather than INSERT INTO / SELECT:


The INTO clause does exist in SQL Server 2000-2005, but still requires specifying column names. 2008 appears to add the ability to use SELECT *.

See the MSDN articles on INTO (SQL2005), (SQL2008) for details.

The INTO clause only works if the destination table does not yet exist, however. If you're looking to add records to an existing table, this won't help.

How do I concatenate two strings in C?

I'll assume you need it for one-off things. I'll assume you're a PC developer.

Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.

#include <string.h>
#include <stdio.h>

#define STR_SIZE 10000

int main()
  char s1[] = "oppa";
  char s2[] = "gangnam";
  char s3[] = "style";

    char result[STR_SIZE] = {0};
    snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
    printf("%s\n", result);

If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.

parse html string with jquery

just add container element befor your img element just to be sure that your intersted element not the first one, tested in ie,ff

Git push failed, "Non-fast forward updates were rejected"

Sometimes, while taking a pull from your git, the HEAD gets detached. You can check this by entering the command:

git branch 
  • (HEAD detached from 8790704)



It's better to move to your branch and take a fresh pull from your respective branch.

git checkout develop

git pull origin develop

git push origin develop

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

The concept of http location and disk location is different. What you need to do is:

  1. for uploaded file summer.jpg
  2. move that under a known (to the application) location to disk, e.g c:\images\summer.jpg
  3. insert into db record representing the image with text summer.jpg
  4. to display it use plain <img src="images/summer.jpg" />
  5. you need something (e.g apache) that will serve c:\images\ under your application's /images. If you cannot do this then in step #2 you need to save somewhere under your web root, e.g c:\my-applications\demo-app\build\images

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

How to define custom configuration variables in rails

This works in rails 3.1:

in config/environment.rb (or in config/environments/.. to target a specific environment) :

YourApp::Application.config.yourKey = 'foo'

This will be accessible in controller or views like this:


(YourApp should be replaced by your application name.)

Note: It's Ruby code, so if you have a lot of config keys, you can do this :

in config/environment.rb :

YourApp::Application.configure do
  config.something = foo

Best algorithm for detecting cycles in a directed graph

If DFS finds an edge that points to an already-visited vertex, you have a cycle there.

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

ngOnInit() is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

ngAfterViewInit() is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.

Set time to 00:00:00

Another way to do this would be to use a DateFormat without any seconds:

public static Date trim(Date date) {
    DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    Date trimmed = null;
    try {
        trimmed = format.parse(format.format(date));
    } catch (ParseException e) {} // will never happen
    return trimmed;

ImportError: No module named 'encodings'

For Windows10 User.

I was using python3.4 on Windows10. I installed python3.5. I couldn't find PYTHONPATH, PYTHONHOME env variable. If I command python in CMD console, It kept using python3.4. I deleted python3.4. Whenever I command python in CMD console, it starts showing an error like below.

Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'

I searched to figure out my problem. Solution was simple. When you install python3.5, you can custom install and check Add Python to environment variables in Advanced Options.

I just leave here for case that someone have similar issues visit here so that they don't waste their precious time much to figure out.

How to send multiple data fields via Ajax?

This one works for me.

Here's my PHP:

<div id="pageContent">
    while($row = mysqli_fetch_assoc($stmt)) {
  <input id="vendorName_" name="vendorName_<?php echo $row["id"]; ?>" value='<?php echo $row["vendorName"]; ?>'>
  <input id="owner_" name="owner_<?php echo $row["id"]; ?>" value='<?php echo $row["owner"]; ?>'>
  <input id="city_" name="city_<?php echo $row["id"]; ?>" value='<?php echo $row["city"]; ?>'>
  <button id="btn_update_<?php echo $row["id"]; ?>">Update</button>
  <button id="btn_delete_<?php echo $row["id"]; ?>">Delete</button>
  <input id = "vendorName_new" value="">
  <input id = "owner_new" value="">
  <input id = "city_new" value="">
  <button id = "addNewVendor" type="submit">+ New Vendor</button>

Here's my jQuery using AJAX:

$("#addNewVendor").click(function() {
    type: "POST",
    url: "create.php",
    data: {vendorName: $("#vendorName_new").val(), owner: $("#owner_new").val(), city: $("#city_new").val()},
    success: function(){

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

I can elaborate on the details of DLLs in Windows to help clarify those mysteries to my friends here in *NIX-land...

A DLL is like a Shared Object file. Both are images, ready to load into memory by the program loader of the respective OS. The images are accompanied by various bits of metadata to help linkers and loaders make the necessary associations and use the library of code.

Windows DLLs have an export table. The exports can be by name, or by table position (numeric). The latter method is considered "old school" and is much more fragile -- rebuilding the DLL and changing the position of a function in the table will end in disaster, whereas there is no real issue if linking of entry points is by name. So, forget that as an issue, but just be aware it's there if you work with "dinosaur" code such as 3rd-party vendor libs.

Windows DLLs are built by compiling and linking, just as you would for an EXE (executable application), but the DLL is meant to not stand alone, just like an SO is meant to be used by an application, either via dynamic loading, or by link-time binding (the reference to the SO is embedded in the application binary's metadata, and the OS program loader will auto-load the referenced SO's). DLLs can reference other DLLs, just as SOs can reference other SOs.

In Windows, DLLs will make available only specific entry points. These are called "exports". The developer can either use a special compiler keyword to make a symbol an externally-visible (to other linkers and the dynamic loader), or the exports can be listed in a module-definition file which is used at link time when the DLL itself is being created. The modern practice is to decorate the function definition with the keyword to export the symbol name. It is also possible to create header files with keywords which will declare that symbol as one to be imported from a DLL outside the current compilation unit. Look up the keywords __declspec(dllexport) and __declspec(dllimport) for more information.

One of the interesting features of DLLs is that they can declare a standard "upon load/unload" handler function. Whenever the DLL is loaded or unloaded, the DLL can perform some initialization or cleanup, as the case may be. This maps nicely into having a DLL as an object-oriented resource manager, such as a device driver or shared object interface.

When a developer wants to use an already-built DLL, she must either reference an "export library" (*.LIB) created by the DLL developer when she created the DLL, or she must explicitly load the DLL at run time and request the entry point address by name via the LoadLibrary() and GetProcAddress() mechanisms. Most of the time, linking against a LIB file (which simply contains the linker metadata for the DLL's exported entry points) is the way DLLs get used. Dynamic loading is reserved typically for implementing "polymorphism" or "runtime configurability" in program behaviors (accessing add-ons or later-defined functionality, aka "plugins").

The Windows way of doing things can cause some confusion at times; the system uses the .LIB extension to refer to both normal static libraries (archives, like POSIX *.a files) and to the "export stub" libraries needed to bind an application to a DLL at link time. So, one should always look to see if a *.LIB file has a same-named *.DLL file; if not, chances are good that *.LIB file is a static library archive, and not export binding metadata for a DLL.

What is the correct way to free memory in C#

Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.

For managed resources, the garbage collector will know when this is, and you don't need to do anything.

For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)

If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)

Why does the arrow (->) operator in C exist?

Beyond historical (good and already reported) reasons, there's is also a little problem with operators precedence: dot operator has higher priority than star operator, so if you have struct containing pointer to struct containing pointer to struct... These two are equivalent:



But the second is clearly more readable. Arrow operator has the highest priority (just as dot) and associates left to right. I think this is clearer than use dot operator both for pointers to struct and struct, because we know the type from the expression without have to look at the declaration, that could even be in another file.

<DIV> inside link (<a href="">) tag

No, the link assigned to the containing <a> will be assigned to every elements inside it.

And, this is not the proper way. You can make a <a> behave like a <div>.

An Example [Demo]


a.divlink { 


    <a class="divlink" href="yourlink.html">
         The text or elements inside the elements
    <a class="divlink" href="yourlink2.html">
         Another text or element

AttributeError: 'str' object has no attribute 'append'

Why myList[1] is considered a 'str' object?

Because it is a string. What else is 'from form', if not a string? (Actually, strings are sequences too, i.e. they can be indexed, sliced, iterated, etc. as well - but that's part of the str class and doesn't make it a list or something).

mList[1] returns the first item in the list 'from form'

If you mean that myList is 'from form', no it's not!!! The second (indexing starts at 0) element is 'from form'. That's a BIG difference. It's the difference between a house and a person.

Also, myList doesn't have to be a list from your short code sample - it could be anything that accepts 1 as index - a dict with 1 as index, a list, a tuple, most other sequences, etc. But that's irrelevant.

but I cannot append to item 1 in the list myList

Of course not, because it's a string and you can't append to string. String are immutable. You can concatenate (as in, "there's a new object that consists of these two") strings. But you cannot append (as in, "this specific object now has this at the end") to them.

PYTHONPATH vs. sys.path

In general I would consider setting up of an environment variable (like PYTHONPATH) to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.

Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the test environment as well, leading to situations like the tests running fine for a particular developer but probably failing when some one launches the tests.

How to get twitter bootstrap modal to close (after initial launch)

Try specifying exactly the modal that the button should close with data-target. So your button should look like the following -

<button class="close" data-dismiss="modal" data-target="#myModal">×</button>

Also, you should only need bootstrap.modal.js so you can safely remove the others.

Edit: if this doesn't work then remove the visible-phone class and test it on your PC browser instead of the phone. This will show whether you are getting javascript errors or if its a compatibility issue for example.

Edit: Demo code

    <link href="/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/bootstrap.modal.js" type="text/javascript"></script>

    <script type="text/javascript">
      $(document).ready(function () {
        if( navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
          ) {

        $("#myModalClose").click(function () {
    <div class="modal hide" id="myModal">
      <div class="modal-header">
        <a class="close" id="myModalClose">×</a>
        <h3>text introductory<br>want to navigate to...</h3>
     <div class="modal-body">
        <ul class="nav">
          <li> ... list of links here </li>

how to get all child list from Firebase android

your problem is why your code doesn't work.

this your code:

Firebase ref = new Firebase(FIREBASE_URL);

  ref.addValueEventListener(new ValueEventListener() {
      public void onDataChange(DataSnapshot snapshot) {
          Log.e("Count " ,""+snapshot.getChildrenCount());
          for (DataSnapshot postSnapshot: snapshot.getChildren()) {
            <YourClass> post = postSnapshot.getValue(<YourClass>.class);
            Log.e("Get Data", post.<YourMethod>());
      public void onCancelled(FirebaseError firebaseError) {
          Log.e("The read failed: " ,firebaseError.getMessage());

you miss the simplest thing: getChildren()

FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference reference = FirebaseAuth.getInstance().getReference("Donald Trump");

reference.addValueEventListener(new ValueEventListener() {
   public void onDataChange(DataSnapshot dataSnapshot) {

            int count = (int) dataSnapshot.getChildrenCount(); // retrieve number of childrens under Donald Trump

            String[] hairColors = new String[count];

            index = 0;
            for (DataSnapshot datas : dataSnapshot.getChildren()){

                hairColors[index] = datas.getValue(String.class);

            index ++

            for (int i = 0; i < count; i++)
            Toast(MainActivity.this, "hairColors : " + hairColors[i], toast.LENGTH_SHORT).show();



        public void onCancelled(DatabaseError databaseError) {



C program to check little vs. big endian

This is big endian test from a configure script:

#include <inttypes.h>
int main(int argc, char ** argv){
    volatile uint32_t i=0x01234567;
    // return 0 for big endian, 1 for little endian.
    return (*((uint8_t*)(&i))) == 0x67;

Cross-Origin Request Blocked

@Egidius, when creating an XMLHttpRequest, you should use

var xhr = new XMLHttpRequest({mozSystem: true});

What is mozSystem?

mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox.

Changes to your Manifest

On your manifest, do not forget to include this line on your permissions:

"permissions": {
       "systemXHR" : {},

Using AngularJS date filter with UTC date

After some research I was able to find a good solution for converting UTC to local time, have a a look at the fiddle. Hope it help

<script src=""></script>

<div ng-app ng-controller="MyCtrl">
  {{date | date:'yyyy-mm-dd hh:mm:ss' }}

function MyCtrl($scope) {
 $scope.d = "2017-07-21 19:47:00";
  $scope.d = $scope.d.replace(" ", 'T') + 'Z';
  $ = new Date($scope.d);

Windows batch: formatted date into variable

This is an extension of Joey's answer to include the time and pad the parts with 0's.

For example, the result will be 2019-06-01_17-25-36. Also note that this is the UTC time.

  for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x

  set Month=0%Month%
  set Month=%Month:~-2%
  set Day=0%Day%
  set Day=%Day:~-2%
  set Hour=0%Hour%
  set Hour=%Hour:~-2%
  set Minute=0%Minute%
  set Minute=%Minute:~-2%
  set Second=0%Second%
  set Second=%Second:~-2%

  set TimeStamp=%Year%-%Month%-%Day%_%Hour%-%Minute%-%Second%

Convert String to SecureString

no fancy linq, not adding all the chars by hand, just plain and simple:

var str = "foo";
var sc = new SecureString();
foreach(char c in str) sc.appendChar(c);

Java Process with Input/Output Stream

I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:

Thread T=new Thread(new Runnable() {

    public void run() {
            String input = scan.nextLine();
            input += "\n";
            try {
            } catch (IOException e) {
                // TODO Auto-generated catch block


} );

and you can reader will be same as above i.e.

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);

make your writer as final otherwise it wont be able to accessible by inner class.

How to hide column of DataGridView when using custom DataSource?

MyDataGridView.RowHeadersVisible = False; Before binding and rename each columns header and set columns width. To help my failing memory when I search, because I will search ... that's for sure ;-)

Should switch statements always contain a default clause?

The default case may not necessary in the switch used by enum. when switch contained all value, the default case will never execute. So in this case, it is not necessary.

How to convert enum names to string in c

One way, making the preprocessor do the work. It also ensures your enums and strings are in sync.

        FRUIT(apple)   \
        FRUIT(orange)  \
        FRUIT(grape)   \
        FRUIT(banana)  \



static const char *FRUIT_STRING[] = {

After the preprocessor gets done, you'll have:

    apple, orange, grape, banana,

static const char *FRUIT_STRING[] = {
    "apple", "orange", "grape", "banana",

Then you could do something like:

printf("enum apple as a string: %s\n",FRUIT_STRING[apple]);

If the use case is literally just printing the enum name, add the following macros:

#define str(x) #x
#define xstr(x) str(x)

Then do:

printf("enum apple as a string: %s\n", xstr(apple));

In this case, it may seem like the two-level macro is superfluous, however, due to how stringification works in C, it is necessary in some cases. For example, let's say we want to use a #define with an enum:

#define foo apple

int main() {
    printf("%s\n", str(foo));
    printf("%s\n", xstr(foo));

The output would be:


This is because str will stringify the input foo rather than expand it to be apple. By using xstr the macro expansion is done first, then that result is stringified.

See Stringification for more information.

Remove duplicates from a List<T> in C#

If you have tow classes Product and Customer and we want to remove duplicate items from their list

public class Product
    public int Id { get; set; }
    public string ProductName { get; set; }

public class Customer
    public int Id { get; set; }
    public string CustomerName { get; set; }


You must define a generic class in the form below

public class ItemEqualityComparer<T> : IEqualityComparer<T> where T : class
    private readonly PropertyInfo _propertyInfo;

    public ItemEqualityComparer(string keyItem)
        _propertyInfo = typeof(T).GetProperty(keyItem, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);

    public bool Equals(T x, T y)
        var xValue = _propertyInfo?.GetValue(x, null);
        var yValue = _propertyInfo?.GetValue(y, null);
        return xValue != null && yValue != null && xValue.Equals(yValue);

    public int GetHashCode(T obj)
        var propertyValue = _propertyInfo.GetValue(obj, null);
        return propertyValue == null ? 0 : propertyValue.GetHashCode();

then, You can remove duplicate items in your list.

var products = new List<Product>
                new Product{ProductName = "product 1" ,Id = 1,},
                new Product{ProductName = "product 2" ,Id = 2,},
                new Product{ProductName = "product 2" ,Id = 4,},
                new Product{ProductName = "product 2" ,Id = 4,},
var productList = products.Distinct(new ItemEqualityComparer<Product>(nameof(Product.Id))).ToList();

var customers = new List<Customer>
                new Customer{CustomerName = "Customer 1" ,Id = 5,},
                new Customer{CustomerName = "Customer 2" ,Id = 5,},
                new Customer{CustomerName = "Customer 2" ,Id = 5,},
                new Customer{CustomerName = "Customer 2" ,Id = 5,},
var customerList = customers.Distinct(new ItemEqualityComparer<Customer>(nameof(Customer.Id))).ToList();

this code remove duplicate items by Id if you want remove duplicate items by other property, you can change nameof(YourClass.DuplicateProperty) same nameof(Customer.CustomerName) then remove duplicate items by CustomerName Property.

Truncate string in Laravel blade templates

You can set string limit as below example:

<td>{{str_limit($biodata ->description, $limit = 20, $end = '...')}}</td>

It will display only the 20 letters including whitespaces and ends with ....

Example imageIt shows the example of string limit

Is there a command for formatting HTML in the Atom editor?

There are a few packages for prettifying HTML. You can find them by searching the Atom package archive:

  1. Navigate to the Atom site
  2. Click the Packages link
  3. Enter "prettify" in the search box

Or just go to this link:

Once you've selected a package that does what you want you can install it by using the command: apm install [package name] from the command line or install it using the interface in Preferences.

When the package is installed, follow its instructions for how to activate its capabilities.

Read a variable in bash with a default value

read -e -p "Enter Your Name:" -i "Ricardo" NAME

echo $NAME

How to execute Python code from within Visual Studio Code

I use Python 3.7 (32 bit). To run a program in Visual Studio Code, I right-click on the program and select "Run Current File in Python Interactive Window". If you do not have Jupyter, you may be asked to install it.

Enter image description here

On linux SUSE or RedHat, how do I load Python 2.7

If you get an error when at the ./configure stage that says

configure: error: in `/home//Downloads/Python-2.7.14': configure: error: no acceptable C compiler found in $PATH

then try this.

no acceptable C compiler found in $PATH when installing python

Paramiko's SSHClient with SFTP


Sample Usage:

import paramiko

# Open a transport
host,port = "",22
transport = paramiko.Transport((host,port))

# Auth    
username,password = "bar","foo"

# Go!    
sftp = paramiko.SFTPClient.from_transport(transport)

# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"

# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"

# Close
if sftp: sftp.close()
if transport: transport.close()

How to align center the text in html table row?

The following worked for me to vertically align content (multi-line) in a list-table

.. list-table::
   :class: longtable
   :header-rows: 1
   :stub-columns: 1
   :align: left
   :widths: 20, 20, 20, 20, 20

   * - Classification
     - Restricted
     - Company |br| Confidential
     - Internal Use Only
     - Public
   * - Row1 col1
     - Row1 col2
     - Row1 col3 
     - Row1 col4
     - Row1 col5

Using theme overrides .css option I defined:

.stub {
       text-align: left;
       vertical-align: top;

In the theme that I use 'python-docs-theme', the cell entry is defined as 'stub' class. Use your browser development menu to inspect what your theme class is for cell content and update that accordingly.

Running multiple commands in one line in shell

Why not cp to location 1, then mv to location 2. This takes care of "removing" the original.

And no, it's not the correct syntax. | is used to "pipe" output from one program and turn it into input for the next program. What you want is ;, which seperates multiple commands.

cp file1 file2 ; cp file1 file3 ; rm file1

If you require that the individual commands MUST succeed before the next can be started, then you'd use && instead:

cp file1 file2 && cp file1 file3 && rm file1

That way, if either of the cp commands fails, the rm will not run.

Merge two objects with ES6

You can use Object.assign() to merge them into a new object:

const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
console.log(newItem );

You can also use object spread, which is a Stage 4 proposal for ECMAScript:

const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
console.log(newItem );

store and retrieve a class object in shared preference

Do you need to retrieve the object even after the application shutting donw or just during it's running ?

You can store it into a database.
Or Simply create a custom Application class.

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter

<manifest xmlns:android="">
    <application ... android:name=".MyApplication">
        <activity ... />

And then from every activities do :

((MyApplication) getApplication).getMyObject();

Not really the best way but it works.

Where can I find the default timeout settings for all browsers?

firstly I don't think there is just one solution to your problem....

As you know each browser is vastly differant.

But lets see if we can get any closer to the answer you need....

I think IE Might be easy...

Check this link

For Firefox try this:

Open Firefox, and in the address bar, type "about:config" (without quotes). From there, scroll down to the Network.http.keep-alive and make sure that is set to "true". If it is not, double click it, and it will go from false to true. Now, go one below that to network.http.keep-alive.timeout -- and change that number by double clicking it. if you put in, say, 500 there, you should be good. let us know if this helps at all

select rows in sql with latest date for each ID repeated multiple times

You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:

FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id =

Here we give the yourtable table an alias of t1 and then use that alias in the subquery grabbing the max(date) from the same table yourtable for that id.

Convert Mongoose docs to json

It worked for me:

Products.find({}).then(a => console.log( => p.toJSON())))

also if you want use getters, you should add its option also (on defining schema):

new mongoose.Schema({...}, {toJSON: {getters: true}})

calling Jquery function from javascript


        // Instantiate your javascript function
        niceJavascriptRoutine = null;

        // Begin jQuery
        $(document).ready(function() {

            // Your jQuery function
            function niceJqueryRoutine() {
                // some code
            // Point the javascript function to the jQuery function
            niceJavaScriptRoutine = niceJueryRoutine;



Resolving require paths with webpack

My biggest headache was working without a namespaced path. Something like this:


Before I used to set my environment to do this:


I found far more convenient avoiding an implicit src path, which hides important context information.

My aim is to require like this:


As you see, all my app code lives within a mandatory path namespace. This makes quite clear which require call takes a library, app code or a test file.

For this I make sure that my resolve paths are just node_modules and the current app folder, unless you namespace your app inside your source folder like src/my_app

This is my default with webpack

resolve: {
  extensions: ['', '.jsx', '.js', '.json'],
  root: path.resolve(__dirname),
  modulesDirectories: ['node_modules']

It would be even better if you set the environment var NODE_PATH to your current project file. This is a more universal solution and it will help if you want to use other tools without webpack: testing, linting...

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:


before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

Remove characters from C# string

It seems that the shortest way is to combine LINQ and string.Concat:

var input = @"My name @is ,Wan.;'; Wan";
var chrs = new[] {'@', ',', '.', ';', '\''};
var result = string.Concat(input.Where(c => !chrs.Contains(c)));
// => result = "My name is Wan Wan" 

See the C# demo. Note that string.Concat is a shortcut to string.Join("", ...).

Note that using a regex to remove individual known chars is still possible to build dynamically, although it is believed that regex is slower. However, here is a way to build such a dynamic regex (where all you need is a character class):

var pattern = $"[{Regex.Escape(new string(chrs))}]+";
var result = Regex.Replace(input, pattern, string.Empty);

See another C# demo. The regex will look like [@,\.;']+ (matching one or more (+) consecutive occurrences of @, ,, ., ; or ' chars) where the dot does not have to be escaped, but Regex.Escape will be necessary to escape other chars that must be escaped, like \, ^, ] or - whose position inside the character class you cannot predict.

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

I think groupby should work.

df.groupby(['A', 'B']).max()['C']

If you need a dataframe back you can chain the reset index call.

df.groupby(['A', 'B']).max()['C'].reset_index()

moving changed files to another branch for check-in

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally - changes to files are not tied to a particular branch until you commit them.

If you have already committed your changes:

  1. Type git log and remember the SHA of the commit you want to move.
  2. Check out the branch you want to move the commit to.
  3. Type git cherry-pick SHA substituting the SHA from above.
  4. Switch back to your original branch.
  5. Use git reset HEAD~1 to reset back before your wrong-branch commit.

cherry-pick takes a given commit and applies it to the currently checked-out head, thus allowing you to copy the commit over to a new branch.

Selenium webdriver click google search

Most of the answers on this page are outdated.
Here's an updated python version to search google and get all results href's:

import urllib.parse
import re
from selenium import webdriver
q = driver.find_element_by_name('q')
q.send_keys("always look on the bright side of life monty python")
links= driver.find_elements_by_xpath("//h3[@class='r']//a")
for link in links:
    url = urllib.parse.unquote(webElement.get_attribute("href")) # decode the url
    url = re.sub("^.*?(?:url\?q=)(.*?)&sa.*", r"\1", url, 0, re.IGNORECASE) # get the clean url

Please note that the element id/name/class (@class='r') ** will change depending on the user agent**.
The above code used PhantomJS default user agent.

How do I iterate over an NSArray?

Here is how you declare an array of strings and iterate over them:

NSArray *langs = @[@"es", @"en", @"pt", @"it", @"fr"];

for (int i = 0; i < [langs count]; i++) {
  NSString *lang = (NSString*) [langs objectAtIndex:i];
  NSLog(@"%@, ",lang);

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

I'm sure the original poster's issue has long since been resolved. However, I had this same issue, so I thought I'd explain what was causing this problem for me.

I was doing a union query with two tables -- 'foo' and 'foo_bar'. However, in my SQL statement, I had a typo: ''

So, instead of telling me that the '' table doesn't exist, the error message indicates that the command was denied -- as though I don't have permissions.

Hope this helps someone.

What Content-Type value should I send for my XML sitemap?

The difference between text/xml and application/xml is the default character encoding if the charset parameter is omitted:

Text/xml and application/xml behave differently when the charset parameter is not explicitly specified. If the default charset (i.e., US-ASCII) for text/xml is inconvenient for some reason (e.g., bad web servers), application/xml provides an alternative (see "Optional parameters" of application/xml registration in Section 3.2).

For text/xml:

Conformant with [RFC2046], if a text/xml entity is received with the charset parameter omitted, MIME processors and XML processors MUST use the default charset value of "us-ascii"[ASCII]. In cases where the XML MIME entity is transmitted via HTTP, the default charset value is still "us-ascii".

For application/xml:

If an application/xml entity is received where the charset parameter is omitted, no information is being provided about the charset by the MIME Content-Type header. Conforming XML processors MUST follow the requirements in section 4.3.3 of [XML] that directly address this contingency. However, MIME processors that are not XML processors SHOULD NOT assume a default charset if the charset parameter is omitted from an application/xml entity.

So if the charset parameter is omitted, the character encoding of text/xml is US-ASCII while with application/xml the character encoding can be specified in the document itself.

Now a rule of thumb on the internet is: “Be strict with the output but be tolerant with the input.” That means make sure to meet the standards as much as possible when delivering data over the internet. But build in some mechanisms to overlook faults or to guess when receiving and interpreting data over the internet.

So in your case just pick one of the two types (I recommend application/xml) and make sure to specify the used character encoding properly (I recommend to use the respective default character encoding to play safe, so in case of application/xml use UTF-8 or UTF-16).

How does the @property decorator work in Python?

Below is another example on how @property can help when one has to refactor code which is taken from here (I only summarize it below):

Imagine you created a class Money like this:

class Money:
    def __init__(self, dollars, cents):
        self.dollars = dollars
        self.cents = cents

and an user creates a library depending on this class where he/she uses e.g.

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 27 dollar and 12 cents.

Now let's suppose you decide to change your Money class and get rid of the dollars and cents attributes but instead decide to only track the total amount of cents:

class Money:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

If the above mentioned user now tries to run his/her library as before

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))

it will result in an error

AttributeError: 'Money' object has no attribute 'dollars'

That means that now everyone who relies on your original Money class would have to change all lines of code where dollars and cents are used which can be very painful... So, how could this be avoided? By using @property!

That is how:

class Money:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

    # Getter and setter for dollars...
    def dollars(self):
        return self.total_cents // 100

    def dollars(self, new_dollars):
        self.total_cents = 100 * new_dollars + self.cents

    # And the getter and setter for cents.
    def cents(self):
        return self.total_cents % 100

    def cents(self, new_cents):
        self.total_cents = 100 * self.dollars + new_cents

when we now call from our library

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 27 dollar and 12 cents.

it will work as expected and we did not have to change a single line of code in our library! In fact, we would not even have to know that the library we depend on changed.

Also the setter works fine:

money.dollars += 2
print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 29 dollar and 12 cents.

money.cents += 10
print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 29 dollar and 22 cents.

You can use @property also in abstract classes; I give a minimal example here.

Updating an object with setState in React

Without using Async and Await Use this...

     this.setState({...this.state.jasper, name: 'someothername'});

If you using with Async And Await use this...

async funCall(){
      await this.setState({...this.state.jasper, name: 'someothername'});

How do I run a class in a WAR from the command line?

It's not possible to run a java class from a WAR file. WAR files have a different structure to Jar files.

To find the related java classes, export (preferred way to use ant) them as Jar put it in your web app lib.

Then you can use the jar file as normal to run java program. The same jar was also referred in web app (if you put this jar in web app lib)

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

  1. PM>Uninstall-Package EntityFramework -Force
  2. PM>Iinstall-Package EntityFramework -Pre -Version 6.0.0

I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.

Changing the text on a label

There are many ways to tackle a problem like this. There are many ways to do this. I'm going to give you the most simple solution to this question I know. When changing the text of a label or any kind of wiget really. I would do it like this.

Name_Of_Label["text"] = "Your New Text"

So when I apply this knowledge to your code. It would look something like this.

from tkinter import*

class MyGUI:
   def __init__(self):
    self.__mainWindow = Tk()
    #self.fram1 = Frame(self.__mainWindow)
    self.labelText = 'Enter amount to deposit'
    self.depositLabel = Label(self.__mainWindow, text = self.labelText)
    self.depositEntry = Entry(self.__mainWindow, width = 10)
    self.depositEntry.bind('<Return>', self.depositCallBack)


  def depositCallBack(self,event):
    self.labelText["text"] = 'change the value'

myGUI = MyGUI()

If this helps please let me know!

check if array is empty (vba excel)

The problem with VBA is that there are both dynamic and static arrays...

Dynamic Array Example

Dim myDynamicArray() as Variant

Static Array Example

Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant

Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.

So for clarity's sake, I named my function "IsZeroLengthArray".

    Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
        'Tell VBA to proceed if there is an error to the next line.
        On Error Resume Next
        Dim UpperBound As Integer
        Dim ErrorNumber As Long
        Dim ErrorDescription As String
        Dim ErrorSource As String
        'If the array is empty this will throw an error because a zero-length 
          'array has no UpperBound (or LowerBound).
        'This only works for dynamic arrays.  If this was a static array there 
          'would be both an upper and lower bound.
        UpperBound = UBound(subject)

        'Store the Error Number and then clear the Error object 
         'because we want VBA to treat unintended errors normally
        ErrorNumber = Err.Number
        ErrorDescription = Err.Description
        ErrorSource = Err.Source
        On Error GoTo 0
        'Check the Error Object to see if we have a "subscript out of range" error.  
          'If we do (the number is 9) then we can assume that the array is zero-length.
        If ErrorNumber = 9 Then
            IsZeroLengthArray = True

        'If the Error number is something else then 9 we want to raise 
        'that error again...
        ElseIf ErrorNumber <> 0 Then
            Err.Raise ErrorNumber, ErrorSource, ErrorDescription

        'If the Error number is 0 then we have no error and can assume that the
         'array is not of zero-length
        ElseIf ErrorNumber = 0 Then
            IsZeroLengthArray = False
        End If
    End Function

I hope that this helps others as it helped me.

Install mysql-python (Windows)

I have a slightly different setup, but think my solution will help you out.

I have a Windows 8 Machine, Python 2.7 installed and running my stuff through eclipse.

Some Background:

When I did an easy install it tries to install MySQL-python 1.2.5 which failed with an error: Unable to find vcvarsall.bat. I did an easy_install of pip and tried the pip install which also failed with a similar error. They both reference vcvarsall.bat which is something to do with visual studio, since I don't have visual studio on my machine, it left me looking for a different solution, which I share below.

The Solution:

  1. Reinstall python 2.7.8 from 2.7.8 from this will add any missing registry settings, which is required by the next install.
  2. Install 1.2.4 from

After I did both of those installs I was able to query my MySQL db through eclipse.

Python regex for integer?

You need to anchor the regex at the start and end of the string:



^      # Start of string
[0-9]+ # one or more digits 0-9
$      # End of string

importing jar libraries into android-studio

I also faced same obstacle but not able to find out solution from given answers. Might be it's happening due to project path which is having special characters & space etc... So please try to add this line in your build.gradle.

compile files('../app/libs/jtwitter.jar')// pass your .jar file name

".." (Double dot) will find your root directory of your project.

Why did my Git repo enter a detached HEAD state?

Any checkout of a commit that is not the name of one of your branches will get you a detached HEAD. A SHA1 which represents the tip of a branch still gives a detached HEAD. Only a checkout of a local branch name avoids that mode.

See committing with a detached HEAD

When HEAD is detached, commits work like normal, except no named branch gets updated. (You can think of this as an anonymous branch.)

alt text

For example, if you checkout a "remote branch" without tracking it first, you can end up with a detached HEAD.

See git: switch branch without detaching head

Meaning: git checkout origin/main (or origin/master in the old days) would result in:

Note: switching to 'origin/main'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at a1b2c3d My commit message

That is why you should not use git checkout anymore, but the new git switch command.

With git switch, the same attempt to "checkout" (switch to) a remote branch would fail immediately:

git switch origin/main
fatal: a branch is expected, got remote branch 'origin/main'

To add more on git switch:

With Git 2.23 (August 2019), you don't have to use the confusing git checkout command anymore.

git switch can also checkout a branch, and get a detach HEAD, except:

  • it has an explicit --detach option

To check out commit HEAD~3 for temporary inspection or experiment without creating a new branch:

git switch --detach HEAD~3
HEAD is now at 9fc9555312 Merge branch 'cc/shared-index-permbits'
  • it cannot detached by mistake a remote tracking branch


C:\Users\vonc\arepo>git checkout origin/master
Note: switching to 'origin/master'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

Vs. using the new git switch command:

C:\Users\vonc\arepo>git switch origin/master
fatal: a branch is expected, got remote branch 'origin/master'

If you wanted to create a new local branch tracking a remote branch:

git switch <branch> 

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to

git switch -c <branch> --track <remote>/<branch>

No more mistake!
No more unwanted detached HEAD!

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.

Credits goes to @JeroenMostert for giving me the solution.

Build .NET Core console application to output an EXE

The following will produce, in the output directory,

  • all the package references
  • the output assembly
  • the bootstrapping exe

But it does not contain all .NET Core runtime assemblies.


  <BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>

<Target Name="GenerateNetcoreExe"
        Condition="'$(IsNestedBuild)' != 'true'">
  <RemoveDir Directories="$(Temp)" />
    Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
    <Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />


I wrapped it up in a sample here:

iptables LOG and DROP in one rule

Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.

Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.

Let's create a chain to log and accept:

iptables -N LOG_ACCEPT

And let's populate its rules:

iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT

Now let's create a chain to log and drop:

iptables -N LOG_DROP

And let's populate its rules:

iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP

Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:

iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP

How do I to insert data into an SQL table using C# as well as implement an upload function?

You should use parameters in your query to prevent attacks, like if someone entered '); drop table ArticlesTBL;--' as one of the values.

string query = "INSERT INTO ArticlesTBL (ArticleTitle, ArticleContent, ArticleType, ArticleImg, ArticleBrief,  ArticleDateTime, ArticleAuthor, ArticlePublished, ArticleHomeDisplay, ArticleViews)";
query += " VALUES (@ArticleTitle, @ArticleContent, @ArticleType, @ArticleImg, @ArticleBrief, @ArticleDateTime, @ArticleAuthor, @ArticlePublished, @ArticleHomeDisplay, @ArticleViews)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleTitle", ArticleTitleTextBox.Text);
myCommand.Parameters.AddWithValue("@ArticleContent", ArticleContentTextBox.Text);
// ... other parameters

Exploits of a Mom


How do I generate a random int number?

I've tried all of these solutions excluding the COBOL answer... lol

None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

It's all about the seed.

I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

public int GenerateRandom(int min, int max)
    var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
    return new Random(seed).Next(min, max);

Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

public static class IntUtil
   private static Random random;

   private static void Init()
      if (random == null) random = new Random();

   public static int Random(int min, int max)
      return random.Next(min, max);

Then you can use the static class like so..

for(var i = 0; i < 1000; i++)
   int randomNumber = IntUtil.Random(1,100);

I admit I like this approach better.

Java read file and store text in an array

Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.

Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));

StringBuilder sb = new Stringbuilder();
while(inFile1.hasNext()) {

String[] yourArray = sb.toString().split(", ");

3D Plotting from X, Y, Z Data, Excel or other Tools

You can use r libraries for 3 D plotting.

Steps are:

First create a data frame using data.frame() command.

Create a 3D plot by using scatterplot3D library.

Or You can also rotate your chart using rgl library by plot3d() command.

Alternately you can use plot3d() command from rcmdr library.

In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.


How do I get the time of day in javascript/Node.js?

Check out the moment.js library. It works with browsers as well as with Node.JS. Allows you to write




without prior writing of any functions.

android - How to get view from context?

For example you can find any textView:

TextView textView = (TextView) ((Activity) context).findViewById(;

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

It might be a wrong path. Ensure in your main app file you have:


Example link to your css as:

<link href="/css/clean-blog.min.css" rel="stylesheet">

similar for link to js files:

<script src="/js/clean-blog.min.js"></script>

How to increase the max upload file size in ASP.NET?

If you use ssl cert your ssl pipeline F5 settings configure.Important.

ASP.NET Core Web API exception handling

Use built-in Exception Handling Middleware

Step 1. In your startup, register your exception handling route:

// It should be one of your very first registrations
app.UseExceptionHandler("/error"); // Add this
app.UseEndpoints(endpoints => endpoints.MapControllers());

Step 2. Create controller that will handle all exceptions and produce error response:

[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorsController : ControllerBase
    public MyErrorResponse Error()
        var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
        var exception = context.Error; // Your exception
        var code = 500; // Internal Server Error by default

        if      (exception is MyNotFoundException) code = 404; // Not Found
        else if (exception is MyUnauthException)   code = 401; // Unauthorized
        else if (exception is MyException)         code = 400; // Bad Request

        Response.StatusCode = code; // You can use HttpStatusCode enum instead

        return new MyErrorResponse(exception); // Your error model

A few important notes and observations:

  • [ApiExplorerSettings(IgnoreApi = true)] is needed. Otherwise, it may break your Swashbuckle swagger
  • Again, app.UseExceptionHandler("/error"); has to be one of the very top registrations in your Startup Configure(...) method. It's probably safe to place it at the top of the method.
  • The path in app.UseExceptionHandler("/error") and in controller [Route("error")] should be the same, to allow the controller handle exceptions redirected from exception handler middleware.

Microsoft documentation for this subject is not that great but has some interesting ideas. I'll just leave the link here.

Response models and custom exceptions

Implement your own response model and exceptions. This example is just a good starting point. Every service would need to handle exceptions in its own way. But with this code, you have full flexibility and control over handling exceptions and returning a proper result to the caller.

An example of error response model (just to give you some ideas):

public class MyErrorResponse
    public string Type { get; set; }
    public string Message { get; set; }
    public string StackTrace { get; set; }

    public MyErrorResponse(Exception ex)
        Type = ex.GetType().Name;
        Message = ex.Message;
        StackTrace = ex.ToString();

For simpler services, you might want to implement http status code exception that would look like this:

public class HttpStatusException : Exception
    public HttpStatusCode Status { get; private set; }

    public HttpStatusException(HttpStatusCode status, string msg) : base(msg)
        Status = status;

This can be thrown like that:

throw new HttpStatusCodeException(HttpStatusCode.NotFound, "User not found");

Then your handling code could be simplified to:

if (exception is HttpStatusException httpException)
    code = (int) httpException.Status;

Why so un-obvious HttpContext.Features.Get<IExceptionHandlerFeature>()?

ASP.NET Core developers embraced the concept of middlewares where different aspects of functionality such as Auth, Mvc, Swagger etc. are separated and executed sequentially by processing the request and returning the response or passing the execution to the next middleware. With this architecture, MVC itself, for instance, would not be able to handle errors happening in Auth. So, they came up with exception handling middleware that catches all the exceptions happening in middlewares registered down in the pipeline, pushes exception data into HttpContext.Features, and re-runs the pipeline for specified route (/error), allowing any middleware to handle this exception, and the best way to handle it is by our Controllers to maintain proper content negotiation.

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:


Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    $ vi "$(dosbox -printconf)"
    $ dosbox
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

How to convert a string with comma-delimited items to a list in Python?

The following Python code will turn your string into a list of strings:

import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)

How can I insert values into a table, using a subquery with more than one result?

You want:

insert into prices (group, id, price)
    7, articleId, 1.50
from article where name like 'ABC%';

where you just hardcode the constant fields.

Why would you use Expression<Func<T>> rather than Func<T>?

Overly simplified here, but Func is a machine, whereas Expression is a blueprint. :D

Delete all lines starting with # or ; in Notepad++

Its possible, but not directly.

In short, go to the search, use your regex, check "mark line" and click "Find all". It results in bookmarks for all those lines.

In the search menu there is a point "delete bookmarked lines" voila.

I found the answer here (the correct answer is the second one, not the accepted!): How to delete specific lines on Notepad++?

How to clear cache of Eclipse Indigo

If you are asking about cache where eclipse stores your project and workspace information right click on your project(s) and choose refresh. Then go to project in the menu on top of the window and click "clean".

This typically does what you need.

If it does not try to remove project from the workspace (just press "delete" on the project and then say that you DO NOT want to remove the sources). Then open project again.

If this does not work too, do the same with the workspace. If this still does not work, perform fresh checkout of your project from source control and create new workspace.

Well, this should work.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Working with Bjarne Stroustrup Programming Principles and Practice Using C++ "FLTK" example i got the same error but after like 1 hour i got an idea, i tracked one of the libs already seen in Project Properties -> Linker -> Input -> Additional Dependencies, in my case i tracked the kernel32.lib to see where was located and saw there were many kernel32.lib's in different folders. So i started copy the FLTK libs in those folders and the last one i tried worked. Visual Studio 2013 Express found the fltkd.lib and the code worked.

In my case the correct route was C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86

I don't know how to set that route inside Visual Studio.

Not sure if that Windows kits folder was created when i installed Microsoft Windows SDK for Windows 7 and .NET Framework 4 (ISO)

Hope that helps you people.

What is an OS kernel ? How does it differ from an operating system?

It seems that the original metaphor that got us the word "kernel" for this in the first place has been forgotten. The metaphor is that an operating system is a seed. The "kernel" of the seed is the core of the operating system, providing operating system services to applications programs, which is surrounded by the "shell" of the seed that is what users see from the outside.

Some people want to tie "kernel" (and, indeed, "shell") down to be more specific than that. But in truth there's a lot of variation across operating systems. Not the least these variations is what constitutes a "shell" (which can range from Solaris' sh through Netware's Console Command Interpreter to OS/2's Workplace Shell and Windows NT's Explorer), but there's also a lot of variance from one operating system to another in what is, and isn't, a part of a "kernel" (which may or may not include disk I/O, for example).

It's best to remember that these terms are metaphors.

Further reading

Multiple conditions in a C 'for' loop

There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to && or ||.

javascript regex - look behind alternative?

Below is a positive lookbehind JavaScript alternative showing how to capture the last name of people with 'Michael' as their first name.

1) Given this text:

const exampleText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";

get an array of last names of people named Michael. The result should be: ["Jordan","Johnson","Green","Wood"]

2) Solution:

function getMichaelLastName2(text) {
  return text
    .match(/(?:Michael )([A-Z][a-z]+)/g)
    .map(person => person.slice(person.indexOf(' ')+1));

// or even
    .map(person => person.slice(8)); // since we know the length of "Michael "

3) Check solution

console.log(JSON.stringify(    getMichaelLastName(exampleText)    ));
// ["Jordan","Johnson","Green","Wood"]

Demo here:

You can also try it out by running the snippet below.

const inputText = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green Miller and Michael Wood?";_x000D_
function getMichaelLastName(text) {_x000D_
  return text_x000D_
    .match(/(?:Michael )([A-Z][a-z]+)/g)_x000D_
    .map(person => person.slice(8));_x000D_
console.log(JSON.stringify(    getMichaelLastName(inputText)    ));

Generate fixed length Strings filled with whitespaces

For right pad you need String.format("%0$-15s", str)

i.e. - sign will "right" pad and no - sign will "left" pad

See my example:

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
            Scanner sc=new Scanner(;
            for(int i=0;i<3;i++)
                String s1=sc.nextLine();
                Scanner line = new Scanner( s1);
                line=line.useDelimiter(" ");
                String language =;
                int mark = line.nextInt();;
                System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);

The input must be a string and a number

example input : Google 1

Add disabled attribute to input element using Javascript

You can get the DOM element, and set the disabled property directly.

$(".shownextrow").click(function() { 
          .find('.longboxsmall').hide()[0].disabled = 'disabled';

or if there's more than one, you can use each() to set all of them:

$(".shownextrow").click(function() { 
          .find('.longboxsmall').each(function() {
      = 'none';
               this.disabled = 'disabled';

How do I find all files containing specific text on Linux?

You can use:

grep -r "string to be searched"  /path/to/dir

The r stands for recursive and so will search in the path specified and also its sub-directories. This will tell you the file name as well as print out the line in the file where the string appears.

Or a command similar to the one you are trying (example: ) for searching in all javascript files (*.js):

find . -name '*.js' -exec grep -i 'string to search for' {} \; -print

This will print the lines in the files where the text appears, but it does not print the file name.

In addition to this command, we can write this too: grep -rn "String to search" /path/to/directory/or/file -r: recursive search n: line number will be shown for matches

How can I insert vertical blank space into an html document?

write it like this

p {
    padding-bottom: 3cm;


p {
    margin-bottom: 3cm;

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

Jquery Ajax, return success/error from 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");


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


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:

        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:

        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

file_put_contents - failed to open stream: Permission denied

I know that it is a very old question, but I wanted to add the good solution with some in depth explanation. You will have to execute two statements on Ubuntu like systems and then it works like a charm.

Permissions in Linux can be represented with three digits. The first digit defines the permission of the owner of the files. The second digit the permissions of a specific group of users. The third digit defines the permissions for all users who are not the owner nor member of the group.

The webserver is supposed to execute with an id that is a member of the group. The webserver should never run with the same id as the owner of the files and directories. In Ubuntu runs apache under the id www-data. That id should be a member of the group for whom the permissions are specified.

To give the directory in which you want to change the content of files the proper rights, execute the statement:

find %DIR% -type d -exec chmod 770 {} \;

.That would imply in the question of the OP that the permissions for the directory %ROOT%/database should be changed accordingly. It is therefor important not to have files within that directory that should never get changed, or removed. It is therefor best practice to create a separate directory for files whose content must be changed.

Reading permissions (4) for a directory means being able to collect all files and directories with their metadata within a directory. Write permissions (2) gives the permission to change the content of the directory. Implying adding and removing files, changing permissions etc.. Execution permission (1) means that you have the right to go into that directory. Without the latter is it impossible to go deeper into the directory. The webserver needs read, write and execute permissions when the content of a file should be changed. Therefor needs the group the digit 7.

The second statement is in the question of the OP:

find %DOCUMENT_ROOT%/database -type f -exec chmod 760 {} \;

Being able to read and write a document is required, but it is not required to execute the file. The 7 is given to the owner of the files, the 6 to the group. The webserver does not need to have the permission to execute the file in order to change its content. Those write permissions should only be given to files in that directory.

All other users should not be given any permission.

For directories that do not require to change its files are group permissions of 5 sufficient. Documentation about permissions and some examples:

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {

<div id="music" class="nav">Music I Like 
    <a href=""> 
        <span class="hyperspan"></span>

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

Trimming text strings in SQL Server 2008

I would try something like this for a Trim function that takes into account all white-space characters defined by the Unicode Standard (LTRIM and RTRIM do not even trim new-line characters!):

IF OBJECT_ID(N'dbo.IsWhiteSpace', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.IsWhiteSpace;_x000D_
-- Determines whether a single character is white-space or not (according to the UNICODE standard)._x000D_
 SELECT @WHITESPACE = ' ' + NCHAR(13) + NCHAR(10) + NCHAR(9) + NCHAR(11) + NCHAR(12) + NCHAR(133) + NCHAR(160) + NCHAR(5760) + NCHAR(8192) + NCHAR(8193) + NCHAR(8194) + NCHAR(8195) + NCHAR(8196) + NCHAR(8197) + NCHAR(8198) + NCHAR(8199) + NCHAR(8200) + NCHAR(8201) + NCHAR(8202) + NCHAR(8232) + NCHAR(8233) + NCHAR(8239) + NCHAR(8287) + NCHAR(12288) + NCHAR(6158) + NCHAR(8203) + NCHAR(8204) + NCHAR(8205) + NCHAR(8288) + NCHAR(65279);_x000D_
 RETURN 1;_x000D_
IF OBJECT_ID(N'dbo.Trim', N'FN') IS NOT NULL_x000D_
    DROP FUNCTION dbo.Trim;_x000D_
-- Removes all leading and tailing white-space characters. NULL is converted to an empty string._x000D_
 -- Check tiny strings (NULL, 0 or 1 chars)_x000D_
  IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1)) = 1) RETURN '';_x000D_
  RETURN @TEXT;_x000D_
 -- Check whether we have to LTRIM/RTRIM_x000D_
 SELECT @SKIPSTART = dbo.IsWhiteSpace(SUBSTRING(@TEXT, 1, 1));_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- FULLTRIM_x000D_
   -- Determine start white-space length_x000D_
   SELECT @INDEX = 2;_x000D_
   WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise assign index as @SKIPSTART_x000D_
    -- Increase character index_x000D_
    SELECT @INDEX = (@INDEX + 1);_x000D_
   -- Return '' if the whole string is white-space_x000D_
   IF (@SKIPSTART = (@TEXTLENGTH - 1)) RETURN ''; _x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   -- Return trimmed string_x000D_
  END _x000D_
  -- LTRIM_x000D_
  -- Determine start white-space length_x000D_
  SELECT @INDEX = 2;_x000D_
  WHILE (@INDEX < @TEXTLENGTH) BEGIN -- Hint: The last character is already checked_x000D_
   -- Stop loop if no white-space_x000D_
   IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
   -- Otherwise assign index as @SKIPSTART_x000D_
   -- Increase character index_x000D_
   SELECT @INDEX = (@INDEX + 1);_x000D_
  -- Return trimmed string_x000D_
  -- RTRIM_x000D_
  IF (@SKIPEND = 1) BEGIN_x000D_
   -- Determine end white-space length_x000D_
   SELECT @INDEX = (@TEXTLENGTH - 1);_x000D_
   WHILE (@INDEX > 1) BEGIN _x000D_
    -- Stop loop if no white-space_x000D_
    IF (dbo.IsWhiteSpace(SUBSTRING(@TEXT, @INDEX, 1)) = 0) BREAK;_x000D_
    -- Otherwise increase @SKIPEND_x000D_
    SELECT @SKIPEND = (@SKIPEND + 1);_x000D_
    -- Decrease character index_x000D_
    SELECT @INDEX = (@INDEX - 1);_x000D_
   -- Return trimmed string_x000D_
  END _x000D_
 -- NO TRIM_x000D_

Problems with Android Fragment back stack

If you are Struggling with addToBackStack() & popBackStack() then simply use

FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(, new HomeFragment(), "Home");

In your Activity In OnBackPressed() find out fargment by tag and then do your stuff

Fragment home = getSupportFragmentManager().findFragmentByTag("Home");

if (home instanceof HomeFragment && home.isVisible()) {
    // do you stuff

For more Information I never use addToBackStack() for handling fragment.

error: RPC failed; curl transfer closed with outstanding read data remaining

This problem usually occurs while cloning large repos. If git clone --depth 1 does not work on windows cmd. Try running the command in windows powershell.

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".

How to convert a Date to a formatted string in

myDate.ToString("yyyy-MM-dd HH:mm:ss")

the capital HH is for 24 hours format as you specified

Changing background colour of tr element on mouseover

tr:hover td {background-color:#000;}

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: = 10

In [102]: df.append(s)
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

compare two list and return not matching items using linq

The naive approach:

MsgList.Where(x => !SentList.Any(y => y.MsgID == x.MsgID))

Be aware this will take up to m*n operations as it compares every MsgID in SentList to each in MsgList ("up to" because it will short-circuit when it does happen to match).

How can I cast int to enum?

The following is a slightly better extension method:

public static string ToEnumString<TEnum>(this int enumValue)
    var enumString = enumValue.ToString();
    if (Enum.IsDefined(typeof(TEnum), enumValue))
        enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
    return enumString;

Number prime test in JavaScript

Following code uses most efficient way of looping to check if a given number is prime.

function checkPrime(number){    
    if (number==2 || number==3) {
    return true
    if(number<2 ||number % 2===0){
        return false
        for (let index = 3; index <= Math.sqrt(number); index=index+2) {
            if (number%index===0) {
                return false
    return true
  1. First check rules out 2 and lesser numbers and all even numbers
  2. Using Math.sqrt() to minimize the looping count
  3. Incrementing loop counter by 2, skipping all even numbers, further reducing loop count by half

MomentJS getting JavaScript Date in UTC

A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.

Here's some code to illustrate. A point is time is captured in three different ways.

var moment = require( 'moment' );

var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );

//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );

//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate  = ' + utcDate );

//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );

Which outputs this:

localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate  = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570

In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).

As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!

Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.

Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate ), and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log calls in the example.

Java: Why is the Date constructor deprecated, and what do I use instead?

One reason that the constructor is deprecated is that the meaning of the year parameter is not what you would expect. The javadoc says:

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date).

Notice that the year field is the number of years since 1900, so your sample code most likely won't do what you expect it to do. And that's the point.

In general, the Date API only supports the modern western calendar, has idiosyncratically specified components, and behaves inconsistently if you set fields.

The Calendar and GregorianCalendar APIs are better than Date, and the 3rd-party Joda-time APIs were generally thought to be the best. In Java 8, they introduced the java.time packages, and these are now the recommended alternative.

Response to preflight request doesn't pass access control check

A very common cause of this error could be that the host API had mapped the request to a http method (e.g. PUT) and the API client is calling the API using a different http method (e.g. POST or GET)

Setting max width for body using Bootstrap

I don't know if this was pointed out here. The settings for .container width have to be set on the Bootstrap website. I personally did not have to edit or touch anything within CSS files to tune my .container size which is 1600px. Under Customize tab, there are three sections responsible for media and the responsiveness of the web:

  • Media queries breakpoints
  • Grid system
  • Container sizes

Besides Media queries breakpoints, which I believe most people refer to, I've also changed @container-desktop to (1130px + @grid-gutter-width) and @container-large-desktop to (1530px + @grid-gutter-width). Now, the .container changes its width if my browser is scaled up to ~1600px and ~1200px. Hope it can help.

Check if xdebug is working


php -m -c

in your terminal, and then look for [Zend Modules]. It should be somewhere there if it is loaded!


If you're using Ubuntu, it may not show up here because you need to add the xdebug settings from /etc/php5/apache2/php.ini into /etc/php5/cli/php.ini. Mine are

zend_extension = /usr/lib/php5/20121212/

Check object empty

This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            if (field.get(this)!=null) {
                return false;
        } catch (Exception e) {
          System.out.println("Exception occured in processing");
    return true;

What does the error "arguments imply differing number of rows: x, y" mean?

Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:

I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.

I had this:

    user_id = gift$email,
    sourced_from_agent_id = gift$source,
    method_used = method,
    given_to = gift$account,
    recurring_subscription_id = NULL,
    notes = notes,
    stringsAsFactors = FALSE

turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.

PHP code is not being executed, instead code shows on the page

I'm posting this answer because my Virtualmin/Webmin admin interface decided it was a good idea to disable my PHP engine.. took me a while to find the solution, so I thought I'd share it with you guys:

Also, be sure to check that none of your website config files related to this specific host or virtualhost have any php_admin_value's in them that turn off PHP, like this:

php_admin_value engine Off

When in doubt, comment it...

# php_admin_value engine Off

And restart your webserver.

MySQL's now() +1 day

You can use:


If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:


How do I programmatically force an onchange event on an input?

If you add all your events with this snippet of code:

//put this somewhere in your JavaScript:
HTMLElement.prototype.addEvent = function(event, callback){
  if(! = {};
  if(![event]){[event] = [];
    var element = this;
    this['on'+event] = function(e){
      var events =[event];
      for(var i=0;i<events.length;i++){
//use like this:
element.addEvent('change', function(e){...});

then you can just use element.on<EVENTNAME>() where <EVENTNAME> is the name of your event, and that will call all events with <EVENTNAME>

How to compare two JSON have the same properties without order?

lodash will work, tested even for angular 5,

var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": 
var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", 
  "allowExternalMembers": "false"};

 if(_.isEqual(remoteJSON, localJSON)){

it works, for installation in angular, follow this

Could someone explain this for me - for (int i = 0; i < 8; i++)

for(<first part>; <second part>; <third part>)

This code is evaluated like this:

  1. Run <first part>
  2. If <second part> is false, skip to the end
  3. DoStuff();
  4. Run <third part>
  5. Goto 2

So for your example:

for (int i = 0; i < 8; i++)
  1. Set i to 0.
  2. If i is not less than 8, skip to the end.
  3. DoStuff();
  4. i++
  5. Goto 2

So the loop runs one time with i set to each value from 0 to 7. Note that i is incremented to 8, but then the loop ends immediately afterwards; it does not run with i set to 8.

Run an Ansible task only when the variable contains a specific string

This works for me in Ansible 2.9:

variable1 = 
variable2 = 

when: ".com" in variable1

and for not:

when: not ".com" in variable2

How to get process ID of background process?

pgrep can get you all of the child PIDs of a parent process. As mentioned earlier $$ is the current scripts PID. So, if you want a script that cleans up after itself, this should do the trick:

trap 'kill $( pgrep -P $$ | tr "\n" " " )' SIGINT SIGTERM EXIT

Cannot read configuration file due to insufficient permissions

I tried most of the previous suggestions but in vain. I can't reload the website, so I edited the .csproj file and changed the port number and it worked immediately:


Editing .csproj file

Uncaught TypeError: Object #<Object> has no method 'movingBoxes'

I had the same problem. I changed the order of the scripts in the head part, and it worked for me. Every script the plugin needs - needs to stay close.

For example:

<script src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript"> 
$(document).ready(function() {
            fx: 'fade' 

jsonify a SQLAlchemy result set in Flask

Flask-Restful 0.3.6 the Request Parsing recommend marshmallow

marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.

A simple marshmallow example is showing below.

from marshmallow import Schema, fields

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()

from marshmallow import pprint

user = User(name="Monty", email="[email protected]")
schema = UserSchema()
result = schema.dump(user)
# {"name": "Monty",
#  "email": "[email protected]",
#  "created_at": "2014-08-17T14:54:16.049594+00:00"}

The core features contain

Declaring Schemas
Serializing Objects (“Dumping”)
Deserializing Objects (“Loading”)
Handling Collections of Objects
Specifying Attribute Names
Specifying Serialization/Deserialization Keys
Refactoring: Implicit Field Creation
Ordering Output
“Read-only” and “Write-only” Fields
Specify Default Serialization/Deserialization Values
Nesting Schemas
Custom Fields

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

this works for me:

It can be used inside the dialog, but the dialog can´t be inside any componet such as panels, accordion, etc.

How to redirect to the same page in PHP

A quick easy approach if you are not concerned about query params:

header("location: ./");

Filter object properties by key in ES6

A simpler solution without using filter can be achieved with Object.entries() instead of Object.keys()

const raw = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }

const allowed = ['item1', 'item3'];

const filtered = Object.entries(raw).reduce((acc,elm)=>{
  const [k,v] = elm
  if (allowed.includes(k)) {
    acc[k] = v 
  return acc

How to combine two lists in R

c can be used on lists (and not only on vectors):

# you have
l1 = list(2, 3)
l2 = list(4)

# you want
list(2, 3, 4)
[1] 2

[1] 3

[1] 4

# you can do
c(l1, l2)
[1] 2

[1] 3

[1] 4

If you have a list of lists, you can do it (perhaps) more comfortably with, eg:, list(l1, l2))

Duplicating a MySQL table, indices, and data

Go to phpMyAdmin and select your original table then select "Operations" tab in the "Copy table to (database.table)" area. Select the database where you want to copy and add a name for your new table.

copy table - phyMyAdmin Screenshot

Twitter Bootstrap Datepicker within modal window

Add z-indez in class ui-datepicker

    .ui-datepicker{ z-index:1151 !important; }

Android ImageView Fixing Image Size

You can also try this, suppose if you want to make a back image button and you have "500x500 png" and want it to fit in small button size.

Use dp to fix ImageView's size.

add this line of code to your Imageview.




What are the benefits of using C# vs F# or F# vs C#?

General benefits of functional programming over imperative languages:

You can formulate many problems much easier, closer to their definition and more concise in a functional programming language like F# and your code is less error-prone (immutability, more powerful type system, intuitive recurive algorithms). You can code what you mean instead of what the computer wants you to say ;-) You will find many discussions like this when you google it or even search for it at SO.

Special F#-advantages:

  • Asynchronous programming is extremely easy and intuitive with async {}-expressions - Even with ParallelFX, the corresponding C#-code is much bigger

  • Very easy integration of compiler compilers and domain-specific languages

  • Extending the language as you need it: LOP

  • Units of measure

  • More flexible syntax

  • Often shorter and more elegant solutions

Take a look at this document

The advantages of C# are that it's often more accurate to "imperative"-applications (User-interface, imperative algorithms) than a functional programming language, that the .NET-Framework it uses is designed imperatively and that it's more widespread.

Furthermore you can have F# and C# together in one solution, so you can combine the benefits of both languages and use them where they're needed.

How to remove all listeners in an element?

If you’re not opposed to jquery, this can be done in one line:

jQuery 1.7+


jQuery < 1.7


Here’s an example:

How to substring in jquery

var name = "nameGorge";

What is difference between XML Schema and DTD?

DTD can have only two types of data, the CDATA and the PCDATA. But in a schema you can use all the primitive data type that you use in the programming language and you have the flexibility of defining your own custom data types.

The developer building a schema can create custom data types based on the core data types and by using different operators and modifiers.

Simple int to char[] conversion

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

But you probably meant "i want to stringify a number", so ignore this response :-)

one line if statement in php

Use ternary operator:

echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis

But in this case you can't use shorter reversed version because it will return bool(true) in first condition.

echo (($test != '') ?: $redText); //this will not work properly for this case

How to check if a div is visible state or not?

is(':visible') checks the display property of an element, you can use css method.

if (!$("#singlechatpanel-1").css('visibility') === 'hidden') {
   // ...

If you set the display property of the element to none then your if statement returns true.

How can I print out just the index of a pandas dataframe?

You can access the index attribute of a df using df.index[i]

>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
   a         b
0  0  1.088998
1  1 -1.381735
2  2  0.035058
3  3 -2.273023
4  4  1.345342

>> df.index[1] ## Second index
>> df.index[-1] ## Last index

>> for i in xrange(len(df)):print df.index[i] ## Using loop

Making text background transparent but not text itself

Don't use opacity for this, set the background to an RGBA-value instead to only make the background semi-transparent. In your case it would be like this.

.content {
    background: rgb(204, 204, 204); /* Fallback for older browsers without RGBA-support */
    background: rgba(204, 204, 204, 0.5);

See for more info and samples of rgba-values in css.

Writing string to a file on a new line every time

Use "\n":

file.write("My String\n")

See the Python manual for reference.

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

My problems solved by remove all the runtime part

        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="" newVersion=""/>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
                <bindingRedirect oldVersion="" newVersion=""/>

How to read a PEM RSA private key from .NET


under Cryptography Application Block.

Don't know if you will get your answer, but it's worth a try.

Edit after Comment.

Ok then check this code.

using System.Security.Cryptography;

public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { 
    X509Certificate2 myCertificate; 
        myCertificate = new X509Certificate2(PathToPrivateKeyFile); 
    } catch{ 
        throw new CryptographicException("Unable to open key file."); 

    RSACryptoServiceProvider rsaObj; 
    if(myCertificate.HasPrivateKey) { 
         rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 
    } else 
        throw new CryptographicException("Private key not contained within certificate."); 

    if(rsaObj == null) 
        return String.Empty; 

    byte[] decryptedBytes; 
        decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); 
    } catch { 
        throw new CryptographicException("Unable to decrypt data."); 

    //    Check to make sure we decrpyted the string 
   if(decryptedBytes.Length == 0) 
        return String.Empty; 
        return System.Text.Encoding.UTF8.GetString(decryptedBytes); 

Function ereg_replace() is deprecated - How to clear this bug?

print $input."<hr>".ereg_replace('/&/', ':::', $input);


print $input."<hr>".preg_replace('/&/', ':::', $input);

More example :

$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );

is changed to

$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)

Here is the result. enter image description here

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

Not sure what is the difference between .cfg & .cnf In my server I couldn't find .cfg or .cnf I had created a new file for the same and placed it in the following folder /usr/local/ssl/bin

executed the

.\openssl genrsa -des3 -out <key name>.key 2048 

went great..

Send XML data to webservice using php curl

After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:

//Store your XML Request in a variable
    $input_xml = '<AvailRequest>
            <Clientpassword>*Your API Password</Clientpassword>

Now I've made a little changes in the above curl_setopt declaration as follows:

    $url = "";

        //setting the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
        curl_setopt($ch, CURLOPT_POSTFIELDS,
                    "xmlRequest=" . $input_xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $data = curl_exec($ch);

        //convert the XML result into array
        $array_data = json_decode(json_encode(simplexml_load_string($data)), true);


That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.

Using the slash character in Git branch name

just had the same issue, but i could not find the conflicting branch anymore.

in my case the repo had and "foo" branch before, but not anymore and i tried to create and checkout "foo/bar" from remote. As i said "foo" did not exist anymore, but the issue persisted.

In the end, the branch "foo" was still in the .git/config file, after deleting it everything was alright :)

Clang vs GCC - which produces faster binaries?

A peculiar difference I have noted on gcc 5.2.1 and clang 3.6.2 is that if you have a critical loop like:

for (;;) {
    if (!visited) {
    if (!*node) break;

Then gcc will, when compiling with -O3 or -O2, speculatively unroll the loop eight times. Clang will not unroll it at all. Through trial and error I found that in my specific case with my program data, the right amount of unrolling is five so gcc overshot and clang undershot. However, overshooting was more detrimental to performance, so gcc performed much worse here.

I have no idea if the unrolling difference is a general trend or just something that was specific to my scenario.

A while back I wrote a few garbage collectors to teach myself more about performance optimization in C. And the results I got is in my mind enough to slightly favor clang. Especially since garbage collection is mostly about pointer chasing and copying memory.

The results are (numbers in seconds):

|Type                 |GCC  |Clang|
|Copying GC           |22.46|22.55|
|Copying GC, optimized|22.01|20.22|
|Mark & Sweep         | 8.72| 8.38|
|Ref Counting/Cycles  |15.14|14.49|
|Ref Counting/Plain   | 9.94| 9.32|

This is all pure C code, and I make no claim about either compiler's performance when compiling C++ code.

On Ubuntu 15.10, x86.64, and an AMD Phenom(tm) II X6 1090T processor.

How can I convert a dictionary into a list of tuples?

By keys() and values() methods of dictionary and zip.

zip will return a list of tuples which acts like an ordered dictionary.


>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]

Returning JSON response from Servlet to Javascript/JSP page

I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

What is compiler, linker, loader?

Wikipedia ought to have a good answer, here's my thoughts:

  • Compiler: reads something.c source, writes something.o object.
  • Linker: joins several *.o files into an executable program.
  • Loader: code that loads an executable into memory and starts it running.

How to return dictionary keys as a list in Python?

A bit off on the "duck typing" definition -- dict.keys() returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)

In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list().

Very similarly for zip() -- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?

This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.

dict.keys() should work with comprehensions, though -- check carefully for typos or something... it works fine for me:

>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

class MyConfig{

    private String baseUrl;
    private String authorizeUrl;
    private String tokenUrl;

    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        return resource;

    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));

class MyService {

    private OAuth2RestOperations restTemplate;

    public MyService() {

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github to depict your situation because I could not find any samples for your scenario .

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

How to share data between different threads In C# using AOP?

You can pass an object as argument to the Thread.Start and use it as a shared data storage between the current thread and the initiating thread.

You can also just directly access (with the appropriate locking of course) your data members, if you started the thread using the instance form of the ThreadStart delegate.

You can't use attributes to create shared data between threads. You can use the attribute instances attached to your class as a data storage, but I fail to see how that is better than using static or instance data members.

What is the max size of localStorage values?

I really like cdmckay's answer, but it does not really look good to check the size in a real time: it is just too slow (2 seconds for me). This is the improved version, which is way faster and more exact, also with an option to choose how big the error can be (default 250,000, the smaller error is - the longer the calculation is):

function getLocalStorageMaxSize(error) {
  if (localStorage) {
    var max = 10 * 1024 * 1024,
        i = 64,
        string1024 = '',
        string = '',
        // generate a random key
        testKey = 'size-test-' + Math.random().toString(),
        minimalFound = 0,
        error = error || 25e4;

    // fill a string with 1024 symbols / bytes    
    while (i--) string1024 += 1e16;

    i = max / 1024;

    // fill a string with 'max' amount of symbols / bytes    
    while (i--) string += string1024;

    i = max;

    // binary search implementation
    while (i > 1) {
      try {
        localStorage.setItem(testKey, string.substr(0, i));

        if (minimalFound < i - error) {
          minimalFound = i;
          i = i * 1.5;
        else break;
      } catch (e) {
        i = minimalFound + (i - minimalFound) / 2;

    return minimalFound;

To test:

console.log(getLocalStorageMaxSize()); // takes .3s
console.log(getLocalStorageMaxSize(.1)); // takes 2s, but way more exact

This works dramatically faster for the standard error; also it can be much more exact when necessary.

How can I divide two integers stored in variables in Python?

Use this line to get the division behavior you want:

from __future__ import division

Alternatively, you could use modulus:

if (a % b) == 0: #do something

Couldn't connect to server

1.Create new folder in d drive D:/data/db

2.Open terminal on D:/data/db

3.Type mongod and enter.

4.Type mongo and enter.

and your mongodb has strated............

Object reference not set to an instance of an object.

I want to extend MattMitchell's answer by saying you can create an extension method for this functionality:

public static IsEmptyOrWhitespace(this string value) {
    return String.IsEmptyOrWhitespace(value);

This makes it possible to call:

string strValue;
if (strValue.IsEmptyOrWhitespace())
     // do stuff

To me this is a lot cleaner than calling the static String function, while still being NullReference safe!

How to trigger ngClick programmatically

Simple sample:


<div id='player'>
    <div id="my-button" ng-click="someFuntion()">Someone</div>


$timeout(function() {
}, 0);

What this does is look for the button's id and perform a click action. Voila.


Sending POST data without form

function redir(data) {_x000D_
  document.getElementById('redirect').innerHTML = '<form style="display:none;" position="absolute" method="post" action="location.php"><input id="redirbtn" type="submit" name="value" value=' + data + '></form>';_x000D_
<button onclick="redir('dataToBeSent');">Next Page</button>_x000D_
<div id="redirect"></div>

You can use this method which creates a new hidden form whose "data" is sent by "post" to "location.php" when a button[Next Page] is clicked.

JavaScript Object Id

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
  if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
  return objIdMap.get(object);

var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

Always pass weak reference of self into block in ARC?

As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog in your operation's dealloc method and confirm that's getting called.

You said:

I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit

The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self, or even just references an instance variable of self, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation subclass is released.

For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.

If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation is getting deallocated). A common example is the use of a repeating NSTimer. Or some custom delegate or other object that is erroneously maintaining a strong reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:

record reference counts in Xcode 6

Or in Xcode 5:

record reference counts in Xcode 5

C# Parsing JSON array of objects

Use newtonsoft like so:

using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

class Program
    static void Main()
        string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche    Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891    Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";

        var resultObjects = AllChildren(JObject.Parse(json))
            .First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))

        foreach (JObject result in resultObjects) {
            foreach (JProperty property in result.Properties()) {
                // do something with the property belonging to result

    // recursively yield all children of json
    private static IEnumerable<JToken> AllChildren(JToken json)
        foreach (var c in json.Children()) {
            yield return c;
            foreach (var cc in AllChildren(c)) {
                yield return cc;

if else condition in blade file (laravel 5.3)

No curly braces required you can directly write

@if($user->status =='waiting')         
      <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>         
      <td>{{ $user->status }}</td>        

How to add hyperlink in JLabel?

I wrote an article on how to set a hyperlink or a mailto on a jLabel.

So just try it :

I think that's exactly what you're searching for.

Here's the complete code example :

 * Example of a jLabel Hyperlink and a jLabel Mailto

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

 * @author ibrabelware
public class JLabelLink extends JFrame {
    private JPanel pan;
    private JLabel contact;
        private JLabel website;
     * Creates new form JLabelLink
    public JLabelLink() {
        this.setSize(300, 100);

        pan = new JPanel();
        contact = new JLabel();
        website = new JLabel();

        contact.setText("<html> contact : <a href=\"\">[email protected]</a></html>");
        contact.setCursor(new Cursor(Cursor.HAND_CURSOR));

        website.setText("<html> Website : <a href=\"\"></a></html>");
        website.setCursor(new Cursor(Cursor.HAND_CURSOR));


     * @param args the command line arguments
    public static void main(String args[]) {
         * Create and display the form
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JLabelLink().setVisible(true);

    private void goWebsite(JLabel website) {
        website.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI(""));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem

    private void sendMail(JLabel contact) {
        contact.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().mail(new URI("mailto:[email protected]?subject=TEST"));
                } catch (URISyntaxException | IOException ex) {
                    //It looks like there's a problem

AngularJS: Service vs provider vs factory

Understanding AngularJS Factory, Service and Provider

All of these are used to share reusable singleton objects. It helps to share reusable code across your app/various components/modules.

From Docs Service/Factory:

  • Lazily instantiated – Angular only instantiates a service/factory when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.


A factory is function where you can manipulate/add logic before creating an object, then the newly created object gets returned.

app.factory('MyFactory', function() {
    var serviceObj = {};
    //creating an object with methods/functions or variables
    serviceObj.myFunction = function() {
        //TO DO:
    //return that object
    return serviceObj;


It can be just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are injecting it inside your controller/factory/directive functions. It is instantiated only once per app.


Simply while looking at the services think about the array prototype. A service is a function which instantiates a new object using the 'new' keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains methods/properties).

app.service('MyService', function() {
    //directly binding events to this context
    this.myServiceFunction = function() {
        //TO DO:


Use it when you need to share a single object throughout the application. For example, authenticated user details, share-able methods/data, Utility functions etc.


A provider is used to create a configurable service object. You can configure the service setting from config function. It returns a value by using the $get() function. The $get function gets executed on the run phase in angular.

app.provider('configurableService', function() {
    var name = '';
    //this method can be be available at configuration time inside app.config.
    this.setName = function(newName) {
        name = newName;
    this.$get = function() {
        var getName = function() {
             return name;
        return {
            getName: getName //exposed object to where it gets injected.


When you need to provide module-wise configuration for your service object before making it available, eg. suppose you want to set your API URL on basis of your Environment like dev, stage or prod


Only provider will be available in config phase of angular, while service & factory are not.

Hope this has cleared up your understanding about Factory, Service and Provider.

css transform, jagged edges in chrome

For canvas in Chrome (Version 52)

All listed answers is about images. But my issue is about canvas in chrome (v.52) with transform rotate. They became jagged and all this methods can't help.

Solution that works for me:

  1. Make canvas larger on 1 px for each side => +2 px for width and height;
  2. Draw image with offset + 1px (in position 1,1 instead of 0,0) and fixed size (size of image should be 2px less than size of canvas)
  3. Apply required rotation

So important code blocks:

// Unfixed version
ctx.drawImage(img, 0, 0, 335, 218);
// Fixed version
ctx.drawImage(img, 1, 1, 335, 218);
/* This style should be applied for fixed version */
canvas {
  margin-left: -1px;
<!--Unfixed version-->
<canvas width="335" height="218"></canvas>
<!--Fixed version-->
<canvas width="337" height="220"></canvas>


Note: there is a lot of nested divs because it is simplified version from my project.

This issue is reproduced also for Firefox for me. There is no such issue on Safari and FF with retina.

And other founded solution is to place canvas into div of same size and apply following css to this div:

overflow: hidden;
box-shadow: 0 0 1px rgba(255,255,255,0);
// Or
//outline:1px solid transparent;

And rotation should be applied to this wrapping div. So listed solution is worked but with small modification.

And modified example for such solution is:

Note: See style of div with class 'third'.

jQuery change method on input type="file"

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });


from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });

MongoDb shuts down with Code 100

Mac Users

Instead of running MongoDB with:

sudo mongod

You can use mongod instead if you:

  1. Locate the data folder of mongodb (usually ~/data)
  2. Add permission to read + write with sudo chmod -R ugo+rw data

If you need to use sudo when running mongodb (sudo mongod), that means you don't have read and write permission on the mongodb data folder

Adding a new line/break tag in XML

The Way to do Line Break in XML is to use &#xA;

It worked for me in Eclipse IDE , when I was designing my XML layout & was using TextView.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

In case the error appears when upgrading from Laravel 6 to Laravel 7, the command composer require laravel/ui "^2.0" solves the problem (see -scaffolding)

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Add FormsModule in Imports Array.

declarations: [
imports: [
providers: [],
bootstrap: [AppComponent]

Or this can be done without using [(ngModel)] by using

<input [value]='' (input)='$' placeholder="name">

instead of

<input [(ngModel)]="" placeholder="Name">

Can grep show only words that match search pattern?

You could translate spaces to newlines and then grep, e.g.:

cat * | tr ' ' '\n' | grep th

Code snippet or shortcut to create a constructor in Visual Studio

As mentioned by many, "ctor" and double TAB works in Visual Studio 2017, but it only creates the constructor with none of the attributes.

To auto-generate with attributes (if there are any), just click on an empty line below them and press Ctrl + .. It'll display a small pop-up from which you can select the "Generate Constructor..." option.