Programs & Examples On #Microsoft ui automation

The Microsoft UI Automation (UIA) framework provides programmatic access to most user interface elements on Win32, WinForms, and WPF applications. It is primarily used for the purposes of automated UI testing and accessibility assistance.

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

Java Does Not Equal (!=) Not Working?

do the one of these.

   if(!statusCheck.equals("success"))
    {
        //do something
    }

      or

    if(!"success".equals(statusCheck))
    {
        //do something
    }

Code for Greatest Common Divisor in Python

I had to do something like this for a homework assignment using while loops. Not the most efficient way, but if you don't want to use a function this works:

num1 = 20
num1_list = []
num2 = 40
num2_list = []
x = 1
y = 1
while x <= num1:
    if num1 % x == 0:
        num1_list.append(x)
    x += 1
while y <= num2:
    if num2 % y == 0:
        num2_list.append(y)
    y += 1
xy = list(set(num1_list).intersection(num2_list))
print(xy[-1])

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

How to write DataFrame to postgres table?

Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)

You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of pandas.io.sql: https://gist.github.com/jorisvandenbossche/10841234.
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where con is a postgresql connection):

import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

How can I check for NaN values?

numpy.isnan(number) tells you if it's NaN or not.

How to change the port of Tomcat from 8080 to 80?

On Ubuntu and Debian systems, there are several steps needed:

  1. In server.xml, change the line <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> to have port="80".

  2. Install the recommended (not required) authbind package, with a command like:

    sudo apt-get install authbind

  3. Enable authbind in the server.xml file (in either /etc/tomcat6 or /etc/tomcat7) by uncommenting and setting the line like:

    AUTHBIND=yes

All three steps are needed.

Set keyboard caret position in html textbox

I found an easy way to fix this issue, tested in IE and Chrome:

function setCaret(elemId, caret)
 {
   var elem = document.getElementById(elemId);
   elem.setSelectionRange(caret, caret);
 }

Pass text box id and caret position to this function.

How do I download a package from apt-get without installing it?

There are a least these apt-get extension packages that can help:

apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media

This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.

Otherwise, the --download-only option to apt-get is your friend:

 -d, --download-only
     Download only; package files are only retrieved, not unpacked or installed.
     Configuration Item: APT::Get::Download-Only.

Does JSON syntax allow duplicate keys in an object?

There are 2 documents specifying the JSON format:

  1. http://json.org/
  2. https://tools.ietf.org/html/rfc7159

The accepted answer quotes from the 1st document. I think the 1st document is more clear, but the 2nd contains more detail.

The 2nd document says:

  1. Objects

    An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

So it is not forbidden to have a duplicate name, but it is discouraged.

Why aren't variable-length arrays part of the C++ standard?

There are situations where allocating heap memory is very expensive compared to the operations performed. An example is matrix math. If you work with smallish matrices say 5 to 10 elements and do a lot of arithmetics the malloc overhead will be really significant. At the same time making the size a compile time constant does seem very wasteful and inflexible.

I think that C++ is so unsafe in itself that the argument to "try to not add more unsafe features" is not very strong. On the other hand, as C++ is arguably the most runtime efficient programming language features which makes it more so are always useful: People who write performance critical programs will to a large extent use C++, and they need as much performance as possible. Moving stuff from heap to stack is one such possibility. Reducing the number of heap blocks is another. Allowing VLAs as object members would one way to achieve this. I'm working on such a suggestion. It is a bit complicated to implement, admittedly, but it seems quite doable.

Add Facebook Share button to static HTML page

Replace <url> with your own link

<script>function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}</script><style> html .fb_share_link { padding:2px 0 0 20px; height:16px; background:url(http://static.ak.facebook.com/images/share/facebook_share_icon.gif?6:26981) no-repeat top left; }</style><a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank" class="fb_share_link">Share on Facebook</a>

Replace given value in vector

The ifelse function would be a quick and easy way to do this.

How do I scroll to an element using JavaScript?

try this function

function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}

Pass the div id as parameter it will work I am using it already

#pragma pack effect

I've used it in code before, though only to interface with legacy code. This was a Mac OS X Cocoa application that needed to load preference files from an earlier, Carbon version (which was itself backwards-compatible with the original M68k System 6.5 version...you get the idea). The preference files in the original version were a binary dump of a configuration structure, that used the #pragma pack(1) to avoid taking up extra space and saving junk (i.e. the padding bytes that would otherwise be in the structure).

The original authors of the code had also used #pragma pack(1) to store structures that were used as messages in inter-process communication. I think the reason here was to avoid the possibility of unknown or changed padding sizes, as the code sometimes looked at a specific portion of the message struct by counting a number of bytes in from the start (ewww).

Open files in 'rt' and 'wt' modes

t refers to the text mode. There is no difference between r and rt or w and wt since text mode is the default.

Documented here:

Character   Meaning
'r'     open for reading (default)
'w'     open for writing, truncating the file first
'x'     open for exclusive creation, failing if the file already exists
'a'     open for writing, appending to the end of the file if it exists
'b'     binary mode
't'     text mode (default)
'+'     open a disk file for updating (reading and writing)
'U'     universal newlines mode (deprecated)

The default mode is 'r' (open for reading text, synonym of 'rt').

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

If you are using rbenv then make sure that you run the "rbenv rehash" command after you set local or global ruby version. It solved the issue for me.

rbenv rehash

How to change a string into uppercase

To get upper case version of a string you can use str.upper:

s = 'sdsd'
s.upper()
#=> 'SDSD'

On the other hand string.ascii_uppercase is a string containing all ASCII letters in upper case:

import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

input type="submit" Vs button tag are they interchangeable?

Although both elements deliver functionally the same result *, I strongly recommend you use <button>:

  • Far more explicit and readable. input suggests that the control is editable, or can be edited by the user; button is far more explicit in terms of the purpose it serves
  • Easier to style in CSS; as mentioned above, FIrefox and IE have quirks in which input[type="submit"] do not display correctly in some cases
  • Predictable requests: IE has verying behaviours when values are submitted in the POST/GET request to the server
  • Markup-friendly; you can nest items, for example, icons, inside the button.
  • HTML5, forward-thinking; as developers, it is our responsibility to adopt to the new spec once it is officialized. HTML5, as of right now, has been official for over one year now, and has been shown in many cases to boost SEO.

* With the exception of <button type="button"> which by default has no specified behaviour.

In summary, I highly discourage use of <input type="submit" />.

HTML Submit-button: Different value / button-text?

I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.

Error Importing SSL certificate : Not an X.509 Certificate

I changed 3 things and then it works:

  1. There is a column of spaces, I removed them
  2. Changed the line break from windows CRLF to linux LF
  3. Removed the empty line at the end.

How to change PHP version used by composer

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

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

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

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

Disable XML validation in Eclipse

Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.

So, if I have the following NewFile.xml:

<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />

And the eclipse encoding is UTF-8:

Eclipse Encoding Resource

The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.

The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.

EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.

When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.

  1. Suspend the validators
  2. Click on the 'Content is not allowed in prolog' message, right click and delete. You can select multiple ones, or all of them.
  3. Do a Project->Clean. The messages should not come back.

I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.

javascript date to string

You will need to pad with "0" if its a single digit & note getMonth returns 0..11 not 1..12

function printDate() {
    var temp = new Date();
    var dateStr = padStr(temp.getFullYear()) +
                  padStr(1 + temp.getMonth()) +
                  padStr(temp.getDate()) +
                  padStr(temp.getHours()) +
                  padStr(temp.getMinutes()) +
                  padStr(temp.getSeconds());
    debug (dateStr );
}

function padStr(i) {
    return (i < 10) ? "0" + i : "" + i;
}

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

Define static method in source-file with declaration in header-file in C++

You don't need to have static in function definition

Change font color and background in html on mouseover

You'd better use CSS for this:

td{
    background-color:black;
    color:white;
}
td:hover{
    background-color:white;
    color:black;
}

If you want to use these styles for only a specific set of elements, you should give your td a class (or an ID, if it's the only element which'll have that style).

Example :

HTML

<td class="whiteHover"></td>

CSS

.whiteHover{
    /* Same style as above */
}

Here's a reference on MDN for :hover pseudo class.

Creating multiline strings in JavaScript

Updated for 2015: it's six years later now: most people use a module loader, and the main module systems each have ways of loading templates. It's not inline, but the most common type of multiline string are templates, and templates should generally be kept out of JS anyway.

require.js: 'require text'.

Using require.js 'text' plugin, with a multiline template in template.html

var template = require('text!template.html')

NPM/browserify: the 'brfs' module

Browserify uses a 'brfs' module to load text files. This will actually build your template into your bundled HTML.

var fs = require("fs");
var template = fs.readFileSync(template.html', 'utf8');

Easy.

jQuery map vs. each

Jquery.map makes more sense when you are doing work on arrays as it performs very well with arrays.

Jquery.each is best used when iterating through selector items. Which is evidenced in that the map function does not use a selector.

$(selector).each(...)

$.map(arr....)

as you can see, map is not intended to be used with selectors.

What is the easiest way to clear a database from the CLI with manage.py in Django?

I think Django docs explicitly mention that if the intent is to start from an empty DB again (which seems to be OP's intent), then just drop and re-create the database and re-run migrate (instead of using flush):

If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.

So for OP's case, we just need to:

  1. Drop the database from MySQL
  2. Recreate the database
  3. Run python manage.py migrate

How to save and load numpy.array() data properly?

For a short answer you should use np.save and np.load. The advantages of these is that they are made by developers of the numpy library and they already work (plus are likely already optimized nicely) e.g.

import numpy as np
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

np.save(path/'x', x)
np.save(path/'y', y)

x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')

print(x is x_loaded) # False
print(x == x_loaded) # [[ True  True  True  True  True]]

Expanded answer:

In the end it really depends in your needs because you can also save it human readable format (see this Dump a NumPy array into a csv file) or even with other libraries if your files are extremely large (see this best way to preserve numpy arrays on disk for an expanded discussion).

However, (making an expansion since you use the word "properly" in your question) I still think using the numpy function out of the box (and most code!) most likely satisfy most user needs. The most important reason is that it already works. Trying to use something else for any other reason might take you on an unexpectedly LONG rabbit hole to figure out why it doesn't work and force it work.

Take for example trying to save it with pickle. I tried that just for fun and it took me at least 30 minutes to realize that pickle wouldn't save my stuff unless I opened & read the file in bytes mode with wb. Took time to google, try thing, understand the error message etc... Small detail but the fact that it already required me to open a file complicated things in unexpected ways. To add that it required me to re-read this (which btw is sort of confusing) Difference between modes a, a+, w, w+, and r+ in built-in open function?.

So if there is an interface that meets your needs use it unless you have a (very) good reason (e.g. compatibility with matlab or for some reason your really want to read the file and printing in python really doesn't meet your needs, which might be questionable). Furthermore, most likely if you need to optimize it you'll find out later down the line (rather than spend ages debugging useless stuff like opening a simple numpy file).

So use the interface/numpy provide. It might not be perfect it's most likely fine, especially for a library that's been around as long as numpy.

I already spent the saving and loading data with numpy in a bunch of way so have fun with it, hope it helps!

import numpy as np
import pickle
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

# using save (to npy), savez (to npz)
np.save(path/'x', x)
np.save(path/'y', y)
np.savez(path/'db', x=x, y=y)
with open(path/'db.pkl', 'wb') as db_file:
    pickle.dump(obj={'x':x, 'y':y}, file=db_file)

## using loading npy, npz files
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
db = np.load(path/'db.npz')
with open(path/'db.pkl', 'rb') as db_file:
    db_pkl = pickle.load(db_file)

print(x is x_loaded)
print(x == x_loaded)
print(x == db['x'])
print(x == db_pkl['x'])
print('done')

Some comments on what I learned:

  • np.save as expected, this already compresses it well (see https://stackoverflow.com/a/55750128/1601580), works out of the box without any file opening. Clean. Easy. Efficient. Use it.
  • np.savez uses a uncompressed format (see docs) Save several arrays into a single file in uncompressed .npz format. If you decide to use this (you were warned to go away from the standard solution so expect bugs!) you might discover that you need to use argument names to save it, unless you want to use the default names. So don't use this if the first already works (or any works use that!)
  • Pickle also allows for arbitrary code execution. Some people might not want to use this for security reasons.
  • human readable files are expensive to make etc. Probably not worth it.
  • there is something called hdf5 for large files. Cool! https://stackoverflow.com/a/9619713/1601580

Note this is not an exhaustive answer. But for other resources check this:

Is there an "if -then - else " statement in XPath?

Unfortunately the previous answers were no option for me so i researched for a while and found this solution:

http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method

I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.

substring('foo',number(not(normalize-space(/elements/the/element/)))*4)

Cannot run emulator in Android Studio

A common approach to follow to solve this problem.

1.CHECK your SDK manager by running from your android studio and stand alons sdk folder by executing ./android.sh helps you to find broken packages

  1. Try installing System emulator images with google API support than the Intel one. Just like , i solved my problem by running into another system image.

  2. Experment on KVM based Virtulaization suggested by Google for Linux

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

Depending on the device, sometimes you are getting "The folder you specified doesn't contain a compatible software" error because the first interface isn't actually the ADB interface.

Try installing it as a generic "USB composite device" instead (from the 'pick from a list' driver install option); once the standard composite driver installs it will allow Windows to communicate with the device and detect the associated ADB driver interface and install it properly.

Android Studio is slow (how to speed up)?

If your app code base is large and you have multiple modules then you can try Local AAR approach as described here, it will give you a big boost in Android Studio performance.

https://blog.gojekengineering.com/how-we-improved-performance-and-build-times-in-android-studio-306028166b79

Sample project can be found here:

https://github.com/akhgupta/AndroidLocalMavenRepoAARDemo

HttpGet with HTTPS : SSLPeerUnverifiedException

Method returning a "secureClient" (in a Java 7 environnement - NetBeans IDE and GlassFish Server: port https by default 3920 ), hope this could help :

public DefaultHttpClient secureClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    SSLSocketFactory sf;

    KeyStore trustStore;
    FileInputStream trustStream = null;
    File truststoreFile;
    // java.security.cert.PKIXParameters for the trustStore
    PKIXParameters pkixParamsTrust;

    KeyStore keyStore;
    FileInputStream keyStream = null;
    File keystoreFile;
    // java.security.cert.PKIXParameters for the keyStore
    PKIXParameters pkixParamsKey;

    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        truststoreFile = new File(TRUSTSTORE_FILE);
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystoreFile = new File(KEYSTORE_FILE);
        try {
            trustStream = new FileInputStream(truststoreFile);
            keyStream = new FileInputStream(keystoreFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            trustStore.load(trustStream, PASSWORD.toCharArray());
            keyStore.load(keyStream, PASSWORD.toCharArray());
        } catch (IOException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsTrust = new PKIXParameters(trustStore);
            // accepts Server certificate generated with keytool and (auto) signed by SUN
            pkixParamsTrust.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsKey = new PKIXParameters(keyStore);
            // accepts Client certificate generated with keytool and (auto) signed by SUN
            pkixParamsKey.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            sf = new SSLSocketFactory(trustStore);
            ClientConnectionManager manager = httpclient.getConnectionManager();
            manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
        } catch (KeyManagementException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnrecoverableKeyException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    // use the httpclient for any httpRequest
    return httpclient;
}

What's the regular expression that matches a square bracket?

If you want to remove the [ or the ], use the expression: "\\[|\\]".

The two backslashes escape the square bracket and the pipe is an "or".

HTML5 event handling(onfocus and onfocusout) using angular 2

I've created a little directive that bind with the tabindex attribute. It adds/removes the has-focus class dynamically.

@Directive({
    selector: "[tabindex]"
})
export class TabindexDirective {
    constructor(private elementHost: ElementRef) {}

    @HostListener("focus")
    setInputFocus(): void {
        this.elementHost.nativeElement.classList.add("has-focus");
    }

    @HostListener("blur")
    setInputFocusOut(): void {
        this.elementHost.nativeElement.classList.remove("has-focus");
    }
}

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

Open an html page in default browser with VBA?

You can use the Windows API function ShellExecute to do so:

Option Explicit

Private Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal Filename As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long

Public Sub OpenUrl()

    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", "www.google.com")

End Sub

Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute would execute any command with the user's permissions, also a format c: would be executed if the user is an administrator.

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

How can I decrypt a password hash in PHP?

I need to decrypt a password. The password is crypted with password_hash function.

$password = 'examplepassword';
$crypted = password_hash($password, PASSWORD_DEFAULT);

Its not clear to me if you need password_verify, or you are trying to gain unauthorized access to the application or database. Other have talked about password_verify, so here's how you could gain unauthorized access. Its what bad guys often do when they try to gain access to a system.

First, create a list of plain text passwords. A plain text list can be found in a number of places due to the massive data breaches from companies like Adobe. Sort the list and then take the top 10,000 or 100,000 or so.

Second, create a list of digested passwords. Simply encrypt or hash the password. Based on your code above, it does not look like a salt is being used (or its a fixed salt). This makes the attack very easy.

Third, for each digested password in the list, perform a select in an attempt to find a user who is using the password:

$sql_script = 'select * from USERS where password="'.$digested_password.'"'

Fourth, profit.

So, rather than picking a user and trying to reverse their password, the bad guy picks a common password and tries to find a user who is using it. Odds are on the bad guy's side...

Because the bad guy does these things, it would behove you to not let users choose common passwords. In this case, take a look at ProCheck, EnFilter or Hyppocrates (et al). They are filtering libraries that reject bad passwords. ProCheck achieves very high compression, and can digest multi-million word password lists into a 30KB data file.

Determining if a number is prime

I would guess taking sqrt and running foreach frpm 2 to sqrt+1 if(input% number!=0) return false; once you reach sqrt+1 you can be sure its prime.

Shuffle an array with python, randomize array item order with python

The other answers are the easiest, however it's a bit annoying that the random.shuffle method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:

    import random
    def my_shuffle(array):
        random.shuffle(array)
        return array

Then you can do lines like:

    for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):

resize2fs: Bad magic number in super-block while trying to open

On centos and fedora work with fsadm

fsadm resize /dev/vg_name/root

image.onload event and browser cache

There are two possible solutions for these kind of situations:

  1. Use the solution suggested on this post
  2. Add a unique suffix to the image src to force browser downloading it again, like this:

    var img = new Image();
    img.src = "img.jpg?_="+(new Date().getTime());
    img.onload = function () {
        alert("image is loaded");
    }
    

In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again

How to pass a null variable to a SQL Stored Procedure from C#.net code

    SQLParam = cmd.Parameters.Add("@RetailerID", SqlDbType.Int, 4)
    If p_RetailerID.Length = 0 Or p_RetailerID = "0" Then
        SQLParam.Value = DBNull.Value
    Else
        SQLParam.Value = p_RetailerID
    End If

C# how to change data in DataTable?

dt.Rows[1].ItemArray gives you a copy of item arrays. When you modify it, you're not modifying the original.

You can simply do this:

dt.Rows[1][3] = "Value";

ItemArray property is used when you want to modify all row values.

ex.:

dt.Rows[1].ItemArray = newItemArray;

How do you see the entire command history in interactive Python?

Since the above only works for python 2.x for python 3.x (specifically 3.5) is similar but with a slight modification:

import readline
for i in range(readline.get_current_history_length()):
    print (readline.get_history_item(i + 1))

note the extra ()

(using shell scripts to parse .python_history or using python to modify the above code is a matter of personal taste and situation imho)

CSS Margin: 0 is not setting to 0

you should have either (or both):

  1. a paddding != 0 on body
  2. a margin !=0 on #header

try

html, #header {
    margin: 0 !important;
    padding: 0 !important;
}

The margin is the "space" outside the box, the padding is the "space" inside the box (between the border and the content). The !important prevent overriding of property by latter rules.

XML Parser for C

For C++ I suggest using CMarkup.

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

When is it appropriate to use UDP instead of TCP?

Network communication for video games is almost always done over UDP.

Speed is of utmost importance and it doesn't really matter if updates are missed since each update contains the complete current state of what the player can see.

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

Angular JS Uncaught Error: [$injector:modulerr]

I got this error because I had a dependency on another module that was not loaded.

angular.module("app", ["kendo.directives"]).controller("MyCtrl", function(){}...

so even though I had all the Angular modules, I didn't have the kendo one.

How to program a fractal?

You should indeed start with the Mandelbrot set, and understand what it really is.

The idea behind it is relatively simple. You start with a function of complex variable

f(z) = z2 + C

where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).

In practice, to draw the Mandelbrot set you should:

  • Choose a rectangle in the complex plane (say, from point -2-2i to point 2+2i).
  • Cover the rectangle with a suitable rectangular grid of points (say, 400x400 points), which will be mapped to pixels on your monitor.
  • For each point/pixel, let C be that point, compute, say, 20 terms of the corresponding iterated sequence z1, z2, z3, ... and check whether it "goes to infinity". In practice you can check, while iterating, if the absolute value of one of the 20 terms is greater than 2 (if one of the terms does, the subsequent terms are guaranteed to be unbounded). If some z_k does, the sequence "goes to infinity"; otherwise, you can consider it as bounded.
  • If the sequence corresponding to a certain point C is bounded, draw the corresponding pixel on the picture in black (for it belongs to the Mandelbrot set). Otherwise, draw it in another color. If you want to have fun and produce pretty plots, draw it in different colors depending on the magnitude of abs(20th term).

The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.

Enjoy!

How to pause a YouTube player when hiding the iframe?

RobW's way worked great for me. For people using jQuery here's a simplified version that I ended up using:

var iframe = $(video_player_div).find('iframe');

var src = $(iframe).attr('src');      

$(iframe).attr('src', '').attr('src', src);

In this example "video_player" is a parent div containing the iframe.

How to check if the user can go back in browser history or not

Solution

'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  }
}

Explaination

window.location.pathname will give you the current URI. For instance https://domain/question/1234/i-have-a-problem will give /question/1234/i-have-a-problem. See the documentation about window.location for more informations.

Next, the call to split() will give us all fragments of that URI. so if we take our previous URI, we will have something like ["", "question", "1234", "i-have-a-problem"]. See the documentation about String.prototype.split() for more informations.

The call to filter() is here to filter out the empty string generated by the backward slash. It will basically return only the fragment URI that have a length greater than 1 (non-empty string). So we would have something like ["question", "1234", "i-have-a-question"]. This could have been writen like so:

'use strict';
window.location.pathname.split('/').filter(function(fragment) {
  return fragment.length > 0;
});

See the documentation about Array.prototype.filter() and the Destructuring assignment for more informations.

Now, if the user tries to go back while being on https://domain/, we wont trigger the if-statement, and so wont trigger the window.history.back() method so the user will stay in our website. This URL will be equivalent to [] which has a length of 0, and 0 > 0 is false. Hence, silently failing. Of course, you can log something or have another action if you want.

'use strict';
function previousPage() {
  if (window.location.pathname.split('/').filter(({ length }) => length > 0).length > 0) {
    window.history.back();
  } else {
    alert('You cannot go back any further...');
  }
}

Limitations

Of course, this solution wont work if the browser do not support the History API. Check the documentation to know more about it before using this solution.

In MySQL, how to copy the content of one table to another table within the same database?

Try this. Works well in my Oracle 10g,

CREATE TABLE new_table
  AS (SELECT * FROM old_table);

How to keep environment variables when using sudo

If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.

# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document 
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

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

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

How to open a folder in Windows Explorer from VBA?

I just used this and it works fine:

System.Diagnostics.Process.Start("C:/Users/Admin/files");

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

git error: failed to push some refs to remote

Not sure if this applies, but the fix for me was to commit something locally after git init. Then I pushed to remote using --set-upstream ...

Replace text in HTML page with jQuery

Like others mentioned in this thread, replacing the entire body HTML is a bad idea because it reinserts the entire DOM and can potentially break any other javascript that was acting on those elements.

Instead, replace just the text on your page and not the DOM elements themselves using jQuery filter:

  $('body :not(script)').contents().filter(function() {
    return this.nodeType === 3;
  }).replaceWith(function() {
      return this.nodeValue.replace('-9o0-9909','The new string');
  });

this.nodeType is the type of node we are looking to replace the contents of. nodeType 3 is text. See the full list here.

How to output in CLI during execution of PHP Unit tests?

Update: See rdlowrey's update below regarding the use of fwrite(STDERR, print_r($myDebugVar, TRUE)); as a much simpler work around


This behaviour is intentional (as jasonbar has pointed out). The conflicting state of the manual has been reported to PHPUnit.

A work-around is to have PHPUnit assert the expected output is empty (when infact there is output) which will trigger the unexpected output to be shown.

class theTest extends PHPUnit_Framework_TestCase
{
    /**
     * @outputBuffering disabled
     */
    public function testOutput() {
        $this->expectOutputString(''); // tell PHPUnit to expect '' as output
        print_r("Hello World");
        print "Ping";
        echo "Pong";
        $out = "Foo";
        var_dump($out);
    }   
}

gives:

PHPUnit @package_version@ by Sebastian Bergmann.

F

Time: 1 second, Memory: 3.50Mb

There was 1 failure:

1) theTest::testOutput
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-''
+'Hello WorldPingPongstring(4) "Foo"
+'

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Be certain to disable any other assertions you have for the test as they may fail before the output assertion is tested (and hence you wont see the output).

`require': no such file to load -- mkmf (LoadError)

After some search for a solution it turns out the -dev package is needed, not just ruby1.8. So if you have ruby1.9.1 doing

sudo apt-get install ruby1.9.1-dev

or to install generic ruby version, use (as per @lamplightdev comment):

sudo apt-get install ruby-dev

should fix it.

Try locate mkmf to see if the file is actually there.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

“Failed to configure a DataSource” error. First, we fixed the issue by defining the data source. Next, we discussed how to work around the issue without configuring the data source at all.

https://www.baeldung.com/spring-boot-failed-to-configure-data-source

Windows path in Python

Yes, \ in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a, which is collapsed into one character that is ASCII Bell:

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

Other common escape sequences include \t (tab), \n (line feed), \r (carriage return):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python's escape sequences is here.

There are a variety of ways to deal with that:

  1. Python will not process escape sequences in string literals prefixed with r or R:

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join ...

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. ... or the newer pathlib module

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

Execute PHP script in cron job

You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser (man runuser). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.

I provide a detailed answer how to use cron in this stackoverflow post.

How to write a cron that will run a script every day at midnight?

Spark read file from S3 using sc.textFile ("s3n://...)

You probably have to use s3a:/ scheme instead of s3:/ or s3n:/ However, it is not working out of the box (for me) for the spark shell. I see the following stacktrace:

java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found
        at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2074)
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2578)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:91)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2630)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2612)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:370)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:296)
        at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:256)
        at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228)
        at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313)
        at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:207)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:1781)
        at org.apache.spark.rdd.RDD.count(RDD.scala:1099)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:24)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:29)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:31)
        at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:33)
        at $iwC$$iwC$$iwC$$iwC.<init>(<console>:35)
        at $iwC$$iwC$$iwC.<init>(<console>:37)
        at $iwC$$iwC.<init>(<console>:39)
        at $iwC.<init>(<console>:41)
        at <init>(<console>:43)
        at .<init>(<console>:47)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
        at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1338)
        at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:840)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:871)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:819)
        at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:857)
        at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:814)
        at org.apache.spark.repl.SparkILoop.processLine$1(SparkILoop.scala:657)
        at org.apache.spark.repl.SparkILoop.innerLoop$1(SparkILoop.scala:665)
        at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$loop(SparkILoop.scala:670)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply$mcZ$sp(SparkILoop.scala:997)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
        at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$process(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:1059)
        at org.apache.spark.repl.Main$.main(Main.scala:31)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:665)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:170)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:193)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:112)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found
        at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:1980)
        at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2072)
        ... 68 more

What I think - you have to manually add the hadoop-aws dependency manually http://search.maven.org/#artifactdetails|org.apache.hadoop|hadoop-aws|2.7.1|jar But I have no idea how to add it to spark-shell properly.

SQLite equivalent to ISNULL(), NVL(), IFNULL() or COALESCE()

Use IS NULL or IS NOT NULL in WHERE-clause instead of ISNULL() method:

SELECT myField1
FROM myTable1
WHERE myField1 IS NOT NULL

How to get the first element of the List or Set?

You can use the get(index) method to access an element from a List.

Sets, by definition, simply contain elements and have no particular order. Therefore, there is no "first" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method.

Cannot lower case button text in android studio

In your .xml file within Button add this line--

android:textAllCaps="false"

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

Please to solve this problem we just have set installed JDK path in

standalone.conf

file which under the bin folder of JBoss\Wildfly Server. To solve this we do the following steps:

  1. Open the standlone.conf file which under JBoss_or_wildfly\bin folder
  2. Within this file find for #JAVA_HOME text.
  3. Remove the # character and set your installed JDK path as JAVA_HOME="C:\Program Files\Java\jdk1.8.0_65" Hope this will solve your problem Thanks

add a temporary column with a value

select field1, field2, 'example' as TempField
from table1

This should work across different SQL implementations.

Create empty file using python

Of course there IS a way to create files without opening. It's as easy as calling os.mknod("newfile.txt"). The only drawback is that this call requires root privileges on OSX.

XSL if: test with multiple test conditions

Try to use the empty() function:

<xsl:if test="empty(node/ABC/node()) and empty(node/DEF/node())">
    <xsl:text>This should work</xsl:text>
</xsl:if>

This identifies ABC and DEF as empty in the sense that they do not have any child nodes (no elements, no text nodes, no processing instructions, no comments).

But, as pointed out by @Ian, your elements might not be empty really or that might not be your actual problem - you did not show what your input XML looks like.

Another cause of error could be your relative position in the tree. This way of testing conditions only works if the surrounding template matches the parent element of node or if you iterate over the parent element of node.

How to multi-line "Replace in files..." in Notepad++

This is a subjective opinion, but I think a text editor shouldn't do everything and the kitchen sink. I prefer lightweight flexible and powerful (in their specialized fields) editors. Although being mostly a Windows user, I like the Unix philosophy of having lot of specialized tools that you can pipe together (like the UnxUtils) rather than a monster doing everything, but not necessarily as you would like it!

Find in files is on the border of these extra features, but useful when you can double-click on a found line to open the file at the right line. Note that initially, in SciTE it was just a Tools call to grep or equivalent!
FTP is very close to off topic, although it can be seen as an extended open/save dialog.
Replace in files is too much IMO: it is dangerous (you can mess lot of files at once) if you have no preview, etc. I would rather use a specialized tool I chose, perhaps among those in Multi line search and replace tool.

To answer the question, looking at N++, I see a Run menu where you can launch any tool, with assignment of a name and shortcut key. I see also Plugins > NppExec, which seems able to launch stuff like sed (not tried it).

async await return Task

You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:

public async Task<object> MethodName()
{
    return await Task.FromResult<object>(null);
}

Here is an example with no return value:

public async Task MethodName()
{
    await Task.CompletedTask;
}

Read these:

TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx

Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

How to insert text with single quotation sql server 2005

INSERT INTO Table1 (Column1) VALUES ('John''s')

Or you can use a stored procedure and pass the parameter as -

usp_Proc1 @Column1 = 'John''s'

If you are using an INSERT query and not a stored procedure, you'll have to escape the quote with two quotes, else its OK if you don't do it.

How to Set OnClick attribute with value containing function in ie8?

You also can use:

element.addEventListener("click", function(){
    // call execute function here...
}, false);

Using fonts with Rails asset pipeline

Here my approach to using fonts in asset pipeline:

1) Put all your font file under app/assets/fonts/, actually you are not restricted to put it under fonts folder name. You can put any subfolder name you like. E.g. app/assets/abc or app/assets/anotherfonts. But i highly recommend you put it under app/assets/fonts/ for better folder structure.

2) From your sass file, using the sass helper font-path to request your font assets like this

@font-face {
    font-family: 'FontAwesome';
    src: url(font-path('fontawesome-webfont.eot') + '?v=4.4.0');
    src: url(font-path('fontawesome-webfont.eot') + '?#iefix&v=4.4.0') format('embedded-opentype'),
         url(font-path('fontawesome-webfont.woff2') + '?v=4.4.0') format('woff2'),
         url(font-path('fontawesome-webfont.woff') + '?v=4.4.0') format('woff'),
         url(font-path('fontawesome-webfont.ttf') + '?v=4.4.0') format('truetype'),
         url(font-path('fontawesome-webfont.svg') + '?v=4.4.0#fontawesomeregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

3) Run bundle exec rake assets:precompile from your local machine and see your application.css result. You should see something like this:

@font-face {
    font-family: 'FontAwesome';
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?v=4.4.0");
    src: url("/assets/fontawesome-webfont-d4f5a99224154f2a808e42a441ddc9248ffe78b7a4083684ce159270b30b912a.eot" "?#iefix&v=4.4.0") format("embedded-opentype"), url("/assets/fontawesome-webfont-3c4a1bb7ce3234407184f0d80cc4dec075e4ad616b44dcc5778e1cfb1bc24019.woff2" "?v=4.4.0") format("woff2"), url("/assets/fontawesome-webfont-a7c7e4930090e038a280fd61d88f0dc03dad4aeaedbd8c9be3dd9aa4c3b6f8d1.woff" "?v=4.4.0") format("woff"), url("/assets/fontawesome-webfont-1b7f3de49d68b01f415574ebb82e6110a1d09cda2071ad8451bdb5124131a292.ttf" "?v=4.4.0") format("truetype"), url("/assets/fontawesome-webfont-7414288c272f6cc10304aa18e89bf24fb30f40afd644623f425c2c3d71fbe06a.svg" "?v=4.4.0#fontawesomeregular") format("svg");
    font-weight: normal;
    font-style: normal;
}

If you want to know more how asset pipeline work, you can visit the following simple guide: https://designcode.commandrun.com/rails-asset-pipeline-simple-guide-830e2e666f6c#.6lejlayk2

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

You simply need to install Crystal Report Report Run Time downloads on Deployment Server. If problem still appears, then place check asp_client folder in your project main folder.

How to add favicon.ico in ASP.NET site

/favicon.ico

might do the trick
I have tried this on my sample website

<link rel="shortcut icon" type="image/x-icon" href="~/ows.ico" />

Try this one in your site put the link in MasterPage,It works :)

<link rel="shortcut icon" type="image/x-icon" href="~/favicon.ico" />


I have tested in ,
FireFox.
enter image description here
Chrome.
enter image description here
Opera.
enter image description here

Some troubleshoots:
1. Check if your favicon is accessible (correct url) ,goto view source and click on the favicon link
2. Full refresh your browser by Ctrl+F5 every time you make changes.
3. Try searching from SO you may find your related problem here.


Some Links to help you out:
Serving favicon.ico in ASP.NET MVC
Favicon Not Showing
Why is favicon not visible

How to migrate GIT repository from one server to a new one

You can use the following command :

git remote set-url --push origin new_repo_url

Example from http://gitref.org/remotes/

$ git remote -v
github  [email protected]:schacon/hw.git (fetch)
github  [email protected]:schacon/hw.git (push)
origin  git://github.com/github/git-reference.git (fetch)
origin  git://github.com/github/git-reference.git (push)
$ git remote set-url --push origin git://github.com/pjhyett/hw.git
$ git remote -v
github  [email protected]:schacon/hw.git (fetch)
github  [email protected]:schacon/hw.git (push)
origin  git://github.com/github/git-reference.git (fetch)
origin  git://github.com/pjhyett/hw.git (push)

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306 - you provided 3360. The 3306 is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect() is the port, which is where it should be specified.

You could just remove the port specification altogether, as you're using the default port, making it

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

References

Make a link use POST instead of GET

You don't need JavaScript for this. Just wanted to make that clear, since as of the time this answer was posted, all of the answers to this question involve the use of JavaScript in some way or another.

You can do this rather easily with pure HTML and CSS by creating a form with hidden fields containing the data you want to submit, then styling the submit button of the form to look like a link.

For example:

_x000D_
_x000D_
.inline {_x000D_
  display: inline;_x000D_
}_x000D_
_x000D_
.link-button {_x000D_
  background: none;_x000D_
  border: none;_x000D_
  color: blue;_x000D_
  text-decoration: underline;_x000D_
  cursor: pointer;_x000D_
  font-size: 1em;_x000D_
  font-family: serif;_x000D_
}_x000D_
.link-button:focus {_x000D_
  outline: none;_x000D_
}_x000D_
.link-button:active {_x000D_
  color:red;_x000D_
}
_x000D_
<a href="some_page">This is a regular link</a>_x000D_
_x000D_
<form method="post" action="some_page" class="inline">_x000D_
  <input type="hidden" name="extra_submit_param" value="extra_submit_value">_x000D_
  <button type="submit" name="submit_param" value="submit_value" class="link-button">_x000D_
    This is a link that sends a POST request_x000D_
  </button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The exact CSS you use may vary depending on how regular links on your site are styled.

How to handle the modal closing event in Twitter Bootstrap?

There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden". As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:

$( '#modal' )
   .on('hide', function() {
       console.log('hide');
   })
   .on('hidden', function(){
       console.log('hidden');
   })
   .on('show', function() {
       console.log('show');
   })
   .on('shown', function(){
      console.log('shown' )
   });

And, as for your question, I think you should listen to the 'hide' event of your modal.

NSDate get year/month/day

Swift

Easier way to get any elements of date as an optional String.

extension Date {

  // Year 
  var currentYear: String? {
    return getDateComponent(dateFormat: "yy")
    //return getDateComponent(dateFormat: "yyyy")
  }

  // Month 
  var currentMonth: String? {
    return getDateComponent(dateFormat: "M")
    //return getDateComponent(dateFormat: "MM")
    //return getDateComponent(dateFormat: "MMM")
    //return getDateComponent(dateFormat: "MMMM")
  }


  // Day
  var currentDay: String? {
    return getDateComponent(dateFormat: "dd")
    //return getDateComponent(dateFormat: "d")
  }


  func getDateComponent(dateFormat: String) -> String? {
    let format = DateFormatter()
    format.dateFormat = dateFormat
    return format.string(from: self)
  }


}

let today = Date()
print("Current Year - \(today.currentYear)")  // result Current Year - Optional("2017")
print("Current Month - \(today.currentMonth)")  // result Current Month - Optional("7")
print("Current Day - \(today.currentDay)")  // result Current Day - Optional("10")

Best way to convert text files between character sets?

Use this Python script: https://github.com/goerz/convert_encoding.py Works on any platform. Requires Python 2.7.

Delete all files of specific type (extension) recursively down a directory using a batch file

I wrote a batch script a while ago that allows you to pick a file extension to delete. The script will look in the folder it is in and all subfolders for any file with that extension and delete it.

@ECHO OFF
CLS

SET found=0
ECHO Enter the file extension you want to delete...
SET /p ext="> "

IF EXIST *.%ext% (           rem Check if there are any in the current folder :)
  DEL *.%ext%
  SET found=1
)
FOR /D /R %%G IN ("*") DO (  rem Iterate through all subfolders
  IF EXIST %%G CD %%G
  IF EXIST *.%ext% (
    DEL *.%ext%
    SET found=1
  )
)

IF %found%==1 (
  ECHO.
  ECHO Deleted all .%ext% files.
  ECHO.
) ELSE (
  ECHO.
  ECHO There were no .%ext% files.
  ECHO Nothing has been deleted.
  ECHO.
)

PAUSE
EXIT

Hope this comes in useful to anyone who wants it :)

How to detect idle time in JavaScript elegantly?

I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:

const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();

It does not depend on jQuery, though you might need to run it through Babel to support older browsers.

https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096

I might release it as an npm package once I get some feedback.

Remove the string on the beginning of an URL

Depends on what you need, you have a couple of choices, you can do:

// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");

// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);

// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");

Insert some string into given string at given index in Python

There are several ways to do this:

One way is to use slicing:

>>> a="line=Name Age Group Class Profession"
>>> b=a.split()
>>> b[2:2]=[b[2]]*3
>>> b
['line=Name', 'Age', 'Group', 'Group', 'Group', 'Group', 'Class', 'Profession']
>>> a=" ".join(b)
>>> a
'line=Name Age Group Group Group Group Class Profession'

Another would be to use regular expressions:

>>> import re
>>> a=re.sub(r"(\S+\s+\S+\s+)(\S+\s+)(.*)", r"\1\2\2\2\2\3", a)
>>> a
'line=Name Age Group Group Group Group Class Profession'

How to open spss data files in excel?

You can use online converter, developed by me at N'counter.

This is the easiest way to open SPSS file in Excel.

1) You just have to upload your file to SPSS coN'verter at https://secure.ncounter.de/SpssConverter

2) Select some options

3) And your converted Excel file will be downloaded

No information about your file contents is retained on our server. The file travels to our server, is converted in-memory, and is immediately discarded: We don't peer into your data at any time!

Is there a way to get version from package.json in nodejs code?

You can use the project-version package.

$ npm install --save project-version

Then

const version = require('project-version');

console.log(version);
//=>  '1.0.0'

It uses process.env.npm_package_version but fallback on the version written in the package.json in case the env var is missing for some reason.

#ifdef replacement in the Swift language

isDebug Constant Based on Active Compilation Conditions

Another, perhaps simpler, solution that still results in a boolean that you can pass into functions without peppering #if conditionals throughout your codebase is to define DEBUG as one of your project build target's Active Compilation Conditions and include the following (I define it as a global constant):

#if DEBUG
    let isDebug = true
#else
    let isDebug = false
#endif

isDebug Constant Based on Compiler Optimization Settings

This concept builds on kennytm's answer

The main advantage when comparing against kennytm's, is that this does not rely on private or undocumented methods.

In Swift 4:

let isDebug: Bool = {
    var isDebug = false
    // function with a side effect and Bool return value that we can pass into assert()
    func set(debug: Bool) -> Bool {
        isDebug = debug
        return isDebug
    }
    // assert:
    // "Condition is only evaluated in playgrounds and -Onone builds."
    // so isDebug is never changed to true in Release builds
    assert(set(debug: true))
    return isDebug
}()

Compared with preprocessor macros and kennytm's answer,

  • ? You don't need to define a custom -D DEBUG flag to use it
  • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
  • ? Documented, which means the function will follow normal API release/deprecation patterns.

  • ? Using in if/else will not generate a "Will never be executed" warning.

What's the difference between ASCII and Unicode?

Storage

Given numbers are only for storing 1 character

  • ASCII ? 27 bits (1 byte)
  • Extended ASCII ? 28 bits (1 byte)
  • UTF-8 ? minimum 28, maximum 232 bits (min 1, max 4 bytes)
  • UTF-16 ? minimum 216, maximum 232 bits (min 2, max 4 bytes)
  • UTF-32 ? 232 bits (4 bytes)

Usage (as of Feb 2020)

Percentages of websites using various character encodings

What is the maximum length of a Push Notification alert text?

EDIT:

Updating the answer with latest information

The maximum size allowed for a notification payload depends on which provider API you employ.

When using the legacy binary interface, maximum payload size is 2KB (2048 bytes).

When using the HTTP/2 provider API, maximum payload size is 4KB (4096 bytes). For Voice over Internet Protocol (VoIP) notifications, the maximum size is 5KB (5120 bytes)

OLD ANSWER: According to the apple doc the payload for iOS 8 is 2 kilobytes (2048 bytes) and 256 bytes for iOS 7 and prior. (removed the link as it was an old doc and it's broken now)

So if you just send text you have 2028 (iOS 8+) or 236 (iOS 7-) characters available.

The Notification Payload

Each remote notification includes a payload. The payload contains information about how the system should alert the user as well as any custom data you provide. In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)

But I've tested and you can send 2 kilobytes to iOS 7 devices too, even in production configurations

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

JavaScript array to CSV

ES6:

let csv = test_array.map(row=>row.join(',')).join('\n') 
//test_array being your 2D array

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

Using number_format method in Laravel

If you are using Eloquent, in your model put:

public function getPriceAttribute($price)
{
    return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));
}

Where getPriceAttribute is your field on database. getSomethingAttribute.

Sorting JSON by values

Solution working with different types and with upper and lower cases.
For example, without the toLowerCase statement, "Goodyear" will come before "doe" with an ascending sort. Run the code snippet at the bottom of my answer to view the different behaviors.

JSON DATA:

var people = [
{
    "f_name" : "john",
    "l_name" : "doe", // lower case
    "sequence": 0 // int
},
{
    "f_name" : "michael",
    "l_name" : "Goodyear", // upper case
    "sequence" : 1 // int
}];

JSON Sort Function:

function sortJson(element, prop, propType, asc) {
  switch (propType) {
    case "int":
      element = element.sort(function (a, b) {
        if (asc) {
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);
        } else {
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);
        }
      });
      break;
    default:
      element = element.sort(function (a, b) {
        if (asc) {
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);
        } else {
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);
        }
      });
  }
}

Usage:

sortJson(people , "l_name", "string", true);
sortJson(people , "sequence", "int", true);

_x000D_
_x000D_
var people = [{_x000D_
  "f_name": "john",_x000D_
  "l_name": "doe",_x000D_
  "sequence": 0_x000D_
}, {_x000D_
  "f_name": "michael",_x000D_
  "l_name": "Goodyear",_x000D_
  "sequence": 1_x000D_
}, {_x000D_
  "f_name": "bill",_x000D_
  "l_name": "Johnson",_x000D_
  "sequence": 4_x000D_
}, {_x000D_
  "f_name": "will",_x000D_
  "l_name": "malone",_x000D_
  "sequence": 2_x000D_
}, {_x000D_
  "f_name": "tim",_x000D_
  "l_name": "Allen",_x000D_
  "sequence": 3_x000D_
}];_x000D_
_x000D_
function sortJsonLcase(element, prop, asc) {_x000D_
  element = element.sort(function(a, b) {_x000D_
    if (asc) {_x000D_
      return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);_x000D_
    } else {_x000D_
      return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
function sortJson(element, prop, propType, asc) {_x000D_
  switch (propType) {_x000D_
    case "int":_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);_x000D_
        } else {_x000D_
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
      break;_x000D_
    default:_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);_x000D_
        } else {_x000D_
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
  }_x000D_
}_x000D_
_x000D_
function sortJsonString() {_x000D_
  sortJson(people, 'l_name', 'string', $("#chkAscString").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonInt() {_x000D_
  sortJson(people, 'sequence', 'int', $("#chkAscInt").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonUL() {_x000D_
  sortJsonLcase(people, 'l_name', $('#chkAsc').prop('checked'));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function display() {_x000D_
  $("#data").empty();_x000D_
  $(people).each(function() {_x000D_
    $("#data").append("<div class='people'>" + this.l_name + "</div><div class='people'>" + this.f_name + "</div><div class='people'>" + this.sequence + "</div><br />");_x000D_
  });_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial;_x000D_
}_x000D_
.people {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
}_x000D_
.buttons {_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  float: left;_x000D_
  width: 20%;_x000D_
}_x000D_
ul {_x000D_
  margin: 5px 0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">with</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonString(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscString" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(255, 214, 215, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">without</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonUL(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAsc" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array:_x000D_
  <ul>_x000D_
    <li>Type: int</li>_x000D_
    <li>Property: sequence</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonInt(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscInt" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<br />_x000D_
<br />_x000D_
<div id="data" style="float: left; border: 1px solid black; width: 60%; margin: 5px;">Data</div>
_x000D_
_x000D_
_x000D_

Python: Find index of minimum item in list of floats

I would use:

val, idx = min((val, idx) for (idx, val) in enumerate(my_list))

Then val will be the minimum value and idx will be its index.

Maven plugins can not be found in IntelliJ

Uncheck the "Work offline" checkbox in Maven settings.

Dynamically generating a QR code with PHP

It's worth adding that, in addition to the QR codes library posted by @abaumg, Google provides a QR Codes API QR Codes APImany thanks to @Toukakoukan for the link update.

To use this , basically:

https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=http%3A%2F%2Fwww.google.com%2F&choe=UTF-8
  • 300x300 is the size of the QR image you want to generate,
  • the chl is the url-encoded string you want to change into a QR code, and
  • the choe is the (optional) encoding.

The link, above, gives more detail, but to use it just have the src of an image point to the manipulated value, like so:

<img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=http%3A%2F%2Fwww.google.com%2F&choe=UTF-8" title="Link to Google.com" />

Demo:

Search text in stored procedure in SQL Server

It might help you!

SELECT DISTINCT 
      A.NAME AS OBJECT_NAME,
      A.TYPE_DESC
      FROM SYS.SQL_MODULES M 
      INNER JOIN SYS.OBJECTS A ON M.OBJECT_ID = A.OBJECT_ID
      WHERE M.DEFINITION LIKE '%['+@SEARCH_TEXT+']%'
      ORDER BY TYPE_DESC

Difference between web server, web container and application server

Web container also known as a Servlet container is the component of a web server that interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

grep exclude multiple strings

tail -f admin.log|grep -v -E '(Nopaging the limit is|keyword to remove is)'

jquery change button color onclick

You have to include the jquery framework in your document head from a cdn for example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

Then you have to include a own script for example:

(function( $ ) {

  $(document).ready(function(){
      $('input').click(function() {
          $(this).css('background-color', 'green');
      }
  });


  $(window).load(function() { 
  });

})( jQuery );

This part is a mapping of the $ to jQuery, so actually it is jQuery('selector').function();

(function( $ ) {

})( jQuery );

Here you can find die api of jquery where all functions are listed with examples and explanation: http://api.jquery.com/

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

Variables not showing while debugging in Eclipse

Resetting the perspective wasn't quite enough for me, I had to first delete the "Variables" tab and then reset the perspective (which reinstated the Variables tab in a working state). One other thing not mentioned above which might help others - when the variables tab is not working, the tab title is in italics (whatever that signifies). When it's working it goes back to normal font.

What is parsing in terms that a new programmer would understand?

I'd explain parsing as the process of turning some kind of data into another kind of data.

In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.

For example, turning

":Nick!User@Host PRIVMSG #channel :Hello!"

into (C)

struct irc_line {
    char *nick;
    char *user;
    char *host;
    char *command;
    char **arguments;
    char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }

Getting RSA private key from PEM BASE64 Encoded private key file

You've just published that private key, so now the whole world knows what it is. Hopefully that was just for testing.

EDIT: Others have noted that the openssl text header of the published key, -----BEGIN RSA PRIVATE KEY-----, indicates that it is PKCS#1. However, the actual Base64 contents of the key in question is PKCS#8. Evidently the OP copy and pasted the header and trailer of a PKCS#1 key onto the PKCS#8 key for some unknown reason. The sample code I've provided below works with PKCS#8 private keys.

Here is some code that will create the private key from that data. You'll have to replace the Base64 decoding with your IBM Base64 decoder.

public class RSAToy {

    private static final String BEGIN_RSA_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\n"
            + "MIIEuwIBADAN ...skipped the rest\n"
         // + ...   
         // + ... skipped the rest
         // + ...   
            + "-----END RSA PRIVATE KEY-----";

    public static void main(String[] args) throws Exception {

        // Remove the first and last lines

        String privKeyPEM = BEGIN_RSA_PRIVATE_KEY.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
        privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");
        System.out.println(privKeyPEM);

        // Base64 decode the data

        byte [] encoded = Base64.decode(privKeyPEM);

        // PKCS8 decode the encoded RSA private key

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(keySpec);

        // Display the results

        System.out.println(privKey);
    }
}

Xcode is not currently available from the Software Update server

The command

xcode-select --install

proposes 3 options: Get Xcode; Not Now; Install.

When I choose to get full Xcode the command finished successfully. It took a while, but this way I was able to complete all macports migration instructions.

How can I print the contents of an array horizontally?

Using Console.Write only works if the thread is the only thread writing to the Console, otherwise your output may be interspersed with other output that may or may not insert newlines, as well as other undesired characters. To ensure your array is printed intact, use Console.WriteLine to write one string. Most any array of objects can be printed horizontally (depending on the type's ToString() method) using the non-generic Join available before .NET 4.0:

        int[] numbers = new int[100];
        for(int i= 0; i < 100; i++)
        {
            numbers[i] = i;
        }

        //For clarity
        IEnumerable strings = numbers.Select<int, string>(j=>j.ToString());
        string[] stringArray = strings.ToArray<string>();
        string output = string.Join(", ", stringArray);
        Console.WriteLine(output);

        //OR 

        //For brevity
        Console.WriteLine(string.Join(", ", numbers.Select<int, string>(j => j.ToString()).ToArray<string>()));

Change the background color of a pop-up dialog

If you just want a light theme and aren't particular about the specific color, then you can pass a theme id to the AlertDialog.Builder constructor.

AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)...

or

AlertDialog.Builder(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)...

Find everything between two XML tags with RegEx

In our case, we receive an XML as a String and need to get rid of the values that have some "special" characters, like &<> etc. Basically someone can provide an XML to us in this form:

<notes>
  <note>
     <to>jenice & carl </to>
     <from>your neighbor <; </from>
  </note>
</notes>

So I need to find in that String the values jenice & carl and your neighbor <; and properly escape & and < (otherwise this is an invalid xml if you later pass it to an engine that shall rename unnamed).

Doing this with regex is a rather dumb idea to begin with, but it's cheap and easy. So the brave ones that would like to do the same thing I did, here you go:

    String xml = ...
    Pattern p = Pattern.compile("<(.+)>(?!\\R<)(.+)</(\\1)>");
    Matcher m = p.matcher(xml);
    String result = m.replaceAll(mr -> {
        if (mr.group(2).contains("&")) {
            return "<" + m.group(1) + ">" + m.group(2) + "+ some change" + "</" + m.group(3) + ">";
        }
        return "<" + m.group(1) + ">" + mr.group(2) + "</" + m.group(3) + ">";
    });

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

How to loop through all elements of a form jQuery

What happens, if you do this way:-

$('#new_user_form input, #new_user_form select').each(function(key, value) {

Refer LIVE DEMO

What's the best way to iterate an Android Cursor?

import java.util.Iterator;
import android.database.Cursor;

public class IterableCursor implements Iterable<Cursor>, Iterator<Cursor> {
    Cursor cursor;
    int toVisit;
    public IterableCursor(Cursor cursor) {
        this.cursor = cursor;
        toVisit = cursor.getCount();
    }
    public Iterator<Cursor> iterator() {
        cursor.moveToPosition(-1);
        return this;
    }
    public boolean hasNext() {
        return toVisit>0;
    }
    public Cursor next() {
    //  if (!hasNext()) {
    //      throw new NoSuchElementException();
    //  }
        cursor.moveToNext();
        toVisit--;
        return cursor;
    }
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

Example code:

static void listAllPhones(Context context) {
    Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    for (Cursor phone : new IterableCursor(phones)) {
        String name = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        Log.d("name=" + name + " phoneNumber=" + phoneNumber);
    }
    phones.close();
}

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

The time complexity of ArrayList.clear() is O(n) and of removeAll is O(n^2).

So yes, ArrayList.clear is much faster.

How to check command line parameter in ".bat" file?

You are comparing strings. If an arguments are omitted, %1 expands to a blank so the commands become IF =="-b" GOTO SPECIFIC for example (which is a syntax error). Wrap your strings in quotes (or square brackets).

REM this is ok
IF [%1]==[/?] GOTO BLANK

REM I'd recommend using quotes exclusively
IF "%1"=="-b" GOTO SPECIFIC

IF NOT "%1"=="-b" GOTO UNKNOWN

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In a conda environment, this is what solved my problem (I was missing cudart64-100.dll:

  1. Downloaded it from dll-files.com/CUDART64_100.DLL

  2. Put it in my conda environment at C:\Users\<user>\Anaconda3\envs\<env name>\Library\bin

That's all it took! You can double check if it's working:

import tensorflow as tf
tf.config.experimental.list_physical_devices('GPU')

Can a html button perform a POST request?

You need to give the button a name and a value.

No control can be submitted without a name, and the content of a button element is the label, not the value.

<form action="" method="post">
    <button name="foo" value="upvote">Upvote</button>
</form>

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

You can also add a .pth file containing the desired directory in either your c:\PythonX.X folder, or your \site-packages folder, which tends to be my preferred method when I'm developing a Python package.

See here for more information.

A JOIN With Additional Conditions Using Query Builder or Eloquent

The sql query sample like this

LEFT JOIN bookings  
    ON rooms.id = bookings.room_type_id
    AND (bookings.arrival = ?
        OR bookings.departure = ?)

Laravel join with multiple conditions

->leftJoin('bookings', function($join) use ($param1, $param2) {
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(function($query) use ($param1, $param2) {
        $query->on('bookings.arrival', '=', $param1);
        $query->orOn('departure', '=',$param2);
    });
})

Decreasing for loops in Python impossible?

This is very late, but I just wanted to add that there is a more elegant way: using reversed

for i in reversed(range(10)):
    print i

gives:

4
3
2
1
0

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

I was getting this error while using JQuery 1.10 and JQuery UI 1.8. I was able to resolve this error by updating to the latest JQuery UI 1.11.4.

Steps to update JQuery UI from Visual Studio:

  • Navigate to Project or Solution
  • Right click: "Manage NuGet Packages"
  • On the left, click on "Installed Packages" tab
  • Look for "JQuery UI (Combined library)" and click Update
  • If found, Select it and click Update
  • If not found, find it in "Online > nuget.org" tab on the left and click install. If the old version of Jquery UI version is still existing, it can be deleted from the project

intl extension: installing php_intl.dll

There is a better way of doing this.

I was having same kind of problem with ldap, intl, curl php extensions. I've solved those issues by the following ways:

At first you've to check whether these extensions have been enabled in the php.ini file by removing semicolon (;) in front of the following lines:

;extension=php_intl.dll
;extension=php_ldap.dll
;extension=php_curl.dll

Now you can directly load those necessary dll files (ie libeay32, libssh2, ssleay32, icu**.dll ) from your httpd.conf (apache configuratio file) file. You don't have to do any other things like copying them to the apache's bin directory or php's ext directory. Just add them directly in you apache's httpd.conf file.

Please note that the followng example is for php version 5.5.x.

LoadFile  "C:/php/icudt51.dll"
LoadFile  "C:/php/icuin51.dll"
LoadFile  "C:/php/icuio51.dll"
LoadFile  "C:/php/icule51.dll"
LoadFile  "C:/php/iculx51.dll"
LoadFile  "C:/php/icutest51.dll"
LoadFile  "C:/php/icutu51.dll"
LoadFile  "C:/php/icuuc51.dll"

LoadFile  "C:/php/libeay32.dll"
LoadFile  "C:/php/libssh2.dll"
LoadFile  "C:/php/ssleay32.dll"

That's it. Now, restart your apache or wamp and you're good to go.

How to reload current page?

Here is the simple one

if (this.router && this.router.url === '/') { or your current page url e.g '/home' 
    window.location.reload();
  } else {
    this.router.navigate([url]);
  }

How to write multiple conditions in Makefile.am with "else if"

I would accept ldav1s' answer if I were you, but I just want to point out that 'else if' can be written in terms of 'else's and 'if's in any language:

if HAVE_CLIENT
  libtest_LIBS = $(top_builddir)/libclient.la
else
  if HAVE_SERVER
    libtest_LIBS = $(top_builddir)/libserver.la
  else
    libtest_LIBS = 
  endif
endif

(The indentation is for clarity. Don't indent the lines, they won't work.)

Multiple conditions in WHILE loop

Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.

Use myChar != 'n' && myChar != 'N' instead

Converting .NET DateTime to JSON

http://stevenlevithan.com/assets/misc/date.format.js

var date = eval(data.Data.Entity.Slrq.replace(/\/Date\((\d )\)\//gi, "new Date($1)"));  
alert(date.format("yyyy-MM-dd HH:mm:ss"));  
alert(dateFormat(date, "yyyy-MM-dd HH:mm:ss"));  

Java difference between FileWriter and BufferedWriter

In unbuffered Input/Output(FileWriter, FileReader) read or write request is handled directly by the underlying OS. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/Unbuffered.gif

This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. To reduce this kind of overhead, the Java platform implements buffered I/O streams. The BufferedReader and BufferedWriter classes provide internal character buffers. Text that’s written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed. https://hajsoftutorial.com/java/wp-content/uploads/2018/04/bufferedoutput.gif

More https://hajsoftutorial.com/java-bufferedwriter/

SSL: CERTIFICATE_VERIFY_FAILED with Python3

In my case, I used the ssl module to "workaround" the certification like so:

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

Then to read your link content, you can use:

urllib.request.urlopen(urllink)

How to display default text "--Select Team --" in combo box on pageload in WPF?

HappyNomad's solution was very good and helped me eventually arrive at this slightly different solution.

<ComboBox x:Name="ComboBoxUploadProject" 
    Grid.Row="2"
    Width="200" 
    Height="23"                           
    Margin="64,0,0,0"
    ItemsSource="{Binding projectList}"
    SelectedValue ="{Binding projectSelect}" 
    DisplayMemberPath="projectName"
    SelectedValuePath="projectId"
    >
    <ComboBox.Template>
        <ControlTemplate TargetType="ComboBox">
            <Grid>
                <ComboBox x:Name="cb" 
                    DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" 
                    ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource TemplatedParent}}"
                    SelectedValue ="{Binding SelectedValue, RelativeSource={RelativeSource TemplatedParent}}" 
                    DisplayMemberPath="projectName"
                    SelectedValuePath="projectId"
                    />
                <TextBlock x:Name="tb" Text="Select Item..." Margin="3,3,0,0" IsHitTestVisible="False" Visibility="Hidden"/>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger SourceName="cb" Property="SelectedItem" Value="{x:Null}">
                    <Setter TargetName="tb" Property="Visibility" Value="Visible"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </ComboBox.Template>
</ComboBox>

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Find mouse position relative to element

Taken from this tutorial, with corrections made thanks to the top comment:

function getMousePos( canvas, evt ) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: Math.floor( ( evt.clientX - rect.left ) / ( rect.right - rect.left ) * canvas.width ),
        y: Math.floor( ( evt.clientY - rect.top ) / ( rect.bottom - rect.top ) * canvas.height )
    };
}

Use on a canvas as follows:

var canvas = document.getElementById( 'myCanvas' );
canvas.addEventListener( 'mousemove', function( evt ) {
    var mousePos = getMousePos( canvas, evt );
} );

When use ResponseEntity<T> and @RestController for Spring RESTful applications

A proper REST API should have below components in response

  1. Status Code
  2. Response Body
  3. Location to the resource which was altered(for example, if a resource was created, client would be interested to know the url of that location)

The main purpose of ResponseEntity was to provide the option 3, rest options could be achieved without ResponseEntity.

So if you want to provide the location of resource then using ResponseEntity would be better else it can be avoided.

Consider an example where a API is modified to provide all the options mentioned

// Step 1 - Without any options provided
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public @ResponseBody Spittle spittleById(@PathVariable long id) {
  return spittleRepository.findOne(id);
}

// Step 2- We need to handle exception scenarios, as step 1 only caters happy path.
@ExceptionHandler(SpittleNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Error spittleNotFound(SpittleNotFoundException e) {
  long spittleId = e.getSpittleId();
  return new Error(4, "Spittle [" + spittleId + "] not found");
}

// Step 3 - Now we will alter the service method, **if you want to provide location**
@RequestMapping(
    method=RequestMethod.POST
    consumes="application/json")
public ResponseEntity<Spittle> saveSpittle(
    @RequestBody Spittle spittle,
    UriComponentsBuilder ucb) {

  Spittle spittle = spittleRepository.save(spittle);
  HttpHeaders headers = new HttpHeaders();
  URI locationUri =
  ucb.path("/spittles/")
      .path(String.valueOf(spittle.getId()))
      .build()
      .toUri();
  headers.setLocation(locationUri);
  ResponseEntity<Spittle> responseEntity =
      new ResponseEntity<Spittle>(
          spittle, headers, HttpStatus.CREATED)
  return responseEntity;
}

// Step4 - If you are not interested to provide the url location, you can omit ResponseEntity and go with
@RequestMapping(
    method=RequestMethod.POST
    consumes="application/json")
@ResponseStatus(HttpStatus.CREATED)
public Spittle saveSpittle(@RequestBody Spittle spittle) {
  return spittleRepository.save(spittle);
}

How to find the date of a day of the week from a date using PHP?

I had to use a similar solution for Portuguese (Brazil):

<?php
$scheduled_day = '2018-07-28';
$days = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
$day = date('w',strtotime($scheduled_day));
$scheduled_day = date('d-m-Y', strtotime($scheduled_day))." ($days[$day])";
// provides 28-07-2018 (Sáb)

How to create a CPU spike with a bash command

I would split the thing in 2 scripts :

infinite_loop.bash :

#!/bin/bash
while [ 1 ] ; do
    # Force some computation even if it is useless to actually work the CPU
    echo $((13**99)) 1>/dev/null 2>&1
done

cpu_spike.bash :

#!/bin/bash
# Either use environment variables for NUM_CPU and DURATION, or define them here
for i in `seq ${NUM_CPU}` : do
    # Put an infinite loop on each CPU
    infinite_loop.bash &
done

# Wait DURATION seconds then stop the loops and quit
sleep ${DURATION}
killall infinite_loop.bash

Eclipse error: "The import XXX cannot be resolved"

I found the problem. It was the hibernate3.jar. I don't know why it was not well extracted from the .zip, maybe corrupt. A good way to check if jars are corrupt or not is navigating through their tree structure in "Project Explorer" in Eclipse: if you can't expand a jar node probably it's corrupt. I've seen that having corrupt packages it's frequent when you drag and drop them to the "Project Explorer". Maybe it's better to move and copy them in the OS environment! Thankyou all.

Difference between decimal, float and double in .NET?

The main difference between each of these is the precision.

float is a 32-bit number, double is a 64-bit number and decimal is a 128-bit number.

How to prepend a string to a column value in MySQL?

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

How do I calculate power-of in C#?

Math.Pow() returns double so nice would be to write like this:

double d = Math.Pow(100.00, 3.00);

MacOSX homebrew mysql root password

Use init file to start mysql to change the root password.

brew services stop mysql
pkill mysqld
echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'newRootPass';" > /tmp/mysql-init
$(brew --prefix mysql)/bin/mysqld --init-file=/tmp/mysql-init

Your root password is now changed. Make sure to shutdown server properly to save password change. In new terminal window execute

mysqladmin -u root -p shutdown

and enter your new pass.

Start your service and remove the init file

brew services start mysql
rm /tmp/mysql-init

Tested on mysql version 8.0.19

How do you calculate log base 2 in Java for integers?

you can use the identity

            log[a]x
 log[b]x = ---------
            log[a]b

so this would be applicable for log2.

            log[10]x
 log[2]x = ----------
            log[10]2

just plug this into the java Math log10 method....

http://mathforum.org/library/drmath/view/55565.html

How do I know the script file name in a Bash script?

# ------------- SCRIPT ------------- #

#!/bin/bash

echo
echo "# arguments called with ---->  ${@}     "
echo "# \$1 ---------------------->  $1       "
echo "# \$2 ---------------------->  $2       "
echo "# path to me --------------->  ${0}     "
echo "# parent path -------------->  ${0%/*}  "
echo "# my name ------------------>  ${0##*/} "
echo
exit

# ------------- CALLED ------------- #

# Notice on the next line, the first argument is called within double, 
# and single quotes, since it contains two words

$  /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"

# ------------- RESULTS ------------- #

# arguments called with --->  'hello there' 'william'
# $1 ---------------------->  'hello there'
# $2 ---------------------->  'william'
# path to me -------------->  /misc/shell_scripts/check_root/show_parms.sh
# parent path ------------->  /misc/shell_scripts/check_root
# my name ----------------->  show_parms.sh

# ------------- END ------------- #

How to check visibility of software keyboard in Android?

if (keyopen())
{
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);            
}

The above function is what I use to check if a Keyboard is visible. If it is, then I close it.

Below shows the two methods required.

First, define the workable Window height in onCreate.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//  add to onCreate method
    Rect rectgle= new Rect();
    Window window= getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
    sheight= rectgle.bottom;
//

} 

Then, add a boolean method that gets the Window height at that instance. If it does not match the original (assuming you are not changing it along the way...) then, the keyboard is open.

public boolean keyopen()
{
    Rect rectgle= new Rect();
    Window window= getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
    int curheight= rectgle.bottom;

    if (curheight!=sheight)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Frotz!

how to remove "," from a string in javascript

If you need a number greater than 999,999.00 you will have a problem.
These are only good for numbers less than 1 million, 1,000,000.
They only remove 1 or 2 commas.

Here the script that can remove up to 12 commas:

function uncomma(x) {
  var string1 = x;
  for (y = 0; y < 12; y++) {
    string1 = string1.replace(/\,/g, '');
  }
  return string1;
}

Modify that for loop if you need bigger numbers.

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

How do I style a <select> dropdown with only CSS?

<select> tags can be styled through CSS just like any other HTML element on an HTML page rendered in a browser. Below is an (overly simple) example that will position a select element on the page and render the text of the options in blue.

Example HTML file (selectExample.html):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <title>Select Styling</title>
  <link href="selectExample.css" rel="stylesheet">
</head>
<body>
<select id="styledSelect" class="blueText">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="cherry">Cherry</option>
</select>
</body>
</html>

Example CSS file (selectExample.css):

/* All select elements on page */
select {
  position: relative;
}

/* Style by class. Effects the text of the contained options. */
.blueText {
  color: #0000FF;
}

/* Style by id. Effects position of the select drop down. */
#styledSelect {
  left: 100px;
}

How to create dynamic href in react render function?

You can use ES6 backtick syntax too

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

Correct way to pass multiple values for same parameter name in GET request

I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple> and how it handles multiple values from this example at w3schools.

<form action="/action_page.php">
<select name="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

For PHP use:

<select name="cars[]" multiple>

Live example from above at w3schools.com

From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.

Hope this helps anyone looking for a more 'standard' way of handling this issue.

Test if a vector contains a given element

is.element() makes for more readable code, and is identical to %in%

v <- c('a','b','c','e')

is.element('b', v)
'b' %in% v
## both return TRUE

is.element('f', v)
'f' %in% v
## both return FALSE

subv <- c('a', 'f')
subv %in% v
## returns a vector TRUE FALSE
is.element(subv, v)
## returns a vector TRUE FALSE

How do I add button on each row in datatable?

Take a Look.

$(document).ready(function () {     
        $('#datatable').DataTable({
            columns: [
                { 'data': 'ID' },
                { 'data': 'AuthorName' },
                { 'data': 'TotalBook' },
                { 'data': 'DateofBirth' },
                { 'data': 'OccupationEN' },   
                { 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
            ],            
            bServerSide: true,
            sAjaxSource: 'EmployeeDataHandler.ashx'           
        });       
    });

Better way to convert an int to a boolean

int i = 0;
bool b = Convert.ToBoolean(i);

What's the difference between identifying and non-identifying relationships?

An identifying relationship is between two strong entities. A non-identifying relationship may not always be a relationship between a strong entity and a weak entity. There may exist a situation where a child itself has a primary key but existence of its entity may depend on its parent entity.

For example : a relationship between a seller and a book where a book is being sold by a seller may exist where seller may have its own primary key but its entity is created only when a book is being sold

Reference based on Bill Karwin

Set environment variables from file of key/value pairs

First, create an environment file that will have all the key-value pair of the environments like below and named it whatever you like in my case its env_var.env

MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"

Then create a script that will export all the environment variables for the python environment like below and name it like export_env.sh

#!/usr/bin/env bash

ENV_FILE="$1"
CMD=${@:2}

set -o allexport
source $ENV_FILE
set +o allexport

$CMD

This script will take the first argument as the environment file then export all the environment variable in that file and then run the command after that.

USAGE:

./export_env.sh env_var.env python app.py

Implementing Singleton with an Enum (in Java)

In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:

Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type. Recommended approach is implement Singletons by simply make an enum type with one element:

// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.

While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Oracle date difference to get number of years

For Oracle SQL Developer I was able to calculate the difference in years using the below line of SQL. This was to get Years that were within 0 to 10 years difference. You can do a case like shown in some of the other responses to handle your ifs as well. Happy Coding!

TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) > 0 and TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) < 10

How can I run MongoDB as a Windows service?

Unlike other answers this will ..

START THE SERVICE AUTOMATICALLY ON SYSTEM REBOOT / RESTART

MongoDB Install

Windows

(1) Install MongoDB

(2) Add bin to path

(3) Create c:\data\db

(4) Create c:\data\log

(5) Create c:\data\mongod.cfg with contents ..

systemLog:
    destination: file
    path: c:\data\log\mongod.log
storage:
    dbPath: c:\data\db

(6) To create service that will auto start on reboot .. RUN AS ADMIN ..

sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe\" --service --config=\"C:\data\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"

(7) Start the service .. RUN AS ADMIN ..

net start MongoDB

IMPORTANT: Even if this says 'The MongoDB service was started successfully' it can fail

To double check open Control Panel > Services, ensure the status of the MongoDB service is 'Running'

If not, check your log file at C:\data\log\mongod.log for the reason for failure and fix it

(Do not start MongoDB via Control Panel > Services, use .. net start MongoDB)

(8) Finally, restart your machine with MongoDB running and it will still be running on restart

If you ever want to kill it ..

net stop MongoDB

sc.exe delete MongoDB

Obtain smallest value from array in Javascript?

I think I have an easy-to-understand solution for this, using only the basics of javaScript.

function myFunction() {
            var i = 0;
            var smallestNumber = justPrices[0];
            for(i = 0; i < justPrices.length; i++) {
                if(justPrices[i] < smallestNumber) {
                    smallestNumber = justPrices[i];
                }
            }
            return smallestNumber;
        }

The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.

Create, read, and erase cookies with jQuery

Use JavaScript Cookie plugin

Set a cookie

Cookies.set("example", "foo"); // Sample 1
Cookies.set("example", "foo", { expires: 7 }); // Sample 2
Cookies.set("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( Cookies.get("example") );

Delete the cookie

Cookies.remove("example");
Cookies.remove('example', { path: '/admin' }) // Must specify path if used when setting.

Catch checked change event of a checkbox

In my experience, I've had to leverage the event's currentTarget:

$("#dingus").click( function (event) {
   if ($(event.currentTarget).is(':checked')) {
     //checkbox is checked
   }
});

Count number of 1's in binary representation

I came here having a great belief that I know beautiful solution for this problem. Code in C:

    short numberOfOnes(unsigned int d) {
        short count = 0;

        for (; (d != 0); d &= (d - 1))
            ++count;

        return count;
    }

But after I've taken a little research on this topic (read other answers:)) I found 5 more efficient algorithms. Love SO!

There is even a CPU instruction designed specifically for this task: popcnt. (mentioned in this answer)

Description and benchmarking of many algorithms you can find here.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

how to check the jdk version used to compile a .class file

You can try jclasslib:

https://github.com/ingokegel/jclasslib

It's nice that it can associate itself with *.class extension.

No connection could be made because the target machine actively refused it 127.0.0.1

I had a similar issue, trying to run a WCF-based HttpSelfHostServer in Debug under my VisualStudio 2013. I tried every possible direction (turn off firewall, disabling IIS completely to eliminate the possibility localhost port is taken by some other service, etc.).

Eventually, what "did the trick" (solved the problem) was re-running VisualStudio 2013 as Administrator.

Amazing.

Disabled form inputs do not appear in the request

I find this works easier. readonly the input field, then style it so the end user knows it's read only. inputs placed here (from AJAX for example) can still submit, without extra code.

<input readonly style="color: Grey; opacity: 1; ">

How to hide a mobile browser's address bar?

create host file = manifest.json

html tag head

<link rel="manifest" href="/manifest.json">

file

manifest.json

{
"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"news",
"business"
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"related_applications": [
{
"platform": "play",
"url": "https://play.google.com/store/apps/details?id=ir.divar"
}
],
"prefer_related_applications": true
}

Fatal error: Call to undefined function pg_connect()

In windows OS find this in php.ini "php_pgsql.dll" and remove the ";" in the extension then that's it :) Cheeers!

Filtering collections in C#

List<T> has a FindAll method that will do the filtering for you and return a subset of the list.

MSDN has a great code example here: http://msdn.microsoft.com/en-us/library/aa701359(VS.80).aspx

EDIT: I wrote this before I had a good understanding of LINQ and the Where() method. If I were to write this today i would probably use the method Jorge mentions above. The FindAll method still works if you're stuck in a .NET 2.0 environment though.

How to read xml file contents in jQuery and display in html elements?

responseText is what you are looking for. Example:

    $.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});

Where xml is your file. Remember this will be your xml in the form form of a string. You can parse it using xmlparse as some of them mentioned.

How to show imageView full screen on imageView click?

You can use ImageView below two properties to show image based on your requirement :

  1. android:adjustViewBounds : Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.

  2. android:scaleType :Controls how the image should be resized or moved to match the size of this ImageView

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/ic_launcher"/>
    

Above two properties can be use either xml or java code.

As you need to decide at run time need to show image into full screen or not so will apply above two properties at java code as below :

public class MainActivity extends Activity {

    ImageView imageView;

    boolean isImageFitToScreen;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isImageFitToScreen) {
                    isImageFitToScreen=false;
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                    imageView.setAdjustViewBounds(true);
                }else{
                    isImageFitToScreen=true;
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                }
            }
        });

    }
}

Using Exit button to close a winform program

We can close every window using Application.Exit(); Using this method we can close hidden windows also.

private void btnExitProgram_Click(object sender, EventArgs e) { Application.Exit(); }

How to clear/delete the contents of a Tkinter Text widget?

According to the tkinterbook the code to clear a text element should be:

text.delete(1.0,END)

This worked for me. source

It's different from clearing an entry element, which is done like this:

entry.delete(0,END) #note the 0 instead of 1.0

Bad operand type for unary +: 'str'

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

Refused to execute script, strict MIME type checking is enabled?

I had my web server returning:

Content-Type: application\javascript

and couldn't for the life of me figure out what was wrong. Then I realized I had the slash in the wrong direction. It should be:

Content-Type: application/javascript

Insertion Sort vs. Selection Sort

The logic for both algorithms is quite similar. They both have a partially sorted sub-array in the beginning of the array. The only difference is how they search for the next element to be put in the sorted array.

  • Insertion sort: inserts the next element at the correct position;

  • Selection sort: selects the smallest element and exchange it with the current item;

Also, Insertion Sort is stable, as opposed to Selection Sort.

I implemented both in python, and it's worth noting how similar they are:

def insertion(data):
    data_size = len(data)
    current = 1
    while current < data_size:
        for i in range(current):
            if data[current] < data[i]:
                temp = data[i]
                data[i] = data[current]
                data[current] = temp

        current += 1

    return data

With a small change it is possible to make the Selection Sort algorithm.

def selection(data):
    data_size = len(data)
    current = 0
    while current < data_size:
        for i in range(current, data_size):
            if data[i] < data[current]:
                temp = data[i]
                data[i] = data[current]
                data[current] = temp

        current += 1

    return data

Remove accents/diacritics in a string in JavaScript

In NPM there is a package for this: latinize

It's a very good package to solve this issue.

How should you diagnose the error SEHException - External component has thrown an exception

Just another information... Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users. Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException

How to create a simple proxy in C#?

Proxy can work in the following way.

Step1, configure client to use proxyHost:proxyPort.

Proxy is a TCP server that is listening on proxyHost:proxyPort. Browser opens connection with Proxy and sends Http request. Proxy parses this request and tries to detect "Host" header. This header will tell Proxy where to open connection.

Step 2: Proxy opens connection to the address specified in the "Host" header. Then it sends HTTP request to that remote server. Reads response.

Step 3: After response is read from remote HTTP server, Proxy sends the response through an earlier opened TCP connection with browser.

Schematically it will look like this:

Browser                            Proxy                     HTTP server
  Open TCP connection  
  Send HTTP request  ----------->                       
                                 Read HTTP header
                                 detect Host header
                                 Send request to HTTP ----------->
                                 Server
                                                      <-----------
                                 Read response and send
                   <-----------  it back to the browser
Render content

How to get ASCII value of string in C#

This should work:

string s = "9quali52ty3";
byte[] ASCIIValues = Encoding.ASCII.GetBytes(s);
foreach(byte b in ASCIIValues) {
    Console.WriteLine(b);
}

Remove space above and below <p> tag HTML

<p> tags have built in padding and margin. You could create a CSS selector combined with some javascript for instances when your <p> is empty. Probably overkill, but it should do what you need it to do.

CSS example: .NoPaddingOrMargin {padding: 0px; margin:0px}

How to send a model in jQuery $.ajax() post request to MVC controller method

The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

For example, the Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:

public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

Escape double quotes in parameter

I cannot quickly reproduce the symptoms: if I try myscript '"test"' with a batch file myscript.bat containing just @echo.%1 or even @echo.%~1, I get all quotes: '"test"'

Perhaps you can try the escape character ^ like this: myscript '^"test^"'?

Liquibase lock - reasons?

In postgres 12 I needed to use this command:

UPDATE DATABASECHANGELOGLOCK SET LOCKED=false, LOCKGRANTED=null, LOCKEDBY=null where ID=1;

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

toISOString() will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ format then you should get the current time using following two methods

Method 1:

_x000D_
_x000D_
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());
_x000D_
_x000D_
_x000D_

Method 2:

_x000D_
_x000D_
document.write(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
_x000D_
_x000D_
_x000D_

How to make a radio button unchecked by clicking it?

I'm surprised no-one has posted this "neat trick" version which doesn't use any JavaScript, it only uses CSS.

_x000D_
_x000D_
#radio1 {
    display: none;
}

#wrapper {
    /* NOTE: This wrapper div is not needed provided you can position the label for #radio1 on top of #radio2 using some other technique. */
    position: relative;
}

#radio1:not(:checked) ~ * label[for="radio1"] {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
#radio1:checked ~ * label[for="radio1"] {
    display: none;
}

/* Non-essential styles: */ 

label[for],
label:not([for="radio1"]) {
    cursor: pointer;
    border-radius: 7px;
}
label[for]:hover + label,
label:not([for="radio1"]):hover {
    background-color: #ccc;
}
_x000D_
<input type="radio" name="group1" id="radio1" checked="checked"  />

<p>Look mum, <strong>no JavaScript!</strong></p>

<div id="wrapper">
    <label for="radio1"></label>
    <label>
        <input type="radio" name="group1" id="radio2" />
        You can toggle me on and off!
    </label>
</div>
_x000D_
_x000D_
_x000D_


Explanation:

  • #radio1 (<input type="radio" id="radio2" />) is always hidden.
  • Using CSS's :checked and :not(:checked) pseudo-class selectors with sibling selectors (+ and ~) allow other elements' style to be affected depending on whether or not an <input type="checkbox" /> or <input type="radio" /> is checked.
    • So when #radio1 is un-checked (or when #radio2 is checked) that causes a <label> to be overlayed on-top of #radio2 and that label has for="radio1", so clicking it will cause #radio1 to be checked, not #radio2.
    • IMPORTANT CAVEAT: CSS's sibling selector rules only allows selectors to select elements based on their ancestors and their ancestors earlier siblings. So you cannot style an element based on any other descendants of its ancestors.
      • This limitation will be removed when CSS4's :has() selector function is supported but as of November 2020 only PrinceXML supports :has() and it's currently looking like :has() will be dropped from CSS4 entirely owing to the difficulty of implementation.

This approach can be scaled to support multiple radio buttons:

_x000D_
_x000D_
#uncheckAll {
    display: none;
}

#uncheckAll:checked ~ * label[for="uncheckAll"] {
    display: none;
}

label {
    cursor: pointer;
}

label:not([for]) {
    position: relative;
}

label[for="uncheckAll"] {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

input[name="group1"]:not(:checked) + label[for="uncheckAll"] {
    display: none;
}
_x000D_
<input type="radio" name="group1" id="uncheckAll" checked="checked"  />

<label>
    <input type="radio" name="group1" id="radio2" />
    <label for="uncheckAll"></label>
    You can toggle me on and off!
</label>

<label>
    <input type="radio" name="group1" id="radio3" />
    <label for="uncheckAll"></label>
    And me!
</label>

<label>
    <input type="radio" name="group1" id="aragorn" />
    <label for="uncheckAll"></label>
    And my sword!
</label>

<label>
    <input type="radio" name="group1" id="gimli" />
    <label for="uncheckAll"></label>
    And my axe!
</label>
_x000D_
_x000D_
_x000D_

How to set bot's status

.setGame is discontinued. Use:

client.user.setActivity("Game"); 

To set a playing game status.

As an addition, if you were using an earlier version of discord.js, try this:

client.user.setGame("Game");

In newer versions of discord.js, this is deprecated.