Programs & Examples On #Propertychangelistener

A Listener object that reacts to a changing value for an Objects property/variable

Nginx 403 forbidden for all files

If you still see permission denied after verifying the permissions of the parent folders, it may be SELinux restricting access.

To check if SELinux is running:

# getenforce

To disable SELinux until next reboot:

# setenforce Permissive

Restart Nginx and see if the problem persists. To allow nginx to serve your www directory (make sure you turn SELinux back on before testing this. i.e, setenforce Enforcing)

# chcon -Rt httpd_sys_content_t /path/to/www

See my answer here for more details

Reverse the ordering of words in a string

Here's a nice tweak for those who liked the question... what if the alphabet comprising the swapped words is smaller than 16 chars (16 including "space")? there are many examples for such alphabets: the numeric chars [01234567890.-+] , the genome letters [GATC] , the hawaiian alphabet [aeiouhklmnpv?], morse code [-.] , musical notes [ABCDEFG#m], etc. This allows encoding the chars as nibbles (4bits) and storing two encoded chars inside one 8bit char.

It's still not trivial doing the words swap in a single loop with one cursor moves left-to-right and the other right-to-left. There are actually 4 types of word-copying: copy a word from the left string's side to the right, from the right string's side to the left and the two equivalent copies that involves read/write overlapping: position X->X+y and X->X-y, where y is smaller than X's length.

The nice optimization is that during the first half of the loop words from the right side are encoded into the left (preserving the original left values), but then on the second half words from the left can be copied directly to right and then the left chars are rewritten with their final values...

Here's the C code, which takes any alphabet as parameter:

#define WORDS_DELIMITER  ' '
#define UNMAPPED         0xFF

#define BITS_IN_NIBBLE   4
#define BITS_IN_BYTE     8
#define CHARS_IN_NIBBLE  (1 << BITS_IN_NIBBLE)
#define CHARS_IN_BYTE    (1 << BITS_IN_BYTE)

typedef union flip_char_ {
    unsigned char clear;
    struct {
        unsigned char org:4;
        unsigned char new:4;
    } encoded;
} flip_char_t;

typedef struct codec_ {
    unsigned char nibble2ascii[CHARS_IN_NIBBLE];
    unsigned char ascii2nibble[CHARS_IN_BYTE];
} codec_t;

static int 
codec_init (const unsigned char *alphabet, codec_t *codec)
{
size_t len = strlen(alphabet), i;

if (len > CHARS_IN_NIBBLE) {
    fprintf(stderr, "alphabet is too long!\n");
    return -1;
}
if (strchr(alphabet, WORDS_DELIMITER) == NULL) {
    fprintf(stderr, "missing space in the alphabet\n");
    return -1;
}
strcpy(codec->nibble2ascii, alphabet);
memset(codec->ascii2nibble , UNMAPPED, CHARS_IN_BYTE);
for (i=0; i<len; i++) {
    codec->ascii2nibble[ alphabet[i] ] = i;
}
return 0;
}

static inline int
is_legal_char (const codec_t *codec, const unsigned char ch)
{
return codec->ascii2nibble[ch] != UNMAPPED;
}

static inline unsigned char 
encode_char (const codec_t *codec, unsigned char org, unsigned char new)
{
flip_char_t flip;
flip.encoded.org = codec->ascii2nibble[org];
flip.encoded.new = codec->ascii2nibble[new];
return flip.clear;
} 

static inline unsigned char 
decode_org (const codec_t *codec, unsigned char ch)
{
flip_char_t flip = { .clear = ch };
return codec->nibble2ascii[flip.encoded.org];
}

static inline unsigned char 
decode_new (const codec_t *codec, unsigned char ch)
{
flip_char_t flip = { .clear = ch };
return codec->nibble2ascii[flip.encoded.new];
}

// static void inline
// encode_char (const char *alphabet, const char *
static int 
flip_words (const unsigned char *alphabet, unsigned char *a, size_t len)
{
codec_t codec;     /* mappings of the 16char-alphabet to a nibble */
int r=len-1;       /* right/reader cursor: moves from right to left scanning for words */
int l=0;           /* left/writer cursor: moves from left to right */
int i=0;                      /* word iterator */
int start_word=-1,end_word=-1; /* word boundaries */
unsigned char org_r=0;        /* original value pointed by the right cursor */
int encode=0, rewrite=0;      /* writing states */

if (codec_init(alphabet, &codec) < 0) return -1;

/* parse the buffer from its end backward */
while (r>=0) {
    if (r>=l && !is_legal_char(&codec, a[r])) {
        fprintf(stderr, "illegal char %c in string\n", a[r]);
        return -1;
    }
    /* read the next charachter looking for word boundaries */
    org_r = (r<l) ? decode_org(&codec, a[r]) : a[r];
    /* handle word boundaries */
    if (org_r == WORDS_DELIMITER) {
        /* mark start of word: next char after space after non-space  */ 
        if (end_word>0 && start_word<0) start_word = r/*skip this space*/+1;
        /* rewrite this space if necessary (2nd half) */
        if (r<l) a[r] = decode_new(&codec,a[r]);
    } else {
        /* mark end of word: 1st non-space char after spaces */ 
        if (end_word<0) end_word = r;
        /* left boundary is a word boundary as well */
        if (!r) start_word = r;
    }
    /* Do we have a complete word to process? */
    if (start_word<0 || end_word<0) {
        r--;
        continue;
    }
    /* copy the word into its new location */
    for(i=start_word; i<=end_word; i++, l++) {
        if (i>=l && !is_legal_char(&codec, a[l])) {
            fprintf(stderr, "illegal char %c in string\n", a[l]);
            return -1;
        }
        /* reading phase: value could be encoded or not according to writer's position */
        org_r= (i<l) ? decode_org(&codec, a[i]) : a[i];
        /* overlapping words in shift right: encode and rewrite */
        encode=rewrite=(l>=start_word && l<=end_word && i<l);
        /* 1st half - encode both org and new vals */
        encode|=(start_word-1>l);
        /* 2nd half - decode and rewrite final values */
        rewrite|=(i<l);
        /* writing phase */
        a[l]= encode ? encode_char(&codec, a[l], org_r) : org_r;
        if (rewrite) {
            a[i]=decode_new(&codec, a[i]);
        }
    }
    /* done with this word! */
    start_word=end_word=-1;
    /* write a space delimiter, unless we're at the end */
    if (r) {
        a[l] = l<r ? encode_char(&codec, a[l], WORDS_DELIMITER) : WORDS_DELIMITER;
        l++;
    }
    r--;
}
a[l]=0;
return 0; /* All Done! */
}

How to get multiline input from user

raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:

Python 3

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
    try:
        line = input()
    except EOFError:
        break
    contents.append(line)

Python 2

print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
    try:
        line = raw_input("")
    except EOFError:
        break
    contents.append(line)

How to add anything in <head> through jquery/javascript?

jQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Making an svg image object clickable with onclick, avoiding absolute positioning

It worked by simply replacing the <embed/> tag with <img/> and deleting the type attribute.

For instance, in my code, instead of:

<embed src=\"./images/info_09c.svg\" type=\"image/svg+xml\" width=\"45\" onClick='afiseaza_indicatie($i, \"$indicatii[$i]\")'> 

which does not answer the clicking, I wrote:

<img src=\"./images/info_09c.svg\" height=\"25\" width=\"25\" onClick='afiseaza_indicatie($i, \"$indicatii[$i]\")'> 

It works in Internet Explorer and Google Chrome, and I hope that in the other browsers too.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You want to use URI templates. Look carefully at the README of this project: URLEncoder.encode() does NOT work for URIs.

Let us take your original URL:

http://site-test.test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf

and convert it to a URI template with two variables (on multiple lines for clarity):

http://site-test.test.com/Meetings/IC/DownloadDocument
    ?meetingId={meetingID}&itemId={itemID}&file={file}

Now let us build a variable map with these three variables using the library mentioned in the link:

final VariableMap = VariableMap.newBuilder()
    .addScalarValue("meetingID", "c21c905c-8359-4bd6-b864-844709e05754")
    .addScalarValue("itemID", "a4b724d1-282e-4b36-9d16-d619a807ba67e")
    .addScalarValue("file", "\\\\s604132shvw140\\Test-Documents"
        + "\\c21c905c-8359-4bd6-b864-844709e05754_attachments"
        + "\\7e89c3cb-ce53-4a04-a9ee-1a584e157987\\myDoc.pdf")
    .build();

final URITemplate template
    = new URITemplate("http://site-test.test.com/Meetings/IC/DownloadDocument"
        + "meetingId={meetingID}&itemId={itemID}&file={file}");

// Generate URL as a String
final String theURL = template.expand(vars);

This is GUARANTEED to return a fully functional URL!

How to show MessageBox on asp.net?

You could just simply write but you have to use JavaScript regardless.

Page.ClientScript.RegisterStartupScript(Page.GetType(), "Message Box", "<script language = 'javascript'>alert('dd')</script>");

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I got the same error, here is how I resolved it:

  • Downloaded logs from AWS.
  • Reviewed Nginx logs, no additional details as above.
  • Reviewed node.js logs, AccessDenied AWS SDK permissions error.
  • Checked the S3 bucket that AWS was trying to read from.
  • Added additional bucket with read permission to correct server role.

Even though I was processing large files there were no other errors or settings I had to change once I corrected the missing S3 access.

Android: Create a toggle button with image and no text

I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background

https://gist.github.com/akshaydashrath/9662072

Faking an RS232 Serial Port

I know this is an old post, but in case someone else happens upon this question, one good option is Virtual Serial Port Emulator (VSPE) from Eterlogic It provides an API for creating kernel mode virtual comport devices, i.e. connectors, mappers, splitters etc.
However, some of the advertised capabilities were really not capabilities at all.

EDIT
A much better choice, Eltima. This product is fully baked. Good developer tech support. The product did all it claimed to do. Product options include both desktop applications, as well as software development kits with APIs.

Neither of these products are open source, or free. However, as other posts here have pointed out, there are other options. Here is a list of various serial utilities:

com0com (current)
com0com - With Signed Driver (old version)
Yet another place for com0com with Signed Driver (Pete's Blog)
Tactical Software
Termite
COM Port Serial Emulator
Kermit (obsolete, but still downloadable)
HWVSP3
HHD Software (free edition)

Deprecated meaning?

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

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

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, and WRITE_EXTERNAL_STORAGE are all part of the Android 6.0 runtime permission system. In addition to having them in the manifest as you do, you also have to request them from the user at runtime (using requestPermissions()) and see if you have them (using checkSelfPermission()).

One workaround in the short term is to drop your targetSdkVersion below 23.

But, eventually, you will want to update your app to use the runtime permission system.

For example, this activity works with five permissions. Four are runtime permissions, though it is presently only handling three (I wrote it before WRITE_EXTERNAL_STORAGE was added to the runtime permission roster).

/***
 Copyright (c) 2015 CommonsWare, LLC
 Licensed under the Apache License, Version 2.0 (the "License"); you may not
 use this file except in compliance with the License. You may obtain a copy
 of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
 by applicable law or agreed to in writing, software distributed under the
 License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 OF ANY KIND, either express or implied. See the License for the specific
 language governing permissions and limitations under the License.

 From _The Busy Coder's Guide to Android Development_
 https://commonsware.com/Android
 */

package com.commonsware.android.permmonger;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
  private static final String[] INITIAL_PERMS={
    Manifest.permission.ACCESS_FINE_LOCATION,
    Manifest.permission.READ_CONTACTS
  };
  private static final String[] CAMERA_PERMS={
    Manifest.permission.CAMERA
  };
  private static final String[] CONTACTS_PERMS={
      Manifest.permission.READ_CONTACTS
  };
  private static final String[] LOCATION_PERMS={
      Manifest.permission.ACCESS_FINE_LOCATION
  };
  private static final int INITIAL_REQUEST=1337;
  private static final int CAMERA_REQUEST=INITIAL_REQUEST+1;
  private static final int CONTACTS_REQUEST=INITIAL_REQUEST+2;
  private static final int LOCATION_REQUEST=INITIAL_REQUEST+3;
  private TextView location;
  private TextView camera;
  private TextView internet;
  private TextView contacts;
  private TextView storage;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    location=(TextView)findViewById(R.id.location_value);
    camera=(TextView)findViewById(R.id.camera_value);
    internet=(TextView)findViewById(R.id.internet_value);
    contacts=(TextView)findViewById(R.id.contacts_value);
    storage=(TextView)findViewById(R.id.storage_value);

    if (!canAccessLocation() || !canAccessContacts()) {
      requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
    }
  }

  @Override
  protected void onResume() {
    super.onResume();

    updateTable();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actions, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
      case R.id.camera:
        if (canAccessCamera()) {
          doCameraThing();
        }
        else {
          requestPermissions(CAMERA_PERMS, CAMERA_REQUEST);
        }
        return(true);

      case R.id.contacts:
        if (canAccessContacts()) {
          doContactsThing();
        }
        else {
          requestPermissions(CONTACTS_PERMS, CONTACTS_REQUEST);
        }
        return(true);

      case R.id.location:
        if (canAccessLocation()) {
          doLocationThing();
        }
        else {
          requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
        }
        return(true);
    }

    return(super.onOptionsItemSelected(item));
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    updateTable();

    switch(requestCode) {
      case CAMERA_REQUEST:
        if (canAccessCamera()) {
          doCameraThing();
        }
        else {
          bzzzt();
        }
        break;

      case CONTACTS_REQUEST:
        if (canAccessContacts()) {
          doContactsThing();
        }
        else {
          bzzzt();
        }
        break;

      case LOCATION_REQUEST:
        if (canAccessLocation()) {
          doLocationThing();
        }
        else {
          bzzzt();
        }
        break;
    }
  }

  private void updateTable() {
    location.setText(String.valueOf(canAccessLocation()));
    camera.setText(String.valueOf(canAccessCamera()));
    internet.setText(String.valueOf(hasPermission(Manifest.permission.INTERNET)));
    contacts.setText(String.valueOf(canAccessContacts()));
    storage.setText(String.valueOf(hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)));
  }

  private boolean canAccessLocation() {
    return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
  }

  private boolean canAccessCamera() {
    return(hasPermission(Manifest.permission.CAMERA));
  }

  private boolean canAccessContacts() {
    return(hasPermission(Manifest.permission.READ_CONTACTS));
  }

  private boolean hasPermission(String perm) {
    return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
  }

  private void bzzzt() {
    Toast.makeText(this, R.string.toast_bzzzt, Toast.LENGTH_LONG).show();
  }

  private void doCameraThing() {
    Toast.makeText(this, R.string.toast_camera, Toast.LENGTH_SHORT).show();
  }

  private void doContactsThing() {
    Toast.makeText(this, R.string.toast_contacts, Toast.LENGTH_SHORT).show();
  }

  private void doLocationThing() {
    Toast.makeText(this, R.string.toast_location, Toast.LENGTH_SHORT).show();
  }
}

(from this sample project)

For the requestPermissions() function, should the parameters just be "ACCESS_COARSE_LOCATION"? Or should I include the full name "android.permission.ACCESS_COARSE_LOCATION"?

I would use the constants defined on Manifest.permission, as shown above.

Also, what is the request code?

That will be passed back to you as the first parameter to onRequestPermissionsResult(), so you can tell one requestPermissions() call from another.

how to set default method argument values?

Hopefully I am not misunderstanding this document, but if your using Java 1.8, in theory, you could accomplish something like this by defining a working implementation of a default method ("defender methods") within an interface that you implement.

interface DoInterface {
    void doNothing();
    public default void remove() {
       throw new UnsupportedOperationException("remove");
    }
    public default int doSomething( int arg1, int arg2) {
        val = arg1 + arg2 * arg1;
        log( "Value is: " + val );
        return val;
    }
}
class DoIt extends DoInterface {
    DoIt() {
        log("Called DoIt constructor.");
    }
    public int doSomething() {
        int val = doSomething( 0, 100 );
        return val;
    }
}

Then, call it either way:

DoIt d = new DoIt();
d.doSomething();
d.soSomething( 5, 45 );

How to execute python file in linux

You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.

It should look like that :

#!/usr/bin/env python

or the real path

#!/usr/bin/python

You should also check the file have the right to be execute. chmod +x file.py

As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

Disable text input history

<input type="text" autocomplete="off" />

In Python script, how do I set PYTHONPATH?

I linux this works too:

import sys
sys.path.extend(["/path/to/dotpy/file/"])

How to include an HTML page into another HTML page without frame/iframe?

If you're willing to use jquery, there is a handy jquery plugin called "inc".

I use it often for website prototyping, where I just want to present the client with static HTML with no backend layer that can be quickly created/edited/improved/re-presented

http://johannburkard.de/blog/programming/javascript/inc-a-super-tiny-client-side-include-javascript-jquery-plugin.html

For example, things like the menu and footer need to be shown on every page, but you dont want to end up with a copy-and-paste-athon

You can include a page fragment as follows

<p class="inc:footer.htm"></p>

how to set length of an column in hibernate with maximum length

if your column is varchar use annotation length

@Column(length = 255)

or use another column type

@Column(columnDefinition="TEXT")

React Native add bold or italics to single words in <Text> field

It is not in a text field as asked but wrapping separate text elements into a view would give the desired output. This can be used if you don't want to add another library into your project just for styling a few texts.

<View style={{flexDirection: 'row'}}>
 <Text style={{fontWeight: '700', marginRight: 5}}>Contact Type:</Text>
 <Text>{data.type}</Text>
</View>

Would result as follows

enter image description here

MIT vs GPL license

It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.

True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.

The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.

is the GPL is more restrictive than the MIT license?

Yes, very much so.

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

Does C# have extension properties?

For the moment it is still not supported out of the box by Roslyn compiler ...

Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. C# 7 and C# 8.0 have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.

But it will ...

There is an extension members item in the C# 7 work list so it may be supported in the near future. The current status of extension property can be found on Github under the related item.

However, there is an even more promising topic which is the "extend everything" with a focus on especially properties and static classes or even fields.

Moreover you can use a workaround

As specified in this article, you can use the TypeDescriptor capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like
string Data(this MyClass instance) as an alias for extension method
string GetData(this MyClass instance) as it stores data into the class.

I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell.

And feel free to contribute as the software of tomorrow will come from the community.

Update: August 2016

As dotnet team published what's new in C# 7.0 and from a comment of Mads Torgensen:

Extension properties: we had a (brilliant!) intern implement them over the summer as an experiment, along with other kinds of extension members. We remain interested in this, but it’s a big change and we need to feel confident that it’s worth it.

It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.

Update: May 2017

The extension members has been closed as duplicate of extension everything issue which is closed too. The main discussion was in fact about Type extensibility in a broad sense. The feature is now tracked here as a proposal and has been removed from 7.0 milestone.

Update: August, 2017 - C# 8.0 proposed feature

While it still remains only a proposed feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:

public interface IEmployee 
{
    public decimal Salary { get; set; }
}

public class Employee
{
    public decimal Salary { get; set; }
}

public extension MyPersonExtension extends Person : IEmployee
{
    private static readonly ConditionalWeakTable<Person, Employee> _employees = 
        new ConditionalWeakTable<Person, Employee>();


    public decimal Salary
    {
        get 
        {
            // `this` is the instance of Person
            return _employees.GetOrCreate(this).Salary; 
        }
        set 
        {
            Employee employee = null;
            if (!_employees.TryGetValue(this, out employee)
            {
                employee = _employees.GetOrCreate(this);
            }
            employee.Salary = value;
        }
    }
}

IEmployee person = new Person();
var salary = person.Salary;

Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in Mads Torgensen podcast, the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...). For this, you can still use the TypeDescriptor/ConditionalWeakTable technique described earlier and with the property extension, hides it under a nice property.

Syntax is still subject to change as implies this issue. For example, extends could be replaced by for which some may feel more natural and less java related.

Update December 2018 - Roles, Extensions and static interface members

Extension everything didn't make it to C# 8.0, because of some of drawbacks explained as the end of this GitHub ticket. So, there was an exploration to improve the design. Here, Mads Torgensen explains what are roles and extensions and how they differs:

Roles allow interfaces to be implemented on specific values of a given type. Extensions allow interfaces to be implemented on all values of a given type, within a specific region of code.

It can be seen at a split of previous proposal in two use cases. The new syntax for extension would be like this:

public extension ULongEnumerable of ulong
{
    public IEnumerator<byte> GetEnumerator()
    {
        for (int i = sizeof(ulong); i > 0; i--)
        {
            yield return unchecked((byte)(this >> (i-1)*8));
        }
    }
}

then you would be able to do this:

foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
    WriteLine($"{e.Current:X}");
}

And for a static interface:

public interface IMonoid<T> where T : IMonoid<T>
{
    static T operator +(T t1, T t2);
    static T Zero { get; }
}

Add an extension property on int and treat the int as IMonoid<int>:

public extension IntMonoid of int : IMonoid<int>
{
    public static int Zero => 0;
}

Disabling submit button until all fields have values

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

javascript onclick increment number

Simple HTML + Thymeleaf version. Code with Controller

<form action="/" method="post">
                <input type="hidden" th:value="${post.getId_post()}" name="id_post">
                <input type="hidden" th:value="-1" name="valueForChange">
                <input type="submit" value="-">
</form>

This is how it looks - look of buttons you can change with style. https://i.stack.imgur.com/b97N1.png

Code snippet or shortcut to create a constructor in Visual Studio

For the full list of snippets (little bits of prefabricated code) press Ctrl+K and then Ctrl+X. Source from MSDN. Works in Visual Studio 2013 with a C# project.

So how to make a constructor

  1. Press Ctrl+K and then Ctrl+X
  2. Select Visual C#
  3. Select ctor
  4. Press Tab

Update: You can also right-click in your code where you want the snippet, and select Insert Snippet from the right-click menu

Adding value labels on a matplotlib bar chart

If you want to just label the data points above the bar, you could use plt.annotate()

My code:

import numpy as np
import matplotlib.pyplot as plt

n = [1,2,3,4,5,]
s = [i**2 for i in n]
line = plt.bar(n,s)
plt.xlabel('Number')
plt.ylabel("Square")

for i in range(len(s)):
    plt.annotate(str(s[i]), xy=(n[i],s[i]), ha='center', va='bottom')

plt.show()

By specifying a horizontal and vertical alignment of 'center' and 'bottom' respectively one can get centered annotations.

a labelled bar chart

Group by month and year in MySQL

This is how I do it:

GROUP BY  EXTRACT(YEAR_MONTH FROM t.summaryDateTime);

How to delete SQLite database from Android programmatically

context.deleteDatabase(DATABASE_NAME); will delete the database only if all the connections are closed. If you are maintaining singleton instance for handling your database helper - it is easy to close the opened Connection.

Incase the databasehelper is used in multiple place by instantiating directly, the deleteDatabase + killProcess will do the job even if some connections are open. This can be used if the application scenario doesn't have any issues in restarting the app.

Bulk package updates using Conda

You want conda update --all.

conda search --outdated will show outdated packages, and conda update --all will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2).

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

How to crop an image using PIL?

You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800

from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

JavaScript Nested function

function x() {}

is equivalent (or very similar) to

var x = function() {}

unless I'm mistaken.

So there is nothing funny going on.

Delayed function calls

public static class DelayedDelegate
{

    static Timer runDelegates;
    static Dictionary<MethodInvoker, DateTime> delayedDelegates = new Dictionary<MethodInvoker, DateTime>();

    static DelayedDelegate()
    {

        runDelegates = new Timer();
        runDelegates.Interval = 250;
        runDelegates.Tick += RunDelegates;
        runDelegates.Enabled = true;

    }

    public static void Add(MethodInvoker method, int delay)
    {

        delayedDelegates.Add(method, DateTime.Now + TimeSpan.FromSeconds(delay));

    }

    static void RunDelegates(object sender, EventArgs e)
    {

        List<MethodInvoker> removeDelegates = new List<MethodInvoker>();

        foreach (MethodInvoker method in delayedDelegates.Keys)
        {

            if (DateTime.Now >= delayedDelegates[method])
            {
                method();
                removeDelegates.Add(method);
            }

        }

        foreach (MethodInvoker method in removeDelegates)
        {

            delayedDelegates.Remove(method);

        }


    }

}

Usage:

DelayedDelegate.Add(MyMethod,5);

void MyMethod()
{
     MessageBox.Show("5 Seconds Later!");
}

What's "this" in JavaScript onclick?

In the case you are asking about, this represents the HTML DOM element.

So it would be the <a> element that was clicked on.

Print to the same line and not a new line?

import time
import sys


def update_pct(w_str):
    w_str = str(w_str)
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(" " * len(w_str))
    sys.stdout.write("\b" * len(w_str))
    sys.stdout.write(w_str)
    sys.stdout.flush()

for pct in range(0, 101):
    update_pct("{n}%".format(n=str(pct)))
    time.sleep(0.1)

\b will move the location of the cursor back one space
So we move it back all the way to the beginning of the line
We then write spaces to clear the current line - as we write spaces the cursor moves forward/right by one
So then we have to move the cursor back at the beginning of the line before we write our new data

Tested on Windows cmd using Python 2.7

Check if a specific value exists at a specific key in any subarray of a multidimensional array

You can use this with only two parameter

function whatever($array, $val) {
    foreach ($array as $item)
        if (isset($item) && in_array($val,$item))
            return 1;
    return 0;
}

jQuery/JavaScript: accessing contents of an iframe

Have you tried the classic, waiting for the load to complete using jQuery's builtin ready function?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

What is the difference between 'protected' and 'protected internal'?

In practice, about methods:

protected - accessible for inherited classes, otherwise private.

internal - public only for classes inside the assembly, otherwise private.

protected internal - means protected or internal - methods become accessible for inherited classes and for any classes inside the assembly.

"break;" out of "if" statement?

As already mentioned that, break-statement works only with switches and loops. Here is another way to achieve what is being asked. I am reproducing https://stackoverflow.com/a/257421/1188057 as nobody else mentioned it. It's just a trick involving the do-while loop.

do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);

Though I would prefer the use of goto-statement.

Maven error :Perhaps you are running on a JRE rather than a JDK?

I had the same error and I was missing the User variable: JAVA_HOME and the value for the SDK - "C:\Program Files\Java\jdk-9.0.1" in my case

SQL Server using wildcard within IN

  1. I firstly added one off static table with ALL possibilities of my wildcard results (this company has a 4 character nvarchar code as their localities and they wildcard their locals) i.e. they may have 456? which would give them 456[1] to 456[Z] i.e 0-9 & a-z

  2. I had to write a script to pull the current user (declare them) and pull the masks for the declared user.

  3. Create some temporary tables just basic ones to rank the row numbers for this current user

  4. loop through each result (YOUR Or this Or that etc...)

  5. Insert into the test Table.

Here is the script I used:

Drop Table #UserMasks 
Drop Table #TESTUserMasks 

Create Table #TESTUserMasks (
    [User] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

Create Table #UserMasks (
    [RN] [Int] NOT NULL,
    [Mask] [Nvarchar](10) NOT NULL)

DECLARE @User INT
SET @User = 74054

Insert Into #UserMasks 
select ROW_NUMBER() OVER ( PARTITION BY ProntoUserID ORDER BY Id DESC) AS RN,
       REPLACE(mask,'?','') Mask
from dbo.Access_Masks 
where prontouserid = @User

DECLARE @TopFlag INT
SET @TopFlag = 1

WHILE (@TopFlag <=(select COUNT(*) from #UserMasks))
BEGIN
    Insert Into #TestUserMasks 
    select (@User),Code from dbo.MaskArrayLookupTable 
    where code like (select Mask + '%' from #UserMasks Where RN = @TopFlag)

    SET @TopFlag = @TopFlag + 1
END
GO

select * from #TESTUserMasks

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

if you are getting id from url try

$id = (isset($_GET['id']) ? $_GET['id'] : '');

if getting from form you need to use POST method cause your form has method="post"

 $id = (isset($_POST['id']) ? $_POST['id'] : '');

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

Plotting a 3d cube, a sphere and a vector in Matplotlib

It is a little complicated, but you can draw all the objects by the following code:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations


fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
    if np.sum(np.abs(s-e)) == r[1]-r[0]:
        ax.plot3D(*zip(s, e), color="b")

# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")

# draw a point
ax.scatter([0], [0], [0], color="g", s=100)

# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d


class Arrow3D(FancyArrowPatch):

    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        FancyArrowPatch.draw(self, renderer)

a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
            lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()

output_figure

Clear android application user data

// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);

if(sdDir.exists())
    deleteRecursive(sdDir);




// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
    for (File child : fileOrDirectory.listFiles())
        deleteRecursive(child);

    fileOrDirectory.delete();
}

How to get week numbers from dates?

Using only base, I wrote the following function.

Note:

  1. Assumes Mon is day number 1 in the week
  2. First week is week 1
  3. Returns 0 if week is 52 from last year

Fine-tune to suit your needs.

findWeekNo <- function(myDate){
  # Find out the start day of week 1; that is the date of first Mon in the year
  weekday <- switch(weekdays(as.Date(paste(format(as.Date(myDate),"%Y"),"01-01", sep = "-"))),
                    "Monday"={1},
                    "Tuesday"={2},
                    "Wednesday"={3},
                    "Thursday"={4},
                    "Friday"={5},
                    "Saturday"={6},
                    "Sunday"={7}
  )

  firstMon <- ifelse(weekday==1,1, 9 - weekday )

  weekNo <- floor((as.POSIXlt(myDate)$yday - (firstMon-1))/7)+1
  return(weekNo)
}


findWeekNo("2017-01-15") # 2

Copying an array of objects into another array in javascript

A great way for cloning an array is with an array literal and the spread syntax. This is made possible by ES2015.

const objArray = [{name:'first'}, {name:'second'}, {name:'third'}, {name:'fourth'}];

const clonedArr = [...objArray];

console.log(clonedArr) // [Object, Object, Object, Object]

You can find this copy option in MDN's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Copy_an_array

It is also an Airbnb's best practice. https://github.com/airbnb/javascript#es6-array-spreads

Note: The spread syntax in ES2015 goes one level deep while copying an array. Therefore, they are unsuitable for copying multidimensional arrays.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

First, go to that folder which is containing pycharm.sh and open terminal from there. Then type

./pycharm.sh

this will open pycharm.

bin folder contains pycharm.sh file.

Remove leading and trailing spaces?

Starting file:

     line 1
   line 2
line 3  
      line 4 

Code:

with open("filename.txt", "r") as f:
    lines = f.readlines()
    for line in lines:
        stripped = line.strip()
        print(stripped)

Output:

line 1
line 2
line 3
line 4

How to retrieve data from a SQL Server database in C#?

we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields

class Db
{
    private readonly static string ConnectionString =
            ConfigurationManager.ConnectionStrings
                        ["DbConnectionString"].ConnectionString;
    public static List<string> GetValuesFromDB(string LocationCode)
    {
        List<string> ValuesFromDB = new List<string>();
        string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
            $"from [CustomerLocations] where LocationCode='{LocationCode}';";
        using (SqlConnection Locationconnection =
                                 new SqlConnection(ConnectionString))
        {
            SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
            try
            {
                Locationconnection.Open();
                SqlDataReader Locationreader = command.ExecuteReader();
                while (Locationreader.Read())
                {
                    for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
                    {
                        ValuesFromDB.Add(Locationreader[i].ToString());
                    }
                }
                Locationreader.Close();
                return ValuesFromDB;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

    }

}

hope this might helpful

Note: you guys need connection string (in our case "DbConnectionString")

current/duration time of html5 video?

https://www.w3schools.com/tags/av_event_timeupdate.asp

// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");

// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};

function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
    document.getElementById("demo").innerHTML = vid.currentTime;
}

Error: [ng:areq] from angular controller

Check the name of your angular module...what is the name of your module in your app.js?

In your TransportersController, you have:

angular.module('mean.transporters')

and in your TransportersService you have:

angular.module('transporterService', [])

You probably want to reference the same module in each:

angular.module('myApp')

Trying to Validate URL Using JavaScript

In a similar situation I got away with this:

someUtils.validateURL = function(url) {
    var parser = document.createElement('a');
    try {
        parser.href = url;
        return !!parser.hostname;
    } catch (e) {
        return false;
    }
};

i.e. why invent the wheel if browsers can do it for you? But, of course, this will only work in the browser.

there are various parts of parsed URL exactly how browser would interpret it:

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "8080"
parser.pathname; // => "/path/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

Using these you can improve your validating function depending on the requirements. The only drawback is that it will accept relative URLs and use current page server's host and port. But you can use it for your advantage, by re-assembling the URL from parts and always passing it in full to your AJAX service.

What validateURL won't accept is invalid URL, e.g. http:\:8883 will return false, but :1234 is valid and is interpreted as http://pagehost.example.com/:1234 i.e. as a relative path.

UPDATE

This approach is no longer working with Chrome and other WebKit browsers. Even when URL is invalid, hostname is filled with some value, e.g. taken from base. It still helps to parse parts of URL, but will not allow to validate one.

Possible better no-own-parser approach is to use var parsedURL = new URL(url) and catch exceptions. See e.g. URL API. Supported by all major browsers and NodeJS, although still marked experimental.

Fatal error: Call to undefined function mb_strlen()

On Centos, RedHat, Fedora and other yum-my systems it is much simpler than the PHP manual suggests:

yum install php-mbstring
service httpd restart

how to check if List<T> element contains an item with a Particular Property Value

You don't actually need LINQ for this because List<T> provides a method that does exactly what you want: Find.

Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

Example code:

PricePublicModel result = pricePublicList.Find(x => x.Size == 200);

Dynamic instantiation from string name of a class in dynamically imported module?

Use getattr to get an attribute from a name in a string. In other words, get the instance as

instance = getattr(modul, class_name)()

How to insert a timestamp in Oracle?

Inserting date in sql

insert
into tablename (timestamp_value)
values ('dd-mm-yyyy hh-mm-ss AM');

If suppose we wanted to insert system date

insert
into tablename (timestamp_value)
values (sysdate);

Difference between logical addresses, and physical addresses?

  1. An address generated by the CPU is commonly referred to as a logical address. The set of all logical addresses generated by a program is known as logical address space. Whereas, an address seen by the memory unit- that is, the one loaded into the memory-address register of the memory- is commonly referred to as physical address. The set of all physical addresses corresponding to the logical addresses is known as physical address space.
  2. The compile-time and load-time address-binding methods generate identical logical and physical addresses. However, in the execution-time address-binding scheme, the logical and physical-address spaces differ.
  3. The user program never sees the physical addresses. The program creates a pointer to a logical address, say 346, stores it in memory, manipulate it, compares it to other logical addresses- all as the number 346. Only when a logical address is used as memory address, it is relocated relative to the base/relocation register. The memory-mapping hardware device called the memory- management unit(MMU) converts logical addresses into physical addresses.
  4. Logical addresses range from 0 to max. User program that generates logical address thinks that the process runs in locations 0 to max. Logical addresses must be mapped to physical addresses before they are used. Physical addresses range from (R+0) to (R + max) for a base/relocation register value R.
  5. Example: enter image description here Mapping from logical to physical addresses using memory management unit (MMU) and relocation/base register The value in relocation/base register is added to every logical address generated by a user process, at the time it is sent to memory, to generate corresponding physical address. In the above figure, base/ relocation value is 14000, then an attempt by the user to access the location 346 is mapped to 14346.

Android emulator doesn't take keyboard input - SDK tools rev 20

Look in AVD Manager, select the AVD and click in Edit. In Hardware section: click in "New" and search for "Keyboard support" and add with OK button and set the value to "yes" and save changes with "Edit AVD"

How can foreign key constraints be temporarily disabled using T-SQL?

http://www.sqljunkies.com/WebLog/roman/archive/2005/01/30/7037.aspx

-- Disable all table constraints

ALTER TABLE MyTable NOCHECK CONSTRAINT ALL

-- Enable all table constraints

ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT ALL

-- Disable single constraint

ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint

-- Enable single constraint

ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint

Open text file and program shortcut in a Windows batch file

The command start [filename] opened the file in my default text editor.

This command also worked for opening a non-.txt file.

Gaussian filter in MATLAB

You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).

You specify sigma and hsize in fspecial.

Code:

%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)

Activity has leaked window that was originally added

Ensure to call this.dialog.show . (Activity)

Chaining multiple filter() in Django, is this a bug?

As you can see in the generated SQL statements the difference is not the "OR" as some may suspect. It is how the WHERE and JOIN is placed.

Example1 (same joined table) :

(example from https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships)

Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)

This will give you all the Blogs that have one entry with both (entry_headline_contains='Lennon') AND (entry__pub_date__year=2008), which is what you would expect from this query. Result: Book with {entry.headline: 'Life of Lennon', entry.pub_date: '2008'}

Example 2 (chained)

Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

This will cover all the results from Example 1, but it will generate slightly more result. Because it first filters all the blogs with (entry_headline_contains='Lennon') and then from the result filters (entry__pub_date__year=2008).

The difference is that it will also give you results like: Book with {entry.headline: 'Lennon', entry.pub_date: 2000}, {entry.headline: 'Bill', entry.pub_date: 2008}

In your case

I think it is this one you need:

Book.objects.filter(inventory__user__profile__vacation=False, inventory__user__profile__country='BR')

And if you want to use OR please read: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Using jquery to delete all elements with a given id

if you want to remove all elements with matching ID parts, for example:

<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>

try this:

$("span[id*=myID]").remove();

don't forget the '*' - this will remove them all at once - cheers

Working Demo

Switch/toggle div (jQuery)

I think this works:

$(document).ready(function(){

    // Hide (collapse) the toggle containers on load
    $(".toggle_container").hide();

    // Switch the "Open" and "Close" state per click then 
    // slide up/down (depending on open/close state)
    $("h2.trigger").click(function(){
        $(this).toggleClass("active").next().slideToggle("slow");
        return false; // Prevent the browser jump to the link anchor
    });
});

Fastest way of finding differences between two files in unix?

You could also try to include md5-hash-sums or similar do determine whether there are any differences at all. Then, only compare files which have different hashes...

iOS change navigation bar title font and color

Swift:-

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name:"Love Nature", size: 40)!]

Bootstrap 4 - Inline List?

Shouldn't it be just the .list-group? See below,

<ul class="list-group">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>

Reference: Bootstrap 4 Basic Example of a List group

Highlight Bash/shell code in Markdown files

Per the documentation from GitHub regarding GFM syntax highlighted code blocks

We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.

Rendered on GitHub, console makes the lines after the console blue. bash, sh, or shell don't seem to "highlight" much ...and you can use posh for PowerShell or CMD.

Default values and initialization in Java

Yes, an instance variable will be initialized to a default value. For a local variable, you need to initialize before use:

public class Main {

    int instaceVariable; // An instance variable will be initialized to the default value

    public static void main(String[] args) {
        int localVariable = 0; // A local variable needs to be initialized before use
    }
}

How do I run a Python program?

Python itself comes with an editor that you can access from the IDLE File > New File menu option.

Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.

Note: it's just been the easiest and most straightforward way for me so far.

What's the purpose of META-INF?

If you're using JPA1, you might have to drop a persistence.xml file in there which specifies the name of a persistence-unit you might want to use. A persistence-unit provides a convenient way of specifying a set of metadata files, and classes, and jars that contain all classes to be persisted in a grouping.

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

// ...

EntityManagerFactory emf =
      Persistence.createEntityManagerFactory(persistenceUnitName);

See more here: http://www.datanucleus.org/products/datanucleus/jpa/emf.html

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

TypeScript - Append HTML to container element in Angular 2

When working with Angular the recent update to Angular 8 introduced that a static property inside @ViewChild() is required as stated here and here. Then your code would require this small change:

@ViewChild('one') d1:ElementRef;

into

// query results available in ngOnInit
@ViewChild('one', {static: true}) foo: ElementRef;

OR

// query results available in ngAfterViewInit
@ViewChild('one', {static: false}) foo: ElementRef;

Merging Cells in Excel using C#

Code Snippet

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Excel.Application excelApp = null;
    private void button1_Click(object sender, EventArgs e)
    {
        excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
    }
}

Thanks

ListAGG in SQLSERVER

MySQL

SELECT FieldA
     , GROUP_CONCAT(FieldB ORDER BY FieldB SEPARATOR ',') AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

Oracle & DB2

SELECT FieldA
     , LISTAGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

PostgreSQL

SELECT FieldA
     , STRING_AGG(FieldB, ',' ORDER BY FieldB) AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

SQL Server

SQL Server ≥ 2017 & Azure SQL

SELECT FieldA
     , STRING_AGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

SQL Server ≤ 2016 (CTE included to encourage the DRY principle)

  WITH CTE_TableName AS (
       SELECT FieldA, FieldB
         FROM TableName)
SELECT t0.FieldA
     , STUFF((
       SELECT ',' + t1.FieldB
         FROM CTE_TableName t1
        WHERE t1.FieldA = t0.FieldA
        ORDER BY t1.FieldB
          FOR XML PATH('')), 1, LEN(','), '') AS FieldBs
  FROM CTE_TableName t0
 GROUP BY t0.FieldA
 ORDER BY FieldA;

SQLite

Ordering requires a CTE or subquery

  WITH CTE_TableName AS (
       SELECT FieldA, FieldB
         FROM TableName
        ORDER BY FieldA, FieldB)
SELECT FieldA
     , GROUP_CONCAT(FieldB, ',') AS FieldBs
  FROM CTE_TableName
 GROUP BY FieldA
 ORDER BY FieldA;

Without ordering

SELECT FieldA
     , GROUP_CONCAT(FieldB, ',') AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

How do I get my C# program to sleep for 50 msec?

For readability:

using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Here is My Code

protected void btnExcel_Click(object sender, ImageClickEventArgs e)
    {
        if (gvDetail.Rows.Count > 0)
        {
            System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
            gvDetail.RenderControl(htmlWrite1);

            gvDetail.AllowPaging = false;
            Search();
            sh.ExportToExcel(gvDetail, "Report");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

Generating Random Number In Each Row In Oracle Query

If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:

SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL

View JSON file in Browser

If you don't want to install extensions, you can simply prepend the URL with view-source:, e.g. view-source:http://content.dimestore.com/prod/survey_data/4535/4535.json. This usually works in Firefox and Chrome (will still offer to download the file however if Content-Disposition: attachment header is present).

How to find my realm file?

As previously was mentioned you can use next approaches to find file location

//code
Realm.Configuration.defaultConfiguration.fileURL 

//lldb
(lldb) po Realm.Configuration.defaultConfiguration.fileURL

or you can manually find it:

//Simulator
/Users/<username>/Library/Developer/CoreSimulator/Devices/<simulator-uuid>/data/Containers/Data/Application/<application-uuid>/Documents/

//for example
/Users/alex/Library/Developer/CoreSimulator/Devices/E1D084B0-CD97-41B4-871F-E131CA33F635/data/Containers/Data/Application/373721C7-2381-4E3D-9ABC-2147F748322F/Documents/

//iPhone (download a copy)
Xcode -> Window -> Devices and Simulators -> Devices -> <select device and app> -> App container actions -> Download Container... -> <selectfolder and navigate to it (.xcappdata)> -> Right Click -> Show Package Consents -> AppData -> Documents

*Please note that if you set file name for realm and it has some other extension than .realm RealmStudio does not open it by default

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

After I updated my MySql, I was getting the same error message. It turned out that after installing a different version on MySql, inside the my.ini, the port was different. Previous MySql version had port 3306 but the new one have port 3308. Check your MySql my.ini, if it is different use the port from .ini in your connection.

How do I reload a page without a POSTDATA warning in Javascript?

Here's a solution that should always work and doesn't remove the hash.

let currentPage = new URL(window.location.href);
currentPage.searchParams.set('r', (+new Date * Math.random()).toString(36).substring(0, 5));
window.location.href = currentPage.href;

Android Studio cannot resolve R in imported project?

Had this error when importing project from Eclipse. The reason was some of the xml files had errors. Check ALL your XML files for errors. Including androidmanifest.xml, and values, themes, styles, layouts folders, etc. Warnings in xml are ok, but errors will generate this error.

Afterwards, do a Clean Project and rebuild.

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

when you do UNIQUE as a table level constraint as you have done then what your defining is a bit like a composite primary key see ddl constraints, here is an extract

"This specifies that the *combination* of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique."

this means that either field could possibly have a non unique value provided the combination is unique and this does not match your foreign key constraint.

most likely you want the constraint to be at column level. so rather then define them as table level constraints, 'append' UNIQUE to the end of the column definition like name VARCHAR(60) NOT NULL UNIQUE or specify indivdual table level constraints for each field.

How to implement a Navbar Dropdown Hover in Bootstrap v4?

(June 2020) I found this solution and I thought I should post it here:

Bootstrap version: 4.3.1

The CSS part:

.navbar .nav-item:not(:last-child) {
  margin-right: 35px;
}

.dropdown-toggle::after {
   transition: transform 0.15s linear;
}

.show.dropdown .dropdown-toggle::after {
  transform: translateY(3px);
}

.dropdown-menu {
  margin-top: 0;
}

The jQuery part:

const $dropdown = $(".dropdown");
const $dropdownToggle = $(".dropdown-toggle");
const $dropdownMenu = $(".dropdown-menu");
const showClass = "show";

$(window).on("load resize", function() {
  if (this.matchMedia("(min-width: 768px)").matches) {
    $dropdown.hover(
      function() {
        const $this = $(this);
        $this.addClass(showClass);
        $this.find($dropdownToggle).attr("aria-expanded", "true");
        $this.children($dropdownMenu).addClass(showClass);
      },
      function() {
        const $this = $(this);
        $this.removeClass(showClass);
        $this.find($dropdownToggle).attr("aria-expanded", "false");
        $this.children($dropdownMenu).removeClass(showClass);
      }
    );
  } else {
    $dropdown.off("mouseenter mouseleave");
  }
});

Source: https://webdesign.tutsplus.com/tutorials/how-to-make-the-bootstrap-navbar-dropdown-work-on-hover--cms-33840

Time comparison

example:

import java.util.*;   
import java.lang.Object;   
import java.text.Collator;   
public class CurrentTime{   
  public class CurrentTime   
{   
    public static void main( String[] args )   
    {   
        Calendar calendar = new GregorianCalendar();   
        String am_pm;   
        int hour = calendar.get( Calendar.HOUR );   
        int minute = calendar.get( Calendar.MINUTE );   
        // int second = calendar.get(Calendar.SECOND);   
        if( calendar.get( Calendar.AM_PM ) == 0 ){   
            am_pm = "AM";   
            if(hour >=10)   
                System.out.println( "welcome" );   
        }               
        else{   
            am_pm = "PM";   
            if(hour<6)   
                System.out.println( "welcome" );   
        }   

        String time = "Current Time : " + hour + ":" + minute + " " + am_pm;   
        System.out.println( time );    
    }   
}  

Source

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

What is a "static" function in C?

Minor nit: static functions are visible to a translation unit, which for most practical cases is the file the function is defined in. The error you are getting is commonly referred to as violation of the One Definition Rule.

The standard probably says something like:

"Every program shall contain exactly one definition of every noninline function or object that is used in that program; no diagnostic required."

That is the C way of looking at static functions. This is deprecated in C++ however.

In C++, additionally, you can declare member functions static. These are mostly metafunctions i.e. they do not describe/modify a particular object's behavior/state but act on the whole class itself. Also, this means that you do not need to create an object to call a static member function. Further, this also means, you only get access to static member variables from within such a function.

I'd add to Parrot's example the Singleton pattern which is based on this sort of a static member function to get/use a single object throughout the lifetime of a program.

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

Launch programs whose path contains spaces

set shell=CreateObject("Shell.Application")
' shell.ShellExecute "application", "arguments", "path", "verb", window
shell.ShellExecute  "slipery.bat",,"C:\Users\anthony\Desktop\dvx", "runas", 1
set shell=nothing 

How do I correct this Illegal String Offset?

if ($inputs['type'] == 'attach') {

The code is valid, but it expects the function parameter $inputs to be an array. The "Illegal string offset" warning when using $inputs['type'] means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type' is not suitable.)

So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.

However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type' to 0, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)

You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs); in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:

if (is_array($inputs) && $inputs['type'] == 'attach') {

Split string with string as delimiter

Try this:

for /F "tokens=1,3 delims=. " %%a in ("%string%") do (
   echo %%a
   echo %%b
)

that is, take the first and third tokens delimited by space or point...

Cycles in family tree software

Here's the problem with family trees: they are not trees. They are directed acyclic graphs or DAGs. If I understand the principles of the biology of human reproduction correctly, there will not be any cycles.

As far as I know, even the Christians accept marriages (and thus children) between cousins, which will turn the family tree into a family DAG.

The moral of the story is: choose the right data structures.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

SQL Server CTE and recursion example

The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.

The semantics of the recursive execution is as follows:

  1. Split the CTE expression into anchor and recursive members.
  2. Run the anchor member(s) creating the first invocation or base result set (T0).
  3. Run the recursive member(s) with Ti as an input and Ti+1 as an output.
  4. Repeat step 3 until an empty set is returned.
  5. Return the result set. This is a UNION ALL of T0 to Tn.

JavaScript check if value is only undefined, null or false

I think what you're looking for is !!val==false which can be turned to !val (even shorter):

You see:

function checkValue(value) {
    console.log(!!value);
}

checkValue(); // false
checkValue(null); // false
checkValue(undefined); // false
checkValue(false); // false
checkValue(""); // false

checkValue(true); // true
checkValue({}); // true
checkValue("any string"); // true

That works by flipping the value by using the ! operator.

If you flip null once for example like so :

console.log(!null) // that would output --> true

If you flip it twice like so :

console.log(!!null) // that would output --> false

Same with undefined or false.

Your code:

if(val==null || val===false){
  ;
}

would then become:

if(!val) {
  ;
}

That would work for all cases even when there's a string but it's length is zero. Now if you want it to also work for the number 0 (which would become false if it was double flipped) then your if would become:

if(!val && val !== 0) {
  // code runs only when val == null, undefined, false, or empty string ""
}

How do you UDP multicast in Python?

This example doesn't work for me, for an obscure reason.

Not obscure, it's simple routing.

On OpenBSD

route add -inet 224.0.0.0/4 224.0.0.1

You can set the route to a dev on Linux

route add -net 224.0.0.0 netmask 240.0.0.0 dev wlp2s0

force all multicast traffic to one interface on Linux

   ifconfig wlp2s0 allmulti

tcpdump is super simple

tcpdump -n multicast

In your code you have:

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"

Why 10240?

multicast packet size should be 1316 bytes

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Maven: best way of linking custom external JAR to my project?

Don't use systemPath. Contrary to what people have said here, you can put an external jar in a folder under your checked-out project directory and haven Maven find it like other dependencies. Here are two crucial steps:

  1. Use "mvn install:install-file" with -DlocalRepositoryPath.
  2. Configure a repository to point to that path in your POM.

It is fairly straightforward and you can find a step-by-step example here: http://randomizedsort.blogspot.com/2011/10/configuring-maven-to-use-local-library.html

process.start() arguments

To diagnose better, you can capture the standard output and standard error streams of the external program, in order to see what output was generated and why it might not be running as expected.

Look up:

If you set each of those to true, then you can later call process.StandardOutput.ReadToEnd() and process.StandardError.ReadToEnd() to get the output into string variables, which you can easily inspect under the debugger, or output to trace or your log file.

Create view with primary key?

A little late to this party - but this also works well:

CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT 
CAST(CONCAT(CAST([ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO

In my case the join resulted in [ID] - the primary key being repeated up to 5 times (associated different unique data) The nice trick with this is that the original ID can be determined from each UniqueID effectively [ID]+RowNumber() = 11, 12, 13, 14, 21, 22, 23, 24 etc. If you add RowNumber() and [ID] back into the view - you can easily determine your original key from the data. But - this is not something that should be committed to a table because I am fairly sure that the RowNumber() of a view will never be reliably the same as the underlying data alters, even with the OVER(ORDER BY [ID] ASC) to try and help it.

Example output ( Select UniqueId, ID, ROWNR, Name from [REF].[View_Systems] ) :

UniqueId ID ROWNR Name 11 1 1 Amazon A 12 1 2 Amazon B 13 1 3 Amazon C 14 1 4 Amazon D 15 1 5 Amazon E

Table1:

[ID] [Name] 1 Amazon

Table2:

[ID] [Version] 1 A 1 B 1 C 1 D 1 E

CREATE VIEW [REF].[View_Systems]
AS    
SELECT 
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER()  OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]  
FROM  [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

Create a Date with a set timezone without using a string representation

any mileage in

var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

React hooks useState Array

You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect for this.

The following version works:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const StateSelector = () => {
  const initialValue = [
    { id: 0, value: " --- Select a State ---" }];

  const allowedState = [
    { id: 1, value: "Alabama" },
    { id: 2, value: "Georgia" },
    { id: 3, value: "Tennessee" }
  ];

  const [stateOptions, setStateValues] = useState(initialValue);
  // initialValue.push(...allowedState);

  console.log(initialValue.length);
  // ****** BEGINNING OF CHANGE ******
  useEffect(() => {
    // Should not ever set state during rendering, so do this in useEffect instead.
    setStateValues(allowedState);
  }, []);
  // ****** END OF CHANGE ******

  return (<div>
    <label>Select a State:</label>
    <select>
      {stateOptions.map((localState, index) => (
        <option key={localState.id}>{localState.value}</option>
      ))}
    </select>
  </div>);
};

const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);

and here it is in a code sandbox.

I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState directly without using useState at all). If so, that api call to load the list could also go inside the useEffect block.

java.lang.NoClassDefFoundError: Could not initialize class XXX

You are getting a java.lang.NoClassDefFoundError which does NOT mean that your class is missing (in that case you'd get a java.lang.ClassNotFoundException). The ClassLoader ran into an error while reading the class definition when trying to read the class.

Put a try/catch inside your static initializer and look at the exception. If you read some files there and it differs from your local environment it's very likely the cause of the problem (maybe file can't be found, no permissions etc.).

How do you delete all text above a certain line

dgg

will delete everything from your current line to the top of the file.

d is the deletion command, and gg is a movement command that says go to the top of the file, so when used together, it means delete from my current position to the top of the file.

Also

dG

will delete all lines at or below the current one

How does the Python's range function work?

for i in range(5):

is the same as

for i in [0,1,2,3,4]:

Get last record of a table in Postgres

The last inserted record can be queried using this assuming you have the "id" as the primary key:

SELECT timestamp,value,card FROM my_table WHERE id=(select max(id) from my_table)

Assuming every new row inserted will use the highest integer value for the table's id.

Single Result from Database by using mySQLi

If you assume just one result you could do this as in Edwin suggested by using specific users id.

$someUserId = 'abc123';

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);

$stmt->execute();

$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.

OR as "Your Common Sense" which selects just one user.

$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");

$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();

Nothing really different from the above except for PHP v.5

How to implement class constructor in Visual Basic?

A class with a field:

Public Class MyStudent
   Public StudentId As Integer

The constructor:

    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Run git pull over all subdirectories

The mr utility (a.k.a., myrepos) provides an outstanding solution to this very problem. Install it using your favorite package manager, or just grab the mr script directly from github and put it in $HOME/bin or somewhere else on your PATH. Then, cd to the parent plugins folder shared by these repos and create a basic .mrconfig file with contents similar to the following (adjusting the URLs as needed):

# File: .mrconfig
[cms]
checkout = git clone 'https://<username>@github.com/<username>/cms' 'cms'

[admin]
checkout = git clone 'https://<username>@github.com/<username>/admin' 'admin'

[chart]
checkout = git clone 'https://<username>@github.com/<username>/chart' 'chart'

After that, you can run mr up from the top level plugins folder to pull updates from each repository. (Note that this will also do the initial clone if the target working copy doesn't yet exist.) Other commands you can execute include mr st, mr push, mr log, mr diff, etc—run mr help to see what's possible. There's a mr run command that acts as a pass-through, allowing you to access VCS commands not directly suported by mr itself (e.g., mr run git tag STAGING_081220015). And you can even create your own custom commands that execute arbitrary bits of shell script targeting all repos!

mr is an extremely useful tool for dealing with multiple repos. Since the plugins folder is in your home directory, you might also be interested in vcsh. Together with mr, it provides a powerful mechanism for managing all of your configuration files. See this blog post by Thomas Ferris Nicolaisen for an overview.

How can I perform static code analysis in PHP?

PHP PMD (Programming Mistake Detector) and PHP CPD (Copy/Paste Detector) as the former part of PHPUnit.

Unit testing with Spring Security

Just do it the usual way and then insert it using SecurityContextHolder.setContext() in your test class, for example:

Controller:

Authentication a = SecurityContextHolder.getContext().getAuthentication();

Test:

Authentication authentication = Mockito.mock(Authentication.class);
// Mockito.whens() for your authorization object
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);

jquery clone div and append it after specific div

You can do it using clone() function of jQuery, Accepted answer is ok but i am providing alternative to it, you can use append(), but it works only if you can change html slightly as below:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('#clone_btn').click(function(){_x000D_
      $("#car_parent").append($("#car2").clone());_x000D_
    });_x000D_
});
_x000D_
.car-well{_x000D_
  border:1px solid #ccc;_x000D_
  text-align: center;_x000D_
  margin: 5px;_x000D_
  padding:3px;_x000D_
  font-weight:bold;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="car_parent">_x000D_
  <div id="car1" class="car-well">Normal div</div>_x000D_
  <div id="car2" class="car-well" style="background-color:lightpink;color:blue">Clone div</div>_x000D_
  <div id="car3" class="car-well">Normal div</div>_x000D_
  <div id="car4" class="car-well">Normal div</div>_x000D_
  <div id="car5" class="car-well">Normal div</div>_x000D_
</div>_x000D_
<button type="button" id="clone_btn" class="btn btn-primary">Clone</button>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get the path of a running JAR file?

Other answers seem to point to the code source which is Jar file location which is not a directory.

Use

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();

Cannot execute script: Insufficient memory to continue the execution of the program

sqlcmd -S mamxxxxxmu\sqlserverr -U sa -P x1123 -d QLDB -i D:\qldbscript.sql

  • Open command prompt in run as administrator

  • enter above command

"mamxxxxxmu" is computer name "sqlserverr" is server name "sa" is username of server "x1123" is password of server "QLDB" is database name "D:\qldbscript.sql" is sql script file to execute in database

How to manually trigger validation with jQuery validate?

In my similar case, I had my own validation logic and just wanted to use jQuery validation to show the message. This was what I did.

_x000D_
_x000D_
//1) Enable jQuery validation_x000D_
var validator = $('#myForm').validate();_x000D_
_x000D_
$('#myButton').click(function(){_x000D_
  //my own validation logic here_x000D_
  //....._x000D_
  //2) when validation failed, show the error message manually_x000D_
  validator.showErrors({_x000D_
    'myField': 'my custom error message'_x000D_
  });_x000D_
});
_x000D_
_x000D_
_x000D_

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

string comparison in batch file

Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.

Works for me...

C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes

How to initialize an array in angular2 and typescript

Class definitions should be like :

export class Environment {
    cId:string;
    cName:string;

    constructor( id: string, name: string ) { 
        this.cId = id;
        this.cName = name;
    }

    getMyFields(){
        return this.cId + " " + this.cName;
    }
}

 var environments = new Environment('a','b');
 console.log(environments.getMyFields()); // will print a b

Source: https://www.typescriptlang.org/docs/handbook/classes.html

Linq: GroupBy, Sum and Count

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

I think you just want:

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

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

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

Removing nan values from an array

This is my approach to filter ndarray "X" for NaNs and infs,

I create a map of rows without any NaN and any inf as follows:

idx = np.where((np.isnan(X)==False) & (np.isinf(X)==False))

idx is a tuple. It's second column (idx[1]) contains the indices of the array, where no NaN nor inf where found across the row.

Then:

filtered_X = X[idx[1]]

filtered_X contains X without NaN nor inf.

How to change port for jenkins window service when 8080 is being used

Start Jenkins from cmd line with this command :

java -jar jenkins.war --httpPort=8081

How to append something to an array?

Let the array length property do the work:

myarray[myarray.length] = 'new element value added to the end of the array';

myarray.length returns the number of strings in the array. JS is zero based so the next element key of the array will be the current length of the array. EX:

var myarray = [0, 1, 2, 3],
    myarrayLength = myarray.length; //myarrayLength is set to 4

Reload .profile in bash shell script (in unix)?

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

you can start the one when selecting one item from the left tree "virtual device" in AVD manager dialog on the platform of eclipse, the start UI has the option "Wipe User Data"

How to draw an overlay on a SurfaceView used by Camera on Android?

I think you should call the super.draw() method first before you do anything in surfaceView's draw method.

How to unpackage and repackage a WAR file

Adapting from the above answers, this works for Tomcat, but can be adapted for JBoss as well or any container:

sudo -u tomcat /opt/tomcat/bin/shutdown.sh
cd /opt/tomcat/webapps
sudo mkdir tmp; cd tmp
sudo jar -xvf ../myapp.war
#make edits...
sudo vi WEB-INF/classes/templates/fragments/header.html
sudo vi WEB-INF/classes/application.properties
#end of making edits
sudo jar -cvf myapp0.0.1.war *
sudo cp myapp0.0.1.war ..
cd ..
sudo chown tomcat:tomcat myapp0.0.1.war
sudo rm -rf tmp
sudo -u tomcat /opt/tomcat/bin/startup.sh

How to include view/partial specific styling in AngularJS

'use strict'; angular.module('app') .run( [ '$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; } ] ) .config( [ '$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {

            $urlRouterProvider
                .otherwise('/app/dashboard');
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: 'views/layout.html'
                })
                .state('app.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard.html',
                    ncyBreadcrumb: {
                        label: 'Dashboard',
                        description: ''
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                .state('ram', {
                    abstract: true,
                    url: '/ram',
                    templateUrl: 'views/layout-ram.html'
                })
                .state('ram.dashboard', {
                    url: '/dashboard',
                    templateUrl: 'views/dashboard-ram.html',
                    ncyBreadcrumb: {
                        label: 'test'
                    },
                    resolve: {
                        deps: [
                            '$ocLazyLoad',
                            function($ocLazyLoad) {
                                return $ocLazyLoad.load({
                                    serie: true,
                                    files: [
                                        'lib/jquery/charts/sparkline/jquery.sparkline.js',
                                        'lib/jquery/charts/easypiechart/jquery.easypiechart.js',
                                        'lib/jquery/charts/flot/jquery.flot.js',
                                        'lib/jquery/charts/flot/jquery.flot.resize.js',
                                        'lib/jquery/charts/flot/jquery.flot.pie.js',
                                        'lib/jquery/charts/flot/jquery.flot.tooltip.js',
                                        'lib/jquery/charts/flot/jquery.flot.orderBars.js',
                                        'app/controllers/dashboard.js',
                                        'app/directives/realtimechart.js'
                                    ]
                                });
                            }
                        ]
                    }
                })
                 );

Convert Mercurial project to Git

Some notes of my experience converting Mercurial to Git.

1. hg-fast-export

Using hg-fast-export failed and I needed --force as noted above. Next I got this error:

error: cannot lock ref 'refs/heads/stable': 'refs/heads/stable/sub-branch-name' exists; cannot create 'refs/heads/stable'

Upon completion of the hg-fast-export I ended up with an amputated repo. I think that this repo had a good few orphaned branches and that hg-fast-export needs a somewhat idealised repo. This all seemed a bit rough around the edges, so I moved on to Kiln Harmony (http://blog.fogcreek.com/announcing-kiln-harmony-the-future-of-dvcs/)

2. Kiln

Kiln Harmony does not appear to exist on a free tier account as suggested above. I could choose between Git-only and Mercurial-only repos and there is no option to switch. I raised a support ticket and will share the result if they reply.

3. hg-git

The Hg-Git mercurial plugin (http://hg-git.github.io/) did work for me. FYI on Mac OSX I installed hg-git via macports as follows:

  • sudo port install python27
  • sudo port select --set python python27
  • sudo port install py27-hggit
  • vi ~/.hgrc

.hgrc needs these lines:

[ui]
username = Name Surname <[email protected]>

[extensions]
hgext.bookmarks =
hggit = 

I then had success with:

hg push git+ssh://[email protected]:myaccount/myrepo.git

4. Caveat: Know your repo

All the above are blunt instruments and I only pushed ahead because it took enough time to get the team to use git properly.

Upon first pushing the project per (3) I ended up with all new changes missing. This is because this line of code must be viewed as a guide only:

$ hg bookmark -r default master # make a bookmark of master for default, so a ref gets created

The theory is that the default branch can be deemed to be master when pushing to git, and in my case I inherited a repo where they used 'stable' as the equivalent of master. Moreover, I also discovered that the tip of the repo was a hotfix not yet merged with the 'stable' branch.

Without properly understanding both Mercurial and the repo to be converted, you are probably better off not doing the conversion.

I did the following in order to get the repo ready for a second conversion attempt:

hg update -C stable
hg merge stable/hotfix-feature
hg ci -m "Merge with stable branch"
hg push git+ssh://[email protected]:myaccount/myrepo.git

After this I had a verifiably equivalent project in git, however all the orphaned branches I mentioned earlier are gone. I don't think that is too serious, but I may well live to regret this as an oversight. Therefore my final thought is to keep the original anyway.

Edit: If you just want the latest commit in git, this is simpler than the above merge:

hg book -r tip master
hg push git+ssh://[email protected]:myaccount/myrepo.git

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

Is there a Python equivalent to Ruby's string interpolation?

You can also have this

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings

How to use the "required" attribute with a "radio" input field

TL;DR: Set the required attribute for at least one input of the radio group.


Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

_x000D_
_x000D_
<form>_x000D_
  Select Gender:<br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="male" required>_x000D_
    Male_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="female">_x000D_
    Female_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="other">_x000D_
    Other_x000D_
  </label><br>_x000D_
_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also take note of:

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

Source

Limit the size of a file upload (html input element)

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";
    };
};

This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.

Here is the jsfiddle example for more clearence:
https://jsfiddle.net/7bjfr/808/

How to create a simple http proxy in node.js?

Here's a more optimized version of Mike's answer above that gets the websites Content-Type properly, supports POST and GET request, and uses your browsers User-Agent so websites can identify your proxy as a browser. You can just simply set the URL by changing url = and it will automatically set HTTP and HTTPS stuff without manually doing it.

var express = require('express')
var app = express()
var https = require('https');
var http = require('http');
const { response } = require('express');


app.use('/', function(clientRequest, clientResponse) {
    var url;
    url = 'https://www.google.com'
    var parsedHost = url.split('/').splice(2).splice(0, 1).join('/')
    var parsedPort;
    var parsedSSL;
    if (url.startsWith('https://')) {
        parsedPort = 443
        parsedSSL = https
    } else if (url.startsWith('http://')) {
        parsedPort = 80
        parsedSSL = http
    }
    var options = { 
      hostname: parsedHost,
      port: parsedPort,
      path: clientRequest.url,
      method: clientRequest.method,
      headers: {
        'User-Agent': clientRequest.headers['user-agent']
      }
    };  
  
    var serverRequest = parsedSSL.request(options, function(serverResponse) { 
      var body = '';   
      if (String(serverResponse.headers['content-type']).indexOf('text/html') !== -1) {
        serverResponse.on('data', function(chunk) {
          body += chunk;
        }); 
  
        serverResponse.on('end', function() {
          // Make changes to HTML files when they're done being read.
          body = body.replace(`example`, `Cat!` );
  
          clientResponse.writeHead(serverResponse.statusCode, serverResponse.headers);
          clientResponse.end(body);
        }); 
      }   
      else {
        serverResponse.pipe(clientResponse, {
          end: true
        }); 
        clientResponse.contentType(serverResponse.headers['content-type'])
      }   
    }); 
  
    serverRequest.end();
  });    


  app.listen(3000)
  console.log('Running on 0.0.0.0:3000')

enter image description here

enter image description here

How to embed PDF file with responsive width

Seen from a non-PHP guru perspective, this should do exactly what us desired to:

<style>
    [name$='pdf'] { width:100%; height: auto;}
</style>

How to delete last character in a string in C#?

string str="This is test string.";
str=str.Remove(str.Length-1);

How do I remove an item from a stl vector with a certain value?

Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.

Documentation links
std::remove http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase http://www.cppreference.com/cppvector/erase.html

std::vector<int> v;
v.push_back(1);
v.push_back(2);

//Vector should contain the elements 1, 2

//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);

//Erase the "removed" elements.
v.erase(newEnd, v.end());

//Vector should now only contain 2

Thanks to Jim Buck for pointing out my error.

Python MYSQL update statement

Here is the correct way:

import MySQLdb

if __name__ == '__main__':
    connect = MySQLdb.connect(host="localhost", port=3306,
                              user="xxx", passwd="xxx", db='xxx', charset='utf8')

    cursor = connect.cursor()

    cursor.execute("""
       UPDATE tblTableName
       SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
       WHERE Server=%s
    """, (Year, Month, Day, Hour, Minute, ServerID))

    connect.commit()
    connect.close()

P.S. Don't forget connect.commit(), or it won't work

What are the differences between the different saving methods in Hibernate?

Be aware that if you call an update on an detached object, there will always be an update done in the database whether you changed the object or not. If it is not what you want you should use Session.lock() with LockMode.None.

You should call update only if the object was changed outside the scope of your current session (when in detached mode).

How to use && in EL boolean expressions in Facelets?

In addition to the answer of BalusC, use the following Java RegExp to replace && with and:

Search:  (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3

You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.

Shortcut for changing font size

In the Macros explorer under samples/accessibility there is an IncreaseTextEditorFontSize and a DecreaseTextEditorFontSize. Bind those to some keyboard shortcuts.

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

here is another solution I started using after being fed up with the copy and paste issue:

  1. Download MRemote (for pc). this is an alternative to remote desktop manager. You can use remote desktop manager if you like.
  2. Change the VMNet settings to NAT or add another VMNet and set it to NAT.
  3. Configure the vm ip address with an ip in the same network as you host machine. if you want to keep networks separated use a second vmnet and set it's ip address in the same network as the host. that's what I use.
  4. Enable RDP connections on the guest (I only use windows guests)
  5. Create a batch file with this command. add your guest machines:

vmrun start D:\VM\MySuperVM1\vm1.vmx nogui vmrun start D:\VM\MySuperVM2\vm2.vmx nogui

save the file to startmyvms.cmd

create another batch file and add your vms

vmrun stop D:\VM\MySuperVM1\vm1.vmx nogui vmrun stop D:\VM\MySuperVM2\vm2.vmx nogui

save the file to stopmyvms.cmd

  1. Open Mremote go to tools => External tools Add external tool => filename will be the startmyvms.cmd file Add external tool => filename will be the stopmyvms.cmd file So to start working with your vms:

  2. Create you connections to your VMs in mremote

Now to work with your vm 1. You open mremote 2. You go to tools => external tools 3. You click the startmyvms tool when you're done 1. You go to tools => external tools 2. You click the stopmyvms external tool

you could add the vmrun start on the connection setting => external tool before connection and add the vmrun stop in the connection settings => external tool after

Voilà !

Add single element to array in numpy

Let's say a=[1,2,3] and you want it to be [1,2,3,1].

You may use the built-in append function

np.append(a,1)

Here 1 is an int, it may be a string and it may or may not belong to the elements in the array. Prints: [1,2,3,1]

What are callee and caller saved registers?

Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.

In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.

What is the canonical way to trim a string in Ruby without creating a new string?

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)

Leaflet changing Marker color

1) Add the marker 2) find the backgroundcolor attribute for the css and change it. Here it is:
JS

var myIcon = L.divIcon({
      className: 'my-div-icon',
      iconSize: [5, 5]
    });
var marker = L.marker([50,-20], {icon: myIcon}).addTo(map);
    marker.valueOf()._icon.style.backgroundColor = 'green'; //or any color

Setting HTTP headers

I know this is a different twist on the answer, but isn't this more of a concern for a web server? For example, nginx, could help.

The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header

...

location ~ ^<REGXP MATCHING CORS ROUTES> {
    add_header Access-Control-Allow-Methods POST
    ...
}
...

Adding nginx in front of your go service in production seems wise. It provides a lot more feature for authorizing, logging,and modifying requests. Also, it gives the ability to control who has access to your service and not only that but one can specify different behavior for specific locations in your app, as demonstrated above.

I could go on about why to use a web server with your go api, but I think that's a topic for another discussion.

How can I list all cookies for the current page with Javascript?

Some cookies, such as referrer urls, have = in them. As a result, simply splitting on = will cause irregular results, and the previous answers here will breakdown over time (or immediately depending on your depth of use).

This takes only the first instance of the equals sign. It returns an object with the cookie's key value pairs.

// Returns an object of key value pairs for this page's cookies
function getPageCookies(){

    // cookie is a string containing a semicolon-separated list, this split puts it into an array
    var cookieArr = document.cookie.split(";");

    // This object will hold all of the key value pairs
    var cookieObj = {};

    // Iterate the array of flat cookies to get their key value pair
    for(var i = 0; i < cookieArr.length; i++){

        // Remove the standardized whitespace
        var cookieSeg = cookieArr[i].trim();

        // Index of the split between key and value
        var firstEq = cookieSeg.indexOf("=");

        // Assignments
        var name = cookieSeg.substr(0,firstEq);
        var value = cookieSeg.substr(firstEq+1);
        cookieObj[name] = value;
   }
   return cookieObj;
}

Cordova : Requirements check failed for JDK 1.8 or greater

It's an old question, but since i just had the same problem, but the error had another source, here a short answer.

Problem accured on Windows (only) and with the Webstorm IDE 2019.2

In the version 2019.2 Webstorm had an issue, because it internally used open jdk for the %JAVA_HOME% variable instead of the (from the os) targeted java jdk.

In my case (yeah it's old, it's an old cordova project ... )

executing java -version in Windows cmd.exe:

$ java -version
java version "1.8.0_221"

but executing java -version in Webstorms terminal:

$ java -version
openjdk version "11.0.3" 2019-04-16
// more output

A fix came with the patch released later (today), version 2019.2.1. Now Webstorm uses the os %JAVA_HOME% variable as it should and the java -version output is identical in both cases.

Hope it helps someone!

How to find the extension of a file in C#?

You will not be able to restrict the file type that the user uploads at the client side[*]. You'll only be able to do this at the server side. If a user uploads an incorrect file you will only be able to recognise that once the file is uploaded uploaded. There is no reliable and safe way to stop a user uploading whatever file format they want.

[*] yes, you can do all kinds of clever stuff to detect the file extension before starting the upload, but don't rely on it. Someone will get around it and upload whatever they like sooner or later.

Count of "Defined" Array Elements

An array length is not the number of elements in a array, it is the highest index + 1. length property will report correct element count only if there are valid elements in consecutive indices.

var a = [];
a[23] = 'foo';
a.length;  // 24

Saying that, there is no way to exclude undefined elements from count without using any form of a loop.

Capturing browser logs with Selenium WebDriver using Java

Driver manager logs can be used to get console logs from browser and it will help to identify errors appears in console.

   import org.openqa.selenium.logging.LogEntries;
   import org.openqa.selenium.logging.LogEntry;

    public List<LogEntry> getBrowserConsoleLogs()
    {
    LogEntries log= driver.manage().logs().get("browser")
    List<LogEntry> logs=log.getAll();
    return logs;
    }

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

How to check if command line tools is installed

Because Xcode subsumes the CLI tools if installed first, I use the following hybrid which has been validated on 10.12 and 10.14. I expect it works on a lot of other versions:

installed=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables 2>/dev/null || pkgutil --pkg-info=com.apple.pkg.Xcode)

Salt with awk to taste for branching logic.

Of course xcode-select -p handles the variations with a really short command but fails to give the detailed package, version, and installation date metadata.

What is the proper way to re-attach detached objects in Hibernate?

Session.contains(Object obj) checks the reference and will not detect a different instance that represents the same row and is already attached to it.

Here my generic solution for Entities with an identifier property.

public static void update(final Session session, final Object entity)
{
    // if the given instance is in session, nothing to do
    if (session.contains(entity))
        return;

    // check if there is already a different attached instance representing the same row
    final ClassMetadata classMetadata = session.getSessionFactory().getClassMetadata(entity.getClass());
    final Serializable identifier = classMetadata.getIdentifier(entity, (SessionImplementor) session);

    final Object sessionEntity = session.load(entity.getClass(), identifier);
    // override changes, last call to update wins
    if (sessionEntity != null)
        session.evict(sessionEntity);
    session.update(entity);
}

This is one of the few aspects of .Net EntityFramework I like, the different attach options regarding changed entities and their properties.

Get text from pressed button

The view you get passed in on onClick() is the Button you are looking for.

public void onClick(View v) {
    // 1) Possibly check for instance of first 
    Button b = (Button)v;
    String buttonText = b.getText().toString();
}

1) If you are using a non-anonymous class as onClickListener, you may want to check for the type of the view before casting it, as it may be something different than a Button.

How to refresh Android listview?

i got some problems with dynamic refresh of my listview.

Call notifyDataSetChanged() on your Adapter.

Some additional specifics on how/when to call notifyDataSetChanged() can be viewed in this Google I/O video.

notifyDataSetChanged() did not work properly in my case[ I called the notifyDataSetChanged from another class]. Just in the case i edited the ListView in the running Activity (Thread). That video thanks to Christopher gave the final hint.

In my second class i used

Runnable run = new Runnable(){
     public void run(){
         contactsActivity.update();
     }
};
contactsActivity.runOnUiThread(run);

to acces the update() from my Activity. This update includes

myAdapter.notifyDataSetChanged();

to tell the Adapter to refresh the view. Worked fine as far as I can say.

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

Add Bootstrap Glyphicon to Input Box

It can be done using classes from the official bootstrap 3.x version, without any custom css.

Use input-group-addon before the input tag, inside of input-group then use any of the glyphicons, here is the code

<form>
  <div class="form-group">
    <div class="col-xs-5">
      <div class="input-group">
          <span class="input-group-addon transparent"><span class="glyphicon glyphicon-user"></span></span>
          <input class="form-control left-border-none" placeholder="User Name" type="text" name="username">
      </div>
    </div>
  </div>
</form>

Here is the output

enter image description here

To customise it further add a couple of lines of custom css to your own custom.css file (adjust padding if needed)

.transparent {
    background-color: transparent !important;
    box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
 }
 .left-border-none {
    border-left:none !important;
    box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
 }

By making the background of the input-group-addon transparent and making the left gradient of the input tag to zero the input will have a seamless appearance. Here is the customised output

enter image description here

Here is a jsbin example

This will solve the custom css problems of overlapping with labels, alignment while using input-lg and focus on tab issue.

How to define a default value for "input type=text" without using attribute 'value'?

You can set the value property using client script after the element is created:

<input type="text" id="fee" />

<script type="text/javascript>
document.getElementById('fee').value = '1000';
</script>

Principal Component Analysis (PCA) in Python

UPDATE: matplotlib.mlab.PCA is since release 2.2 (2018-03-06) indeed deprecated.

The library matplotlib.mlab.PCA (used in this answer) is not deprecated. So for all the folks arriving here via Google, I'll post a complete working example tested with Python 2.7.

Use the following code with care as it uses a now deprecated library!

from matplotlib.mlab import PCA
import numpy
data = numpy.array( [[3,2,5], [-2,1,6], [-1,0,4], [4,3,4], [10,-5,-6]] )
pca = PCA(data)

Now in `pca.Y' is the original data matrix in terms of the principal components basis vectors. More details about the PCA object can be found here.

>>> pca.Y
array([[ 0.67629162, -0.49384752,  0.14489202],
   [ 1.26314784,  0.60164795,  0.02858026],
   [ 0.64937611,  0.69057287, -0.06833576],
   [ 0.60697227, -0.90088738, -0.11194732],
   [-3.19578784,  0.10251408,  0.00681079]])

You can use matplotlib.pyplot to draw this data, just to convince yourself that the PCA yields "good" results. The names list is just used to annotate our five vectors.

import matplotlib.pyplot
names = [ "A", "B", "C", "D", "E" ]
matplotlib.pyplot.scatter(pca.Y[:,0], pca.Y[:,1])
for label, x, y in zip(names, pca.Y[:,0], pca.Y[:,1]):
    matplotlib.pyplot.annotate( label, xy=(x, y), xytext=(-2, 2), textcoords='offset points', ha='right', va='bottom' )
matplotlib.pyplot.show()

Looking at our original vectors we'll see that data[0] ("A") and data[3] ("D") are rather similar as are data[1] ("B") and data[2] ("C"). This is reflected in the 2D plot of our PCA transformed data.

PCA result plot

How to filter Android logcat by application?

Use fully qualified class names for your log tags:

public class MyActivity extends Activity {
  private static final String TAG = MyActivity.class.getName();
}

Then

Log.i(TAG, "hi");

Then use grep

adb logcat | grep com.myapp

How to use a App.config file in WPF applications?

In my case, I followed the steps below.

App.config

<configuration>  
   <startup> 
       <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>

 <appSettings>
   <add key="POCPublishSubscribeQueueName" value="FormatName:Direct=OS:localhost\Private$\POCPublishSubscribe"/>
 </appSettings>

</configuration>

Added System.Configuartion to my project.

Added using System.Configuration statement in file at top.

Then used this statement:

string queuePath = ConfigurationManager.AppSettings["POCPublishSubscribeQueueName"].ToString();

Install mysql-python (Windows)

For phpmydamin you can use following step

  1. Go to python install path like

     cd C:\Users\Enamul\AppData\Local\Programs\Python\Python37-32\Scripts
    
  2. Run the command pip install PyMySQL

  3. In the python shell import library like import pymysql

  4. connection to databasbe

     db = pymysql.connect(host='localhost',user='root',passwd='yourpassword', database="bd")
    
  5. get cursor cursor = db.cursor()

  6. Create table like

    cursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
    

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).

Convert Unix timestamp to a date string

If you find the notation awkward, maybe the -R-option does help. It outpouts the date in RFC 2822 format. So you won't need all those identifiers: date -d @1278999698 -R. Another possibility is to output the date in seconds in your locale: date -d @1278999698 +%c. Should be easy to remember. :-)

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

Telnet is not recognized as internal or external command

You can try using Putty (freeware). It is mainly known as a SSH client, but you can use for Telnet login as well

Embed Google Map code in HTML with marker

USE this , Don't forget to get a google api key from

https://console.developers.google.com/apis/credentials

and replace it

    <div id="map" style="width:100%;height:400px;"></div>

<script>
function myMap() {

var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var myCenter = new google.maps.LatLng(38.224905, 48.252143);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 16};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=myMap"></script>

How can I add a username and password to Jenkins?

Assuming you have Manage Jenkins > Configure Global Security > Enable Security and Jenkins Own User Database checked you would go to:

  • Manage Jenkins > Manage Users > Create User

IP to Location using Javascript

You can submit the IP you receive to an online geolocation service, such as http://www.geoplugin.net/json.gp?ip=<your ip here>&jsoncallback=<suitable javascript function in your source>, then including the source it returns which will run the function you specify in jsoncallback with the geolocation information.

Alternatively, you may want to look into HTML5's geolocation features -- you can see a demo of it in action here. The advantage of this is that you do not need to make requests to foreign servers, but it may not work on browsers that do not support HTML5.

How to initialize std::vector from C-style array?

You can 'learn' the size of the array automatically:

template<typename T, size_t N>
void set_data(const T (&w)[N]){
    w_.assign(w, w+N);
}

Hopefully, you can change the interface to set_data as above. It still accepts a C-style array as its first argument. It just happens to take it by reference.


How it works

[ Update: See here for a more comprehensive discussion on learning the size ]

Here is a more general solution:

template<typename T, size_t N>
void copy_from_array(vector<T> &target_vector, const T (&source_array)[N]) {
    target_vector.assign(source_array, source_array+N);
}

This works because the array is being passed as a reference-to-an-array. In C/C++, you cannot pass an array as a function, instead it will decay to a pointer and you lose the size. But in C++, you can pass a reference to the array.

Passing an array by reference requires the types to match up exactly. The size of an array is part of its type. This means we can use the template parameter N to learn the size for us.

It might be even simpler to have this function which returns a vector. With appropriate compiler optimizations in effect, this should be faster than it looks.

template<typename T, size_t N>
vector<T> convert_array_to_vector(const T (&source_array)[N]) {
    return vector<T>(source_array, source_array+N);
}

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

How to get index of an item in java.util.Set

you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.

How to remove margin space around body or clear default css styles

body has default margins: http://www.w3.org/TR/CSS2/sample.html

body { margin:0; } /* Remove body margins */

Or you could use this useful Global reset

* { margin:0; padding:0; box-sizing:border-box; }

If you want something less * global than:

html, body, body div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, hgroup, menu, nav, section, time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}

some other CSS Reset:

http://yui.yahooapis.com/3.5.0/build/cssreset/cssreset-min.css
http://meyerweb.com/eric/tools/css/reset/
https://github.com/necolas/normalize.css/
http://html5doctor.com/html-5-reset-stylesheet/

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

"Rate This App"-link in Google Play store app on the phone

I open the Play Store from my App with the following code:

            val uri: Uri = Uri.parse("market://details?id=$packageName")
            val goToMarket = Intent(Intent.ACTION_VIEW, uri)
            // To count with Play market backstack, After pressing back button, 
            // to taken back to our application, we need to add following flags to intent. 
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY or
                    Intent.FLAG_ACTIVITY_NEW_DOCUMENT or
                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
            try {
                startActivity(goToMarket)
            } catch (e: ActivityNotFoundException) {
                startActivity(Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://play.google.com/store/apps/details?id=$packageName")))
            }

How to fix apt-get: command not found on AWS EC2?

I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.

T-SQL get SELECTed value of stored procedure

You'd need to use return values.

DECLARE @SelectedValue int

CREATE PROCEDURE GetMyInt (@MyIntField int OUTPUT)
AS
SELECT @MyIntField = MyIntField FROM MyTable WHERE MyPrimaryKeyField = 1

Then you call it like this:

EXEC GetMyInt OUTPUT @SelectedValue

Generate unique random numbers between 1 and 100

This solution uses the hash which is much more performant O(1) than checking if the resides in the array. It has extra safe checks too. Hope it helps.

function uniqueArray(minRange, maxRange, arrayLength) {
  var arrayLength = (arrayLength) ? arrayLength : 10
  var minRange = (minRange !== undefined) ? minRange : 1
  var maxRange = (maxRange !== undefined) ? maxRange : 100
  var numberOfItemsInArray = 0
  var hash = {}
  var array = []

  if ( arrayLength > (maxRange - minRange) ) throw new Error('Cannot generate unique array: Array length too high')

  while(numberOfItemsInArray < arrayLength){
    // var randomNumber = Math.floor(Math.random() * (maxRange - minRange + 1) + minRange)
    // following line used for performance benefits
    var randomNumber = (Math.random() * (maxRange - minRange + 1) + minRange) << 0

    if (!hash[randomNumber]) {
      hash[randomNumber] = true
      array.push(randomNumber)
      numberOfItemsInArray++
    }
  }
  return array
}
document.write(uniqueArray(1, 100, 8))

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Use this, works for me always.

Response.Redirect(Request.RawUrl, false);

Here, Response.Redirect(Request.RawUrl) simply redirects to the url of the current context, while the second parameter "false" indicates to either endResponse or not.

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

failed to find target with hash string 'android-22'

Just click on the link written in the error:

Open Android SDK Manager

and it will show you the dialogs that will help you to install the required sdk for your project.

Best way to detect when a user leaves a web page?

Thanks to Service Workers, it is possible to implement a solution similar to Adam's purely on the client-side, granted the browser supports it. Just circumvent heartbeat requests:

// The delay should be longer than the heartbeat by a significant enough amount that there won't be false positives
const liveTimeoutDelay = 10000
let liveTimeout = null

global.self.addEventListener('fetch', event => {
  clearTimeout(liveTimeout)
  liveTimeout = setTimeout(() => {
    console.log('User left page')
    // handle page leave
  }, liveTimeoutDelay)
  // Forward any events except for hearbeat events
  if (event.request.url.endsWith('/heartbeat')) {
    event.respondWith(
      new global.Response('Still here')
    )
  }
})

Android Studio: Where is the Compiler Error Output Window?

Are you on Windows? Launch cmd, find your project folder and run "gradlew build". This should already give you more output than the IDE, you can also use --info, --stacktrace and --debug there.

How to move Docker containers between different hosts?

Alternatively, if you do not wish to push to a repository:

  1. Export the container to a tarball

    docker export <CONTAINER ID> > /home/export.tar
    
  2. Move your tarball to new machine

  3. Import it back

    cat /home/export.tar | docker import - some-name:latest
    

Add Favicon to Website

Simply put a file named favicon.ico in the webroot.

If you want to know more, please start reading:

How to find the kth largest element in an unsorted array of length n in O(n)?

There is also one algorithm, that outperforms quickselect algorithm. It's called Floyd-Rivets (FR) algorithm.

Original article: https://doi.org/10.1145/360680.360694

Downloadable version: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.309.7108&rep=rep1&type=pdf

Wikipedia article https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm

I tried to implement quickselect and FR algorithm in C++. Also I compared them to the standard C++ library implementations std::nth_element (which is basically introselect hybrid of quickselect and heapselect). The result was quickselect and nth_element ran comparably on average, but FR algorithm ran approx. twice as fast compared to them.

Sample code that I used for FR algorithm:

template <typename T>
T FRselect(std::vector<T>& data, const size_t& n)
{
    if (n == 0)
        return *(std::min_element(data.begin(), data.end()));
    else if (n == data.size() - 1)
        return *(std::max_element(data.begin(), data.end()));
    else
        return _FRselect(data, 0, data.size() - 1, n);
}

template <typename T>
T _FRselect(std::vector<T>& data, const size_t& left, const size_t& right, const size_t& n)
{
    size_t leftIdx = left;
    size_t rightIdx = right;

    while (rightIdx > leftIdx)
    {
        if (rightIdx - leftIdx > 600)
        {
            size_t range = rightIdx - leftIdx + 1;
            long long i = n - (long long)leftIdx + 1;
            long long z = log(range);
            long long s = 0.5 * exp(2 * z / 3);
            long long sd = 0.5 * sqrt(z * s * (range - s) / range) * sgn(i - (long long)range / 2);

            size_t newLeft = fmax(leftIdx, n - i * s / range + sd);
            size_t newRight = fmin(rightIdx, n + (range - i) * s / range + sd);

            _FRselect(data, newLeft, newRight, n);
        }
        T t = data[n];
        size_t i = leftIdx;
        size_t j = rightIdx;
        // arrange pivot and right index
        std::swap(data[leftIdx], data[n]);
        if (data[rightIdx] > t)
            std::swap(data[rightIdx], data[leftIdx]);

        while (i < j)
        {
            std::swap(data[i], data[j]);
            ++i; --j;
            while (data[i] < t) ++i;
            while (data[j] > t) --j;
        }

        if (data[leftIdx] == t)
            std::swap(data[leftIdx], data[j]);
        else
        {
            ++j;
            std::swap(data[j], data[rightIdx]);
        }
        // adjust left and right towards the boundaries of the subset
        // containing the (k - left + 1)th smallest element
        if (j <= n)
            leftIdx = j + 1;
        if (n <= j)
            rightIdx = j - 1;
    }

    return data[leftIdx];
}

template <typename T>
int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

Erase whole array Python

It's simple:

array = []

will set array to be an empty list. (They're called lists in Python, by the way, not arrays)

If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.

Asp.net Validation of viewstate MAC failed

If you're using a web farm and running the same application on multiple computers, you need to define the machine key explicitly in the machine.config file:

<machineKey validationKey="JFDSGOIEURTJKTREKOIRUWTKLRJTKUROIUFLKSIOSUGOIFDS..." decryptionKey="KAJDFOIAUOILKER534095U43098435H43OI5098479854" validation="SHA1" />

Put it under the <system.web> tag.

The AutoGenerate for the machine code can not be used. To generate your own machineKey see this powershell script: https://support.microsoft.com/en-us/kb/2915218#bookmark-appendixa

Get the correct week number of a given date

Based on il_guru's answer, I created this version for my own needs that also returns the year component.

    /// <summary>
    /// This presumes that weeks start with Monday.
    /// Week 1 is the 1st week of the year with a Thursday in it.
    /// </summary>
    /// <param name="time">The date to calculate the weeknumber for.</param>
    /// <returns>The year and weeknumber</returns>
    /// <remarks>
    /// Based on Stack Overflow Answer: https://stackoverflow.com/a/11155102
    /// </remarks>
    public static (short year, byte week) GetIso8601WeekOfYear(DateTime time)
    {
        // Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll
        // be the same week# as whatever Thursday, Friday or Saturday are,
        // and we always get those right
        DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
        if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
        {
            time = time.AddDays(3);
        }
        // Return the week of our adjusted day
        var week = (byte)CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
        return ((short)(week >= 52 & time.Month == 1 ? time.Year - 1 : time.Year), week);
    }

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

You are confusing 'sets' and 'lists'. A set does not guarantee order, but lists do.

Sets are declared using curly brackets: {}. In contrast, lists are declared using square brackets: [].

mySet = {a, b, c, c}

Does not guarantee order, but list does:

myList = [a, b, c]