Programs & Examples On #Class diagram

UML diagram describing object classes and relations among them.

PHP UML Generator

I strongly recommend BOUML which:

  • is extremely fast (fastest UML tool ever created, check out benchmarks),
  • has rock solid PHP import and export support (also supports C++, Java, Python)
  • is multiplatform (Linux, Windows, other OSes),
  • is full featured, impressively intensively developed (look at development history, it's hard to believe that such fast progress is possible).
  • supports plugins, has modular architecture (this allows user contributions, looks like BOUML community is forming up)

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

Use IntelliJ to generate class diagram

IntelliJ IDEA 14+

  • Show diagram popup

    Right click on a type/class/package > Diagrams > Show Diagram Popup...
    or Ctrl+Alt+U

  • Show diagram (opens a new tab)

    Right click on a type/class/package > Diagrams > Show Diagram...
    or Ctrl+Alt+Shift+U

    right click Diagrams Show Diagram

By default, you see only the classes/interfaces names. If you want to see more details, go to File > Settings... > Tools > Diagrams and check what you want (E.g.: Fields, Methods, etc.)


P.S.: You need IntelliJ IDEA Ultimate, because this feature is not supported in Community Edition. If you go to File > Settings... > Plugins, you can see that there is not UML Support plugin in Community Edition.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Robustness diagrams are written after use cases and before class diagrams. They help to identify the roles of use case steps. You can use them to ensure your use cases are sufficiently robust to represent usage requirements for the system you're building.

They involve:

  1. Actors
  2. Use Cases
  3. Entities
  4. Boundaries
  5. Controls

Whereas the Model-View-Controller pattern is used for user interfaces, the Entity-Control-Boundary Pattern (ECB) is used for systems. The following aspects of ECB can be likened to an abstract version of MVC, if that's helpful:

UML notation

Entities (model)
Objects representing system data, often from the domain model.

Boundaries (view/service collaborator)
Objects that interface with system actors (e.g. a user or external service). Windows, screens and menus are examples of boundaries that interface with users.

Controls (controller)
Objects that mediate between boundaries and entities. These serve as the glue between boundary elements and entity elements, implementing the logic required to manage the various elements and their interactions. It is important to understand that you may decide to implement controllers within your design as something other than objects – many controllers are simple enough to be implemented as a method of an entity or boundary class for example.

Four rules apply to their communication:

  1. Actors can only talk to boundary objects.
  2. Boundary objects can only talk to controllers and actors.
  3. Entity objects can only talk to controllers.
  4. Controllers can talk to boundary objects and entity objects, and to other controllers, but not to actors

Communication allowed:

         Entity    Boundary   Control
Entity     X                     X
Boundary                         X
Control    X          X          X

Generate UML Class Diagram from Java Project

How about the Omondo Plugin for Eclipse. I have used it and I find it to be quite useful. Although if you are generating diagrams for large sources, you might have to start Eclipse with more memory.

How to use doxygen to create UML class diagrams from C++ source

Doxygen creates inheritance diagrams but I dont think it will create an entire class hierachy. It does allow you to use the GraphViz tool. If you use the Doxygen GUI frontend tool you will find the relevant options in Step2: -> Wizard tab -> Diagrams. The DOT relation options are under the Expert Tab.

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

I found a free plugin that can generate class diagrams with android studio. It's called SimpleUML.

Update Android Studio 2.2+: To install the plugin, follow steps in this answer: https://stackoverflow.com/a/36823007/1245894

Older version of Android Studio On Mac: go to Android Studio -> Preferences -> Plugins

On Windows: go to Android Studio -> File -> Settings -> Plugins

Click on Browse repositories... and search for SimpleUMLCE (CE means Community Edition, this is what android studio is based on).

Install it, restart, then you can do a right click on the folder containing the classes you want to visualize, and select Add to simpleUML Diagram.

That's it; you have you fancy class diagram generated from your code!

What is the meaning of the prefix N in T-SQL statements and when should I use it?

It's declaring the string as nvarchar data type, rather than varchar

You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.

To quote from Microsoft:

Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.


If you want to know the difference between these two data types, see this SO post:

What is the difference between varchar and nvarchar?

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

.NET Excel Library that can read/write .xls files

You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:

C# sample

// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;

Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";

// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");

VB.NET sample

' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells

Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"

' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")

Filezilla FTP Server Fails to Retrieve Directory Listing

I experienced the same problem with FZ-client, while my notebook connected via WLAN and DSL/Router. In the Site Manager connection settings I was applied Host:ftp.domain-name, Encryption:Only use plain FTP (insecure) and User:username@domain-name. Then the FTP-client succesfully connected to my website server. More FTP connection information could be found in the CPanel of the webserver. Hope this helps.

Pass parameter to EventHandler

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

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

Edit: you can also use shorter version:

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

How do you migrate an IIS 7 site to another server?

I can't comment up thread due to lack of rep. Another commenter stated they couldn't migrate from a lower version to a higher version of IIS. This is true if you don't merge some files, but if you do you can as I just migrated my IIS 7.5 site to IIS 8.0 using the answer posted by chews.

When the export is created (II7.5), there are two key files (administration.config and applicationHost.config) which have references to resources on the IIS7.5 server. For example, a DLL will be referred with a public key and version specific to 7.5. These are NOT the same on the IIS8 server. The feature configuration may differ as well (I ensured mine were identical). There are some new features in 8 which will never exist in 7.5.

If you are brave enough to merge the two files - it will work. I had to uninstall IIS once because I messed it up, but got it the second time.

I used a merge tool (Beyond Compare) and without something equivalent it would be a huge PITA - but was pretty easy with a good diff tool (five minutes).

To do the merge, the 8.0 files need to be diffed against the exported 7.5 files BEFORE an import is attempted. For the most part, the 8.0 files need to overwrite the server specific stuff in the exported 7.5 files, while leaving the site/app pool specific stuff.

I found that administration.config was almost identical, sans the version info of many entries. This one was easy.

The applicationHost.config has a lot more differences. Some entries are ordered differently, but otherwise identical, so you will have to pick through each difference and figure it out.

I put my 7.5 export files in the System32\inetsrv\config\Export folder prior to merging.

I merged FROM folder System32\inetsrv\config to folder System32\inetsrv\config\Export for both files I mentioned above. I pushed over everything in the FROM files except site specific tags/elements (e.g. applicationPools, customMetadata, sites, authentication). Of special note, there were also many site specific "location" tag blocks that I had to keep, but the new server had its own "location" tag block with server specific defaults that has to be kept.

Lastly, do note that if you use service accounts, these cached passwords are junk and will have to be re-entered for your app pools. None of my sites worked initially, but all that was required was re-entering the passwords for all my app pools and I was up and running.

If someone who can comment mention this post down thread - it will probably help someone else like me who has many sites on one server with complicated configurations.

Regards,

Stuart

Parsing boolean values with argparse

Simplest & most correct way is:

from distutils.util import strtobool

parser.add_argument('--feature', dest='feature', 
                    type=lambda x: bool(strtobool(x)))

Do note that True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

Laravel 5.2 - pluck() method returns array

In the original example, why not use the select() method in your database query?

$name = DB::table('users')->where('name', 'John')->select("id");

This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...

Larvel 5.3: Specifying a Select Clause

Spool Command: Do not output SQL statement to file

set echo off
spool c:\test.csv 
select /*csv*/ username, user_id, created from all_users;
spool off;

escaping question mark in regex javascript

You should use double slash:

var regex = new RegExp("\\?", "g");

Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"

And "\\?", becomes "\?"

Force an Android activity to always use landscape mode

Press CTRL+F11 to rotate the screen.

how do you filter pandas dataframes by multiple columns

In case somebody wonders what is the faster way to filter (the accepted answer or the one from @redreamality):

import pandas as pd
import numpy as np

length = 100_000
df = pd.DataFrame()
df['Year'] = np.random.randint(1950, 2019, size=length)
df['Gender'] = np.random.choice(['Male', 'Female'], length)

%timeit df.query('Gender=="Male" & Year=="2014" ')
%timeit df[(df['Gender']=='Male') & (df['Year']==2014)]

Results for 100,000 rows:

6.67 ms ± 557 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.54 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Results for 10,000,000 rows:

326 ms ± 6.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
472 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So results depend on the size and the data. On my laptop, query() gets faster after 500k rows. Further, the string search in Year=="2014" has an unnecessary overhead (Year==2014 is faster).

What are 'get' and 'set' in Swift?

The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.

Consider a variable members of a class family. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.

So you would probably go ahead by defining the members variable like this:

class family {
   var members:Int
}

This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.

This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.

Returning to our family class, let's make sure nobody can set the members value to anything less than 2:

class family {
  var _members:Int = 2
  var members:Int {
   get {
     return _members
   }
   set (newVal) {
     if newVal >= 2 {
       _members = newVal
     } else {
       println('error: cannot have family with less than 2 members')
     }
   }
  }
}

Now we can access the members variable as before, by typing instanceOfFamily.members, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.

Note the introduction of the _members variable, which is the actual variable to store the value that we set through the members setter function. The original members has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.

Get absolute path of initially run script

realpath($_SERVER['SCRIPT_FILENAME'])

For script run under web server $_SERVER['SCRIPT_FILENAME'] will contain the full path to the initially called script, so probably your index.php. realpath() is not required in this case.

For the script run from console $_SERVER['SCRIPT_FILENAME'] will contain relative path to your initially called script from your current working dir. So unless you changed working directory inside your script it will resolve to the absolute path.

WPF Binding StringFormat Short Date String

If you want add a string with the value use this:

<TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" />

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Regarding semicolon insertion and the var statement, beware forgetting the comma when using var but spanning multiple lines. Somebody found this in my code yesterday:

    var srcRecords = src.records
        srcIds = [];

It ran but the effect was that the srcIds declaration/assignment was global because the local declaration with var on the previous line no longer applied as that statement was considered finished due to automatic semi-colon insertion.

ImportError: No module named six

on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve

ImportError: No module named six

when launching Wammu

If it's occurred for python3 program, six come with

pip3 install six

and if you don't have pip3:

apt install python3-pip

with sudo under Ubuntu!

Reverse Singly Linked List Java

A more elegant solution would be to use recursion

void ReverseList(ListNode current, ListNode previous) {
            if(current.Next != null) 
            {
                ReverseList(current.Next, current);
                ListNode temp = current.Next;
                temp.Next = current;
                current.Next = previous;
            }
        }

What are metaclasses in Python?

Python classes are themselves objects - as in instance - of their meta-class.

The default metaclass, which is applied when when you determine classes as:

class foo:
    ...

meta class are used to apply some rule to an entire set of classes. For example, suppose you're building an ORM to access a database, and you want records from each table to be of a class mapped to that table (based on fields, business rules, etc..,), a possible use of metaclass is for instance, connection pool logic, which is share by all classes of record from all tables. Another use is logic to to support foreign keys, which involves multiple classes of records.

when you define metaclass, you subclass type, and can overrided the following magic methods to insert your logic.

class somemeta(type):
    __new__(mcs, name, bases, clsdict):
      """
  mcs: is the base metaclass, in this case type.
  name: name of the new class, as provided by the user.
  bases: tuple of base classes 
  clsdict: a dictionary containing all methods and attributes defined on class

  you must return a class object by invoking the __new__ constructor on the base metaclass. 
 ie: 
    return type.__call__(mcs, name, bases, clsdict).

  in the following case:

  class foo(baseclass):
        __metaclass__ = somemeta

  an_attr = 12

  def bar(self):
      ...

  @classmethod
  def foo(cls):
      ...

      arguments would be : ( somemeta, "foo", (baseclass, baseofbase,..., object), {"an_attr":12, "bar": <function>, "foo": <bound class method>}

      you can modify any of these values before passing on to type
      """
      return type.__call__(mcs, name, bases, clsdict)


    def __init__(self, name, bases, clsdict):
      """ 
      called after type has been created. unlike in standard classes, __init__ method cannot modify the instance (cls) - and should be used for class validaton.
      """
      pass


    def __prepare__():
        """
        returns a dict or something that can be used as a namespace.
        the type will then attach methods and attributes from class definition to it.

        call order :

        somemeta.__new__ ->  type.__new__ -> type.__init__ -> somemeta.__init__ 
        """
        return dict()

    def mymethod(cls):
        """ works like a classmethod, but for class objects. Also, my method will not be visible to instances of cls.
        """
        pass

anyhow, those two are the most commonly used hooks. metaclassing is powerful, and above is nowhere near and exhaustive list of uses for metaclassing.

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.

Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:

  1. start the 32 bits UDL wizard like this: C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)
  2. open the UDL file in Notepad or another text editor, it should more or less have this format:

[oledb] ; Everything after this line is an OLE DB initstring Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False

That should allow your app to start correctly.

When should I use git pull --rebase?

git pull --rebase may hide a history rewriting from a collaborator git push --force. I recommend to use git pull --rebase only if you know you forgot to push your commits before someone else does the same.

If you did not commit anything, but your working space is not clean, just git stash before to git pull. This way you won't silently rewrite your history (which could silently drop some of your work).

Unresolved reference issue in PyCharm

After following the accepted answer, doing the following solved it for me:

File ? Settings ? Project <your directory/project> ? Project Dependencies

Chose the directory/project where your file that has unresolved imports resides and check the box to tell Pycharm that that project depends on your other project.

My folder hierarcy is slightly different from the one in the question. Mine is like this

+-- MyDirectory  
¦     +-- simulate.py  
+-- src  
¦     +-- networkAlgorithm.py  
¦     +-- ...

Telling Pycharm that src depends on MyDirectory solved the issue for me!

How to write Unicode characters to the console?

This works for me:

Console.OutputEncoding = System.Text.Encoding.Default;

To display some of the symbols, it's required to set Command Prompt's font to Lucida Console:

  1. Open Command Prompt;

  2. Right click on the top bar of the Command Prompt;

  3. Click Properties;

  4. If the font is set to Raster Fonts, change it to Lucida Console.

Python - abs vs fabs

math.fabs() converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.

In addition to floats, abs() also works with integers and complex numbers. Its return type depends on the type of its argument.

In [7]: type(abs(-2))
Out[7]: int

In [8]: type(abs(-2.0))
Out[8]: float

In [9]: type(abs(3+4j))
Out[9]: float

In [10]: type(math.fabs(-2))
Out[10]: float

In [11]: type(math.fabs(-2.0))
Out[11]: float

In [12]: type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))

TypeError: can't convert complex to float

Select All Rows Using Entity Framework

I used the entitydatasource and it provide everything I needed for what I wanted to do.

_repository.[tablename].ToList();

How to check if an element does NOT have a specific class?

use the .not() method and check for an attribute:

$('p').not('[class]');

Check it here: http://jsfiddle.net/AWb79/

g++ ld: symbol(s) not found for architecture x86_64

I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:

gcc -o exec main.o add.o

But my program is a C++ program. Using the g++ compiler solved my issue:

g++ -o exec main.o add.o

I was always under the impression that gcc could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.

Twitter bootstrap scrollable table

Re Jonathan Wood's suggestion. I don't have the option of wrapping tables with a new div as i'm using a CMS. Using JQuery here's what i did:

$( "table" ).wrap( "<div class='table-overflow'></div>" );

This wraps table elements with a new div with the class "table-overflow".

You can then simply add the following definition in your css file:

.table-overflow { overflow: auto; }     

What is a regex to match ONLY an empty string?

The answer may be language dependent, but since you don't mention one, here is what I just came up with in js:

 var a = ['1','','2','','3'].join('\n');

 console.log(a.match(/^.{0}$/gm)); // ["", ""]

 // the "." is for readability. it doesn't really matter
 a.match(/^[you can put whatever the hell you want and this will also work just the same]{0}$/gm)

You could also do a.match(/^(.{10,}|.{0})$/gm) to match empty lines OR lines that meet a criteria. (This is what I was looking for to end up here.)

I know that ^ will match the beginning of any line and $ will match the end of any line

This is only true if you have the multiline flag turned on, otherwise it will only match the beginning/end of the string. I'm assuming you know this and are implying that, but wanted to note it here for learners.

grabbing first row in a mysql query only

To return only one row use LIMIT 1:

SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1

It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY clause. Assuming you add an ORDER BY clause then you can use LIMIT in the following ways:

  • To get the first row use LIMIT 1.
  • To get the 2nd row you can use limit with an offset: LIMIT 1, 1.
  • To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1.

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
    doThis();
} else if (value == 2) {
    doThat();
} else {
    doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)
}

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

How to use NSJSONSerialization

The following code fetches a JSON object from a webserver, and parses it to an NSDictionary. I have used the openweathermap API that returns a simple JSON response for this example. For keeping it simple, this code uses synchronous requests.

   NSString *urlString   = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk"; // The Openweathermap JSON responder
   NSURL *url            = [[NSURL alloc]initWithString:urlString];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSURLResponse *response;
   NSData *GETReply      = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
   NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
   Nslog(@"%@",res);

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I have also dealt with this exception after a fully working context.xml setup was adjusted. I didn't want environment details in the context.xml, so I took them out and saw this error. I realized I must fully create this datasource resource in code based on System Property JVM -D args.

Original error with just user/pwd/host removed: org.apache.tomcat.jdbc.pool.ConnectionPool init SEVERE: Unable to create initial connections of pool.

Removed entire contents of context.xml and try this: Initialize on startup of app server the datasource object sometime before using first connection. If using Spring this is good to do in an @Configuration bean in @Bean Datasource constructor.

package to use: org.apache.tomcat.jdbc.pool.*

PoolProperties p = new PoolProperties();
p.setUrl(jdbcUrl);
            p.setDriverClassName(driverClass);
            p.setUsername(user);
            p.setPassword(pwd);
            p.setJmxEnabled(true);
            p.setTestWhileIdle(false);
            p.setTestOnBorrow(true);
            p.setValidationQuery("SELECT 1");
            p.setTestOnReturn(false);
            p.setValidationInterval(30000);
            p.setValidationQueryTimeout(100);
            p.setTimeBetweenEvictionRunsMillis(30000);
            p.setMaxActive(100);
            p.setInitialSize(5);
            p.setMaxWait(10000);
            p.setRemoveAbandonedTimeout(60);
            p.setMinEvictableIdleTimeMillis(30000);
            p.setMinIdle(5);
            p.setLogAbandoned(true);
            p.setRemoveAbandoned(true);
            p.setJdbcInterceptors(
              "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
              "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
            org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
            ds.setPoolProperties(p);
            return ds;

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

Unit testing click event in Angular

Events can be tested using the async/fakeAsync functions provided by '@angular/core/testing', since any event in the browser is asynchronous and pushed to the event loop/queue.

Below is a very basic example to test the click event using fakeAsync.

The fakeAsync function enables a linear coding style by running the test body in a special fakeAsync test zone.

Here I am testing a method that is invoked by the click event.

it('should', fakeAsync( () => {
    fixture.detectChanges();
    spyOn(componentInstance, 'method name'); //method attached to the click.
    let btn = fixture.debugElement.query(By.css('button'));
    btn.triggerEventHandler('click', null);
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(componentInstance.methodName).toHaveBeenCalled();
}));

Below is what Angular docs have to say:

The principle advantage of fakeAsync over async is that the test appears to be synchronous. There is no then(...) to disrupt the visible flow of control. The promise-returning fixture.whenStable is gone, replaced by tick()

There are limitations. For example, you cannot make an XHR call from within a fakeAsync

Find first element by predicate

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

Which outputs:

will filter 1
will filter 10
10

You see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

declare
  myname varchar2(20) := 'tom';
begin
  for result_cursor in (select * from mytable where first_name = myname) loop
    dbms_output.put_line(result_cursor.first_name);
    dbms_output.put_line(result_cursor.other_field);
  end loop;
end;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

declare 
  myname varchar2(20);
begin
  select first_name into myname 
    from mytable 
    where person_id = 123;
end;

Get type of all variables

You need to use get to obtain the value rather than the character name of the object as returned by ls:

x <- 1L
typeof(ls())
[1] "character"
typeof(get(ls()))
[1] "integer"

Alternatively, for the problem as presented you might want to use eapply:

eapply(.GlobalEnv,typeof)
$x
[1] "integer"

$a
[1] "double"

$b
[1] "character"

$c
[1] "list"

Running multiple AsyncTasks at the same time -- not possible?

The android developers example of loading bitmaps efficiently uses a custom asynctask (copied from jellybean) so you can use the executeOnExecutor in apis lower than < 11

http://developer.android.com/training/displaying-bitmaps/index.html

Download the code and go to util package.

Enter export password to generate a P12 certificate

OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.

You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword to pass the password YourPassword from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.

How do I sort a list of dictionaries by a value of the dictionary?

Sometimes we need to use lower(). For example,

lists = [{'name':'Homer', 'age':39},
  {'name':'Bart', 'age':10},
  {'name':'abby', 'age':9}]

lists = sorted(lists, key=lambda k: k['name'])
print(lists)
# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]

lists = sorted(lists, key=lambda k: k['name'].lower())
print(lists)
# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

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

I'll interpret your question as two questions: 1) why -> even exists, and 2) why . does not automatically dereference the pointer. Answers to both questions have historical roots.

Why does -> even exist?

In one of the very first versions of C language (which I will refer as CRM for "C Reference Manual", which came with 6th Edition Unix in May 1975), operator -> had very exclusive meaning, not synonymous with * and . combination

The C language described by CRM was very different from the modern C in many respects. In CRM struct members implemented the global concept of byte offset, which could be added to any address value with no type restrictions. I.e. all names of all struct members had independent global meaning (and, therefore, had to be unique). For example you could declare

struct S {
  int a;
  int b;
};

and name a would stand for offset 0, while name b would stand for offset 2 (assuming int type of size 2 and no padding). The language required all members of all structs in the translation unit either have unique names or stand for the same offset value. E.g. in the same translation unit you could additionally declare

struct X {
  int a;
  int x;
};

and that would be OK, since the name a would consistently stand for offset 0. But this additional declaration

struct Y {
  int b;
  int a;
};

would be formally invalid, since it attempted to "redefine" a as offset 2 and b as offset 0.

And this is where the -> operator comes in. Since every struct member name had its own self-sufficient global meaning, the language supported expressions like these

int i = 5;
i->b = 42;  /* Write 42 into `int` at address 7 */
100->a = 0; /* Write 0 into `int` at address 100 */

The first assignment was interpreted by the compiler as "take address 5, add offset 2 to it and assign 42 to the int value at the resultant address". I.e. the above would assign 42 to int value at address 7. Note that this use of -> did not care about the type of the expression on the left-hand side. The left hand side was interpreted as an rvalue numerical address (be it a pointer or an integer).

This sort of trickery was not possible with * and . combination. You could not do

(*i).b = 42;

since *i is already an invalid expression. The * operator, since it is separate from ., imposes more strict type requirements on its operand. To provide a capability to work around this limitation CRM introduced the -> operator, which is independent from the type of the left-hand operand.

As Keith noted in the comments, this difference between -> and *+. combination is what CRM is referring to as "relaxation of the requirement" in 7.1.8: Except for the relaxation of the requirement that E1 be of pointer type, the expression E1->MOS is exactly equivalent to (*E1).MOS

Later, in K&R C many features originally described in CRM were significantly reworked. The idea of "struct member as global offset identifier" was completely removed. And the functionality of -> operator became fully identical to the functionality of * and . combination.

Why can't . dereference the pointer automatically?

Again, in CRM version of the language the left operand of the . operator was required to be an lvalue. That was the only requirement imposed on that operand (and that's what made it different from ->, as explained above). Note that CRM did not require the left operand of . to have a struct type. It just required it to be an lvalue, any lvalue. This means that in CRM version of C you could write code like this

struct S { int a, b; };
struct T { float x, y, z; };

struct T c;
c.b = 55;

In this case the compiler would write 55 into an int value positioned at byte-offset 2 in the continuous memory block known as c, even though type struct T had no field named b. The compiler would not care about the actual type of c at all. All it cared about is that c was an lvalue: some sort of writable memory block.

Now note that if you did this

S *s;
...
s.b = 42;

the code would be considered valid (since s is also an lvalue) and the compiler would simply attempt to write data into the pointer s itself, at byte-offset 2. Needless to say, things like this could easily result in memory overrun, but the language did not concern itself with such matters.

I.e. in that version of the language your proposed idea about overloading operator . for pointer types would not work: operator . already had very specific meaning when used with pointers (with lvalue pointers or with any lvalues at all). It was very weird functionality, no doubt. But it was there at the time.

Of course, this weird functionality is not a very strong reason against introducing overloaded . operator for pointers (as you suggested) in the reworked version of C - K&R C. But it hasn't been done. Maybe at that time there was some legacy code written in CRM version of C that had to be supported.

(The URL for the 1975 C Reference Manual may not be stable. Another copy, possibly with some subtle differences, is here.)

Android dex gives a BufferOverflowException when building

Try what van said:

Right click your projectandroid toolsandroid support library.

Hope this helps :)

python pandas extract year from datetime: df['year'] = df['date'].year is not working

When to use dt accessor

A common source of confusion revolves around when to use .year and when to use .dt.year.

The former is an attribute for pd.DatetimeIndex objects; the latter for pd.Series objects. Consider this dataframe:

df = pd.DataFrame({'Dates': pd.to_datetime(['2018-01-01', '2018-10-20', '2018-12-25'])},
                  index=pd.to_datetime(['2000-01-01', '2000-01-02', '2000-01-03']))

The definition of the series and index look similar, but the pd.DataFrame constructor converts them to different types:

type(df.index)     # pandas.tseries.index.DatetimeIndex
type(df['Dates'])  # pandas.core.series.Series

The DatetimeIndex object has a direct year attribute, while the Series object must use the dt accessor. Similarly for month:

df.index.month               # array([1, 1, 1])
df['Dates'].dt.month.values  # array([ 1, 10, 12], dtype=int64)

A subtle but important difference worth noting is that df.index.month gives a NumPy array, while df['Dates'].dt.month gives a Pandas series. Above, we use pd.Series.values to extract the NumPy array representation.

How to update Python?

UPDATE: 2018-07-06

This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don't know if the Windows registry keys are still the same.

UPDATE: 2017-03-24

There have been no updates to Python(x,y) since June of 2015, so I think it's safe to assume it has been abandoned.

UPDATE: 2016-11-11

As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I'll save that exercise for the reader. If you don't want to hack, I suggest that if switching bit-versions, remove the other bit-version first.

UPDATES: 2016-05-16
  • Anaconda and MiniConda can be used with an existing Python installation by disabling the options to alter the Windows PATH and Registry. After extraction, create a symlink to conda in your bin or install conda from PyPI. Then create another symlink called conda-activate to activate in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root to enable Anaconda/Miniconda.
  • Portable Python is no longer being developed or maintained.

TL;DR

  • Using Anaconda or miniconda, then just execute conda update --all to keep each conda environment updated,
  • same major version of official Python (e.g. 2.7.5), just install over old (e.g. 2.7.4),
  • different major version of official Python (e.g. 3.3), install side-by-side with old, set paths/associations to point to dominant (e.g. 2.7), shortcut to other (e.g. in BASH $ ln /c/Python33/python.exe python3).

The answer depends:

  1. If OP has 2.7.x and wants to install newer version of 2.7.x, then

    • if using MSI installer from the official Python website, just install over old version, installer will issue warning that it will remove and replace the older version; looking in "installed programs" in "control panel" before and after confirms that the old version has been replaced by the new version; newer versions of 2.7.x are backwards compatible so this is completely safe and therefore IMHO multiple versions of 2.7.x should never necessary.
    • if building from source, then you should probably build in a fresh, clean directory, and then point your path to the new build once it passes all tests and you are confident that it has been built successfully, but you may wish to keep the old build around because building from source may occasionally have issues. See my guide for building Python x64 on Windows 7 with SDK 7.0.
    • if installing from a distribution such as Python(x,y), see their website. Python(x,y) has been abandoned. I believe that updates can be handled from within Python(x,y) with their package manager, but updates are also included on their website. I could not find a specific reference so perhaps someone else can speak to this. Similar to ActiveState and probably Enthought, Python (x,y) clearly states it is incompatible with other installations of Python:

      It is recommended to uninstall any other Python distribution before installing Python(x,y)

    • Enthought Canopy uses an MSI and will install either into Program Files\Enthought or home\AppData\Local\Enthought\Canopy\App for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.
    • ActiveState also uses an MSI so newer installations can be installed on top of older ones. See their installation notes.

      Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.

    • Sage recommends that you install it into a virtual machine, and provides a Oracle VirtualBox image file that can be used for this purpose. Upgrades are handled internally by issuing the sage -upgrade command.
    • Anaconda can be updated by using the conda command:

      conda update --all
      

      Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.

      Anaconda will likely disrupt any other Python installations. Installation uses MSI installer. [UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe installers and provide options to disable Windows PATH and Registry alterations.

      Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe installer is used and the options to alter Windows PATH and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore keys.

      Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\ with the following keys: Help, InstallPath, Modules and PythonPath - official Python registers these keys too, but under Python\PythonCore. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the "Register with Windows" option during installation, it doesn't create PythonCore, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.

    • WinPython updates, I think, can be handled through the WinPython Control Panel.
    • PortablePython is no longer being developed. It had no update method. Possibly updates could be unzipped into a fresh directory and then App\lib\site-packages and App\Scripts could be copied to the new installation, but if this didn't work then reinstalling all packages might have been necessary. Use pip list to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip to install pip if it wasn't installed.
  2. If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is

    • C:\Python33 for 3.3.x (latest 2013-07-29)
    • C:\Python32 for 3.2.x
    • &c.
    • C:\Python27 for 2.7.x (latest 2013-07-29)
    • C:\Python26 for 2.6.x
    • &c.
  3. If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.

I hope this clears up any confusion.

JSchException: Algorithm negotiation fail

Make sure that you're using the latest version of JSch. I had this exact same problem when using JSch 0.1.31 and trying to connect to a RedHat 5 server. Updating to the latest version solved the problem.

How can the Euclidean distance be calculated with NumPy?

Find difference of two matrices first. Then, apply element wise multiplication with numpy's multiply command. After then, find summation of the element wise multiplied new matrix. Finally, find square root of the summation.

def findEuclideanDistance(a, b):
    euclidean_distance = a - b
    euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
    euclidean_distance = np.sqrt(euclidean_distance)
    return euclidean_distance

Sorting objects by property values

A version of Cheeso solution with reverse sorting, I also removed the ternary expressions for lack of clarity (but this is personal taste).

function(prop, reverse) {
  return function(a, b) {
    if (typeof a[prop] === 'number') {
      return (a[prop] - b[prop]);
    }

    if (a[prop] < b[prop]) {
      return reverse ? 1 : -1;
    }

    if (a[prop] > b[prop]) {
      return reverse ? -1 : 1;
    }

    return 0;
  };
};

C++ for each, pulling from vector elements

C++ does not have the for_each loop feature in its syntax. You have to use c++11 or use the template function std::for_each.

struct Function {
    int input;
    Function(int input): input(input) {}
    void operator()(Attack& attack) {
        if(attack->m_num == input) attack->makeDamage();
    }
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);

How to open a file / browse dialog using javascript?

you can't use input.click() directly, but you can call this in other element click event.

html

<input type="file">
<button>Select file</button>

js

var botton = document.querySelector('button');
var input = document.querySelector('input');
botton.addEventListener('click', function (e) {
    input.click();
});

this tell you Using hidden file input elements using the click() method

How to add a new row to datagridview programmatically

If you are binding a List

List<Student> student = new List<Student>();

dataGridView1.DataSource = student.ToList();
student .Add(new Student());

//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;

If you are binding DataTable

DataTable table = new DataTable();

 DataRow newRow = table.NewRow();

// Add the row to the rows collection.
table.Rows.Add(newRow);

Python error: AttributeError: 'module' object has no attribute

The way I would do it is to leave the __ init__.py files empty, and do:

import lib.mod1.mod11
lib.mod1.mod11.mod12()

or

from lib.mod1.mod11 import mod12
mod12()

You may find that the mod1 dir is unnecessary, just have mod12.py in lib.

How do I get an object's unqualified (short) class name?

I found myself in a unique situation where instanceof could not be used (specifically namespaced traits) and I needed the short name in the most efficient way possible so I've done a little benchmark of my own. It includes all the different methods & variations from the answers in this question.

$bench = new \xori\Benchmark(1000, 1000);     # https://github.com/Xorifelse/php-benchmark-closure
$shell = new \my\fancy\namespace\classname(); # Just an empty class named `classname` defined in the `\my\fancy\namespace\` namespace

$bench->register('strrpos', (function(){
    return substr(static::class, strrpos(static::class, '\\') + 1);
})->bindTo($shell));

$bench->register('safe strrpos', (function(){
    return substr(static::class, ($p = strrpos(static::class, '\\')) !== false ? $p + 1 : 0);
})->bindTo($shell));

$bench->register('strrchr', (function(){
    return substr(strrchr(static::class, '\\'), 1);
})->bindTo($shell));

$bench->register('reflection', (function(){
    return (new \ReflectionClass($this))->getShortName();
})->bindTo($shell));

$bench->register('reflection 2', (function($obj){
    return $obj->getShortName();
})->bindTo($shell), new \ReflectionClass($shell));

$bench->register('basename', (function(){
    return basename(str_replace('\\', '/', static::class));
})->bindTo($shell));

$bench->register('explode', (function(){
    $e = explode("\\", static::class);
    return end($e);
})->bindTo($shell));

$bench->register('slice', (function(){
    return join('',array_slice(explode('\\', static::class), -1));
})->bindTo($shell));    

print_r($bench->start());

A list of the of the entire result is here but here are the highlights:

  • If you're going to use reflection anyways, using $obj->getShortName() is the fastest method however; using reflection only to get the short name it is almost the slowest method.
  • 'strrpos' can return a wrong value if the object is not in a namespace so while 'safe strrpos' is a tiny bit slower I would say this is the winner.
  • To make 'basename' compatible between Linux and Windows you need to use str_replace() which makes this method the slowest of them all.

A simplified table of results, speed is measured compared to the slowest method:

+-----------------+--------+
| registered name | speed  |
+-----------------+--------+
| reflection 2    | 70.75% |
| strrpos         | 60.38% |
| safe strrpos    | 57.69% |
| strrchr         | 54.88% |
| explode         | 46.60% |
| slice           | 37.02% |
| reflection      | 16.75% |
| basename        | 0.00%  |
+-----------------+--------+

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In case anybody comes back to this, I think the problem here was failing to install the parent pom first, which all these submodules depend on, so the Maven Reactor can't collect the necessary dependencies to build the submodule.

So from the root directory (here D:\luna_workspace\empire_club\empirecl) it probably just needs a:

mvn clean install

(Aside: <relativePath>../pom.xml</relativePath> is not really necessary as it's the default value).

AngularJS $resource RESTful example

you can just do $scope.todo = Todo.get({ id: 123 }). .get() and .query() on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.

Android Material Design Button Styles

I tried a lot of answer & third party libs, but none was keeping the border and raised effect on pre-lollipop while having the ripple effect on lollipop without drawback. Here is my final solution combining several answers (border/raised are not well rendered on gifs due to grayscale color depth) :

Lollipop

enter image description here

Pre-lollipop

enter image description here

build.gradle

compile 'com.android.support:cardview-v7:23.1.1'

layout.xml

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card"
    card_view:cardElevation="2dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardMaxElevation="8dp"
    android:layout_margin="6dp"
    >
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="0dp"
        android:background="@drawable/btn_bg"
        android:text="My button"/>
</android.support.v7.widget.CardView>

drawable-v21/btn_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
    <item android:drawable="?attr/colorPrimary"/>
</ripple>

drawable/btn_bg.xml

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

Activity's onCreate

    final CardView cardView = (CardView) findViewById(R.id.card);
    final Button button = (Button) findViewById(R.id.button);
    button.setOnTouchListener(new View.OnTouchListener() {
        ObjectAnimator o1 = ObjectAnimator.ofFloat(cardView, "cardElevation", 2, 8)
                .setDuration
                        (80);
        ObjectAnimator o2 = ObjectAnimator.ofFloat(cardView, "cardElevation", 8, 2)
                .setDuration
                        (80);

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    o1.start();
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    o2.start();
                    break;
            }
            return false;
        }
    });

How do I post form data with fetch api?

You can set body to an instance of URLSearchParams with query string passed as argument

fetch("/path/to/server", {
  method:"POST"
, body:new URLSearchParams("[email protected]&password=pw")
})

_x000D_
_x000D_
document.forms[0].onsubmit = async(e) => {_x000D_
  e.preventDefault();_x000D_
  const params = new URLSearchParams([...new FormData(e.target).entries()]);_x000D_
  // fetch("/path/to/server", {method:"POST", body:params})_x000D_
  const response = await new Response(params).text();_x000D_
  console.log(response);_x000D_
}
_x000D_
<form>_x000D_
  <input name="email" value="[email protected]">_x000D_
  <input name="password" value="pw">_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to display line numbers in 'less' (GNU)

From the manual:

-N or --LINE-NUMBERS Causes a line number to be displayed at the beginning of each line in the display.

You can also toggle line numbers without quitting less by typing -N.

It is possible to toggle any of less's command line options in this way.

Restore a deleted file in the Visual Studio Code Recycle Bin

  1. First go to Recycle Bin of your local machine.
  2. Your VS code deleted files is there in Recycle Bin.
  3. So, Right click on deleted files and select-> Restore option then your deleted files will be automatically restored in your VS code.

Install MySQL on Ubuntu without a password prompt

Use:

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"

Python base64 data decode

Interesting if maddening puzzle...but here's the best I could get:

The data seems to repeat every 8 bytes or so.

import struct
import base64

target = \
r'''Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YH 
[snip.]
ZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA''' 

data = base64.b64decode(target)

cleaned_data = []
struct_format = ">ff"
for i in range(len(data) // 8):
   cleaned_data.append(struct.unpack_from(struct_format, data, 8*i))

That gives output like the following (a sampling of lines from the first 100 or so):

(300.00030517578125, 0.0)
(300.05975341796875, 241.93943786621094)
(301.05612182617187, 0.0)
(301.05667114257812, 8.7439727783203125)
(326.9617919921875, 0.0)
(326.96826171875, 0.0)
(328.34432983398438, 280.55218505859375)

That first number does seem to monotonically increase through the entire set. If you plot it:

import matplotlib.pyplot as plt
f, ax = plt.subplots()
ax.plot(*zip(*cleaned_data))

enter image description here

format = 'hhhh' (possibly with various paddings/directions (e.g. '<hhhh', '<xhhhh') also might be worth a look (again, random lines):

(-27069, 2560, 0, 0)
(-27069, 8968, 0, 0)
(-27069, 13576, 3139, -18487)
(-27069, 18184, 31043, -5184)
(-27069, -25721, -25533, -8601)
(-27069, -7289, 0, 0)
(-25533, 31066, 0, 0)
(-25533, -29350, 0, 0)
(-25533, 25179, 0, 0)
(-24509, -1888, 0, 0)
(-24509, -4447, 0, 0)
(-23741, -14725, 32067, 27475)
(-23741, -3973, 0, 0)
(-23485, 4908, -29629, -20922)

Android webview & localStorage

The following was missing:

settings.setDomStorageEnabled(true);

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

For me

Adding this line

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Before this line.

<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>

worked

jQuery Refresh/Reload Page if Ajax Success after time

if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

An efficient compression algorithm for short text strings

I don't have code to hand, but I always liked the approach of building a 2D lookup table of size 256 * 256 chars (RFC 1978, PPP Predictor Compression Protocol). To compress a string you loop over each char and use the lookup table to get the 'predicted' next char using the current and previous char as indexes into the table. If there is a match you write a single 1 bit, otherwise write a 0, the char and update the lookup table with the current char. This approach basically maintains a dynamic (and crude) lookup table of the most probable next character in the data stream.

You can start with a zeroed lookup table, but obviosuly it works best on very short strings if it is initialised with the most likely character for each character pair, for example, for the English language. So long as the initial lookup table is the same for compression and decompression you don't need to emit it into the compressed data.

This algorithm doesn't give a brilliant compression ratio, but it is incredibly frugal with memory and CPU resources and can also work on a continuous stream of data - the decompressor maintains its own copy of the lookup table as it decompresses, thus the lookup table adjusts to the type of data being compressed.

C++ Remove new line from multiline string

If its anywhere in the string than you can't do better than O(n).

And the only way is to search for '\n' in the string and erase it.

for(int i=0;i<s.length();i++) if(s[i]=='\n') s.erase(s.begin()+i);

For more newlines than:

int n=0;
for(int i=0;i<s.length();i++){
    if(s[i]=='\n'){
        n++;//we increase the number of newlines we have found so far
    }else{
        s[i-n]=s[i];
    }
}
s.resize(s.length()-n);//to delete only once the last n elements witch are now newlines

It erases all the newlines once.

Giving UIView rounded corners

You can use following custom UIView class which can also change border color and width. As this is IBDesignalbe You can change the attributes in interface builder as well.

enter image description here

import UIKit

@IBDesignable public class RoundedView: UIView {

    @IBInspectable var borderColor: UIColor = UIColor.white {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable var borderWidth: CGFloat = 2.0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }

}

How to read html from a url in python 3

import requests

url = requests.get("http://yahoo.com")
htmltext = url.text
print(htmltext)

This will work similar to urllib.urlopen.

How can I convert a string to a float in mysql?

This will convert to a numeric value without the need to cast or specify length or digits:

STRING_COL+0.0

If your column is an INT, can leave off the .0 to avoid decimals:

STRING_COL+0

How do I create a SQL table under a different schema?

When I create a table using SSMS 2008, I see 3 panes:

  • The column designer
  • Column properties
  • The table properties

In the table properties pane, there is a field: Schema which allows you to select the schema.

Finding common rows (intersection) in two Pandas dataframes

If I understand you correctly, you can use a combination of Series.isin() and DataFrame.append():

In [80]: df1
Out[80]:
   rating  user_id
0       2  0x21abL
1       1  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
5       2  0x21abL
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
9       1  0x21abL

In [81]: df2
Out[81]:
   rating      user_id
0       2      0x1d14L
1       1    0xdbdcad7
2       1      0x21abL
3       3      0x21abL
4       3      0x21abL
5       1  0x5734a81e2
6       2      0x1d14L
7       0       0xdafL
8       0      0x1d14L
9       4  0x5734a81e2

In [82]: ind = df2.user_id.isin(df1.user_id) & df1.user_id.isin(df2.user_id)

In [83]: ind
Out[83]:
0     True
1    False
2     True
3     True
4     True
5    False
6     True
7     True
8     True
9    False
Name: user_id, dtype: bool

In [84]: df1[ind].append(df2[ind])
Out[84]:
   rating  user_id
0       2  0x21abL
2       1   0xdafL
3       0  0x21abL
4       4  0x1d14L
6       1  0x21abL
7       0   0xdafL
8       4  0x1d14L
0       2  0x1d14L
2       1  0x21abL
3       3  0x21abL
4       3  0x21abL
6       2  0x1d14L
7       0   0xdafL
8       0  0x1d14L

This is essentially the algorithm you described as "clunky", using idiomatic pandas methods. Note the duplicate row indices. Also, note that this won't give you the expected output if df1 and df2 have no overlapping row indices, i.e., if

In [93]: df1.index & df2.index
Out[93]: Int64Index([], dtype='int64')

In fact, it won't give the expected output if their row indices are not equal.

Git workflow and rebase vs merge questions

In your situation I think your partner is correct. What's nice about rebasing is that to the outsider your changes look like they all happened in a clean sequence all by themselves. This means

  • your changes are very easy to review
  • you can continue to make nice, small commits and yet you can make sets of those commits public (by merging into master) all at once
  • when you look at the public master branch you'll see different series of commits for different features by different developers but they won't all be intermixed

You can still continue to push your private development branch to the remote repository for the sake of backup but others should not treat that as a "public" branch since you'll be rebasing. BTW, an easy command for doing this is git push --mirror origin .

The article Packaging software using Git does a fairly nice job explaining the trade offs in merging versus rebasing. It's a little different context but the principals are the same -- it basically comes down to whether your branches are public or private and how you plan to integrate them into the mainline.

How to add time to DateTime in SQL

Try this

SELECT DATEADD(MINUTE,HOW_MANY_MINUTES,TO_WHICH_TIME)

Here MINUTE is constant which indicates er are going to add/subtract minutes from TO_WHICH_TIME specifier. HOW_MANY_MINUTES is the interval by which we need to add minutes, if it is specified negative, time will be subtracted, else would be added to the TO_WHICH_TIME specifier and TO_WHICH_TIME is the original time to which you are adding MINUTE.

Hope this helps.

Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

There are codes for other space characters, and the codes as such work well, but the characters themselves are legacy character. They have been included into character sets only due to their presence in existing character data, rather than for use in new documents. For some combinations of font and browser version, they may cause a generic glyph of unrepresentable character to be shown. For details, check my page about Unicode spaces.

So using CSS is safer and lets you specify any desired amount of spacing, not just the specific widths of fixed-width spaces. If you just want to have added spacing around your h2 elements, as it seems to me, then setting padding on those elements (changing the value of the padding: 0 settings that you already have) should work fine.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

This article here nicely explains it. Essentially, you can look at it as such:

CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'a'   FROM dual UNION ALL
SELECT 'b'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'c'   FROM dual UNION ALL
SELECT 'd'   FROM dual UNION ALL
SELECT 'e'   FROM dual;

SELECT
  v,
  ROW_NUMBER() OVER (ORDER BY v) row_number,
  RANK()       OVER (ORDER BY v) rank,
  DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;

The above will yield:

+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a |          1 |    1 |          1 |
| a |          2 |    1 |          1 |
| a |          3 |    1 |          1 |
| b |          4 |    4 |          2 |
| c |          5 |    5 |          3 |
| c |          6 |    5 |          3 |
| d |          7 |    7 |          4 |
| e |          8 |    8 |          5 |
+---+------------+------+------------+

In words

  • ROW_NUMBER() attributes a unique value to each row
  • RANK() attributes the same row number to the same value, leaving "holes"
  • DENSE_RANK() attributes the same row number to the same value, leaving no "holes"

Determining image file size + dimensions via Javascript?

The only thing you can do is to upload the image to a server and check the image size and dimension using some server side language like C#.

Edit:

Your need can't be done using javascript only.

Display back button on action bar

Try this code, considers it only if you need the back button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //YOUR CODE
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //YOUR CODE
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    onBackPressed();
    return true;
}

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

CodeIgniter : Unable to load the requested file:

"Unable to load the requested file"

Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"

How do you make div elements display inline?

ok, for me :

<style type="text/css">
    div{
        position: relative;
        display: inline-block;
        width:25px;
        height:25px;
    }
</style>
<div>toto</div>
<div>toto</div>
<div>toto</div>

What does "javascript:void(0)" mean?

It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.

You should actually just return false in the onclick event, like so:

<a href="#" onclick="return false;">hello</a>

Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false.

To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.

<a href="backup_page_displaying_image.aspx"
   onclick="return coolImageDisplayFunction();">hello</a>

How can I listen to the form submit event in javascript?

Based on your requirements you can also do the following without libraries like jQuery:

Add this to your head:

window.onload = function () {
    document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
        var isValid = true;
        //validate your elems here
        isValid = false;

        if (!isValid) {
            alert("Please check your fields!");
            return false;
        }
        else {
            //you are good to go
            return true;
        }
    }
}

And your form may still look something like:

    <form id="frmSubmit" action="/Submit">
        <input type="submit" value="Submit" />
    </form>

error: Error parsing XML: not well-formed (invalid token) ...?

I tried everything on my end and ended up with the following.

I had the first line as:

<?xmlversion="1.0"encoding="utf-8"?>

And I was missing two spaces there, and it should be:

<?xml version="1.0" encoding="utf-8"?>

Before the version and before the encoding there should be a space.

plot data from CSV file with matplotlib

According to the docs numpy.loadtxt is

a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

so there are only a few options to handle more complicated files. As mentioned numpy.genfromtxt has more options. So as an example you could use

import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
                     skip_footer=10, names=['x', 'y', 'z'])

to read the data and assign names to the columns (or read a header line from the file with names=True) and than plot it with

ax1.plot(data['x'], data['y'], color='r', label='the data')

I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython or by using an IDE like spider if you prefer to read them rendered as HTML.

Authentication plugin 'caching_sha2_password' cannot be loaded

For those using Docker or Docker Compose, I experienced this error because I didn't set my MySQL image version. Docker will automatically attempt to get the latest version which is 8.

I set MySQL to 5.7 and rebuilt the image and it worked as normal:

version: '2'
services: 
  db:
   image: mysql:5.7

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

This can also happen when you have an older version of your app installed and made changes to the (support) library or the manifest file. Deleting the old applications from your device (Settings --> Application --> <your application> --> Uninstall) will solve the issue then.

How to use "not" in xpath?

None of these answers worked for me for python. I solved by this

a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as

a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like

a[not(@class)]

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.

HTML

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

<input type="text" value="default!" id="myInput" />

JavaScript

$(document).ready(function (){
    $('#myInput').keyup(function(event) {
        // 27 is key code of ESC
        if (event.keyCode == 27) {
            $('#myInput').val('default!');
            // Loose focus on input field
            $('#myInput').blur();
        }
    });
});

Working source can be found here: http://jsfiddle.net/S3N5H/1/

Please let me know if you meant something different, I can adjust the code later.

Ship an application with a database

Shipping the database inside the apk and then copying it to /data/data/... will double the size of the database (1 in apk, 1 in data/data/...), and will increase the apk size (of course). So your database should not be too big.

Normalize data in pandas

This is how you do it column-wise:

[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]

Loop through all the files with a specific extension

as @chepner says in his comment you are comparing $i to a fixed string.

To expand and rectify the situation you should use [[ ]] with the regex operator =~

eg:

for i in $(ls);do
    if [[ $i =~ .*\.java$ ]];then
        echo "I want to do something with the file $i"
    fi
done

the regex to the right of =~ is tested against the value of the left hand operator and should not be quoted, ( quoted will not error but will compare against a fixed string and so will most likely fail"

but @chepner 's answer above using glob is a much more efficient mechanism.

How to work with string fields in a C struct?

You could just use an even simpler typedef:

typedef char *string;

Then, your malloc would look like a usual malloc:

string s = malloc(maxStringLength);

How can I list ALL grants a user received?

Assuming you want to list grants on all objects a particular user has received:

select * from all_tab_privs_recd where grantee = 'your user'

This will not return objects owned by the user. If you need those, use all_tab_privs view instead.

Common elements comparison between 2 lists

I compared each of method that each answer mentioned. At this moment I use python 3.6.3 for this implementation. This is the code that I have used:

import time
import random
from decimal import Decimal


def method1():
    common_elements = [x for x in li1_temp if x in li2_temp]
     print(len(common_elements))


def method2():
    common_elements = (x for x in li1_temp if x in li2_temp)
    print(len(list(common_elements)))


def method3():
    common_elements = set(li1_temp) & set(li2_temp)
    print(len(common_elements))


def method4():
    common_elements = set(li1_temp).intersection(li2_temp)
    print(len(common_elements))


if __name__ == "__main__":
    li1 = []
    li2 = []
    for i in range(100000):
        li1.append(random.randint(0, 10000))
        li2.append(random.randint(0, 10000))

    li1_temp = list(set(li1))
    li2_temp = list(set(li2))

    methods = [method1, method2, method3, method4]
    for m in methods:
        start = time.perf_counter()
        m()
        end = time.perf_counter()
        print(Decimal((end - start)))

If you run this code you can see that if you use list or generator(if you iterate over generator, not just use it. I did this when I forced generator to print length of it), you get nearly same performance. But if you use set you get much better performance. Also if you use intersection method you will get a little bit better performance. the result of each method in my computer is listed bellow:

  1. method1: 0.8150673999999999974619413478649221360683441
  2. method2: 0.8329545000000001531148541289439890533685684
  3. method3: 0.0016547000000000089414697868051007390022277
  4. method4: 0.0010262999999999244948867271887138485908508

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

Check if the file exists using VBA

Use the Office FileDialog object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library and look in the help. This is much better than having people enter full paths.

Here is an example using msoFileDialogFilePicker to allow the user to choose multiple files. You could also use msoFileDialogOpen.

'Note: this is Excel VBA code
Public Sub LogReader()
    Dim Pos As Long
    Dim Dialog As Office.FileDialog
    Set Dialog = Application.FileDialog(msoFileDialogFilePicker)

    With Dialog
        .AllowMultiSelect = True
        .ButtonName = "C&onvert"
        .Filters.Clear
        .Filters.Add "Log Files", "*.log", 1
        .Title = "Convert Logs to Excel Files"
        .InitialFileName = "C:\InitialPath\"
        .InitialView = msoFileDialogViewList

        If .Show Then
            For Pos = 1 To .SelectedItems.Count
                LogRead .SelectedItems.Item(Pos) ' process each file
            Next
        End If
    End With
End Sub

There are lots of options, so you'll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you'll need to find the correct help for the version you're using).

Is there a "do ... while" loop in Ruby?

CAUTION:

The begin <code> end while <condition> is rejected by Ruby's author Matz. Instead he suggests using Kernel#loop, e.g.

loop do 
  # some code here
  break if <condition>
end 

Here's an email exchange in 23 Nov 2005 where Matz states:

|> Don't use it please.  I'm regretting this feature, and I'd like to
|> remove it in the future if it's possible.
|
|I'm surprised.  What do you regret about it?

Because it's hard for users to tell

  begin <code> end while <cond>

works differently from

  <code> while <cond>

RosettaCode wiki has a similar story:

During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop.

What is the difference between compileSdkVersion and targetSdkVersion?

The CompileSdkVersion is the version of the SDK platform your app works with for compilation, etc DURING the development process (you should always use the latest) This is shipped with the API version you are using

enter image description here

You will see this in your build.gradle file:

enter image description here

targetSdkVersion: contains the info your app ships with AFTER the development process to the app store that allows it to TARGET the SPECIFIED version of the Android platform. Depending on the functionality of your app, it can target API versions lower than the current.For instance, you can target API 18 even if the current version is 23.

Take a good look at this official Google page.

How to find all links / pages on a website

Check out linkchecker—it will crawl the site (while obeying robots.txt) and generate a report. From there, you can script up a solution for creating the directory tree.

Can I use Homebrew on Ubuntu?

You can just follow instructions from the Homebrew on Linux docs, but I think it is better to understand what the instructions are trying to achieve.

Understanding the installation steps can save some time


Step 1: Choose location

First of all, it is important to understand that linuxbrew will be installed on the /home directory and not inside /home/your-user (the ~ directory).
(See the reason for that at the end of answer).
Keep this in mind when you run the other steps below.

Step 2: Add linuxbrew binaries to /home :

The installation script will do it for us:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 3: Check that /linuxbrew was added to the relevant location

This can be done by simply navigating to /home.
Notice that the docs are showing it as a one-liner by adding test -d <linuxbrew location> before each command.

(Read more about the test command in here).

Step 4: Export relevant environment variables to terminal

We need to add linuxbrew to PATH and add some more environment variables to the current terminal.

We can just add the following exports to terminal (wait don't do it..):

export PATH="/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin${PATH+:$PATH}";

export HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew";
export HOMEBREW_CELLAR="/home/linuxbrew/.linuxbrew/Cellar";
export HOMEBREW_REPOSITORY="/home/linuxbrew/.linuxbrew/Homebrew";
export MANPATH="/home/linuxbrew/.linuxbrew/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="/home/linuxbrew/.linuxbrew/share/info:${INFOPATH:-}";

Or simply run (If your linuxbrew folder is on other location then /home - change the path):

eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)

(*) Because brew command is not yet identified by the current terminal (this is what we're solving right now) we'll have to specify the full path to the brew binary: /home/linuxbrew/.linuxbrew/bin/brew shellenv

Test this step by:

1 ) Run brew from current terminal to see if it identifies the command.

2 ) Run printenv and check if all environment variables were exported and that you see /home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin on PATH.

Step 5: Ensure step 4 is running on each terminal

We need to add step 4 to ~/.profile (in case of Debian/Ubuntu):

echo "eval \$($(brew --prefix)/bin/brew shellenv)" >> ~/.profile

For CentOS/Fedora/Red Hat - replace ~/.profile with ~/.bash_profile.

Step 6: Ensure that ~/.profile or ~/.bash_profile are being executed when new terminal is opened

If you executed step 5 and failed to run brew from new terminal - add a test command like echo "Hi!" to ~/.profile or ~/.bash_profile.
If you don't see Hi! when you open a new terminal - go to the terminal preferences and ensure that the attribute of 'run command as login shell' is set.
Read more in here.


Why the installation script installs Homebrew to /home/linuxbrew/.linuxbrew - from here:

The installation script installs Homebrew to /home/linuxbrew/.linuxbrew using sudo if possible and in your home directory at ~/.linuxbrew otherwise. Homebrew does not use sudo after installation.
Using /home/linuxbrew/.linuxbrew allows the use of more binary packages (bottles) than installing in your personal home directory.

The prefix /home/linuxbrew/.linuxbrew was chosen so that users without admin access can ask an admin to create a linuxbrew role account and still benefit from precompiled binaries.

If you do not yourself have admin privileges, consider asking your admin staff to create a linuxbrew role account for you with home directory /home/linuxbrew.

How to wait for all threads to finish, using ExecutorService?

ExecutorService.invokeAll() does it for you.

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
List<Callable<?>> tasks; // your tasks
// invokeAll() returns when all tasks are complete
List<Future<?>> futures = taskExecutor.invokeAll(tasks);

stop all instances of node.js server

Windows & GitBash Terminal I needed to use this command inside Windows / Webstorm / GitBash terminal

cmd "/C TASKKILL /IM node.exe /F"

Darken background image on hover

Try following code:

.image {
    background: url('http://cdn1.iconfinder.com/data/icons/round-simple-social-icons/58/facebook.png');
    width: 58px;
    height: 58px;
    opacity:0.2;
}

.image:hover{
    opacity:1;
}

Rotating a Div Element in jQuery

yeah you're not going to have much luck i think. Typically across the 3 drawing methods the major browsers use (Canvas, SVG, VML), text support is poor, I believe. If you want to rotate an image, then it's all good, but if you've got mixed content with formatting and styles, probably not.

Check out RaphaelJS for a cross-browser drawing API.

Git: How to return from 'detached HEAD' state

I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:

git checkout 1.87.1                                    
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

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

  git checkout -b <new-branch-name>

HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'

In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).

git checkout master did not work:

$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...

git checkout master --force (or git checkout master -f) worked:

git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

Python: how can I check whether an object is of type datetime.date?

If you are using freezegun package in tests you may need to have more smart isinstance checks which works well with FakeDate and original Date/Datetime beeing inside with freeze_time context:

def isinstance_date(value):
    """Safe replacement for isinstance date which works smoothly also with Mocked freezetime"""
    import datetime
    if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.today().date()) == type(value):
        return True
    else:
        return False


def isinstance_datetime(value):
    """Safe replacement for isinstance datetime which works smoothly also with Mocked freezetime """
    import datetime
    if isinstance(value, datetime.datetime):
        return True
    elif type(datetime.datetime.now()) == type(value):
        return True
    else:
        return False

and tests to verify the implementation

class TestDateUtils(TestCase):

    def setUp(self):
        self.date_orig = datetime.date(2000, 10, 10)
        self.datetime_orig = datetime.datetime(2000, 10, 10)

        with freeze_time('2001-01-01'):
            self.date_freezed = datetime.date(2002, 10, 10)
            self.datetime_freezed = datetime.datetime(2002, 10, 10)

    def test_isinstance_date(self):
        def check():
            self.assertTrue(isinstance_date(self.date_orig))
            self.assertTrue(isinstance_date(self.date_freezed))
            self.assertFalse(isinstance_date(self.datetime_orig))
            self.assertFalse(isinstance_date(self.datetime_freezed))
            self.assertFalse(isinstance_date(None))

        check()
        with freeze_time('2005-01-01'):
            check()

    def test_isinstance_datetime(self):
        def check():
            self.assertFalse(isinstance_datetime(self.date_orig))
            self.assertFalse(isinstance_datetime(self.date_freezed))
            self.assertTrue(isinstance_datetime(self.datetime_orig))
            self.assertTrue(isinstance_datetime(self.datetime_freezed))
            self.assertFalse(isinstance_datetime(None))

        check()
        with freeze_time('2005-01-01'):
            check()

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

What is the best way to implement constants in Java?

Just avoid using an interface:

public interface MyConstants {
    String CONSTANT_ONE = "foo";
}

public class NeddsConstant implements MyConstants {

}

It is tempting, but violates encapsulation and blurs the distinction of class definitions.

Android Service needs to run always (Never pause or stop)

You can implement startForeground for the service and even if it dies you can restart it by using START_STICKY on startCommand(). Not sure though this is the right implementation.

How to get the mysql table columns data type?

To get data types of all columns:

describe table_name

or just a single column:

describe table_name column_name

How to ignore certain files in Git

You should write something like

*.class

into your .gitignore file.

Find and Replace string in all files recursive using grep and sed

grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

How to bind multiple values to a single WPF TextBlock?

Use a ValueConverter

[ValueConversion(typeof(string), typeof(String))]
public class MyConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return string.Format("{0}:{1}", (string) value, (string) parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {

        return DependencyProperty.UnsetValue;
    }
}

and in the markup

<src:MyConverter x:Key="MyConverter"/>

. . .

<TextBlock Text="{Binding Name, Converter={StaticResource MyConverter Parameter=ID}}" />

How to use Select2 with JSON via Ajax request?

for select2 v4.0.0 slightly different

$(".itemSearch").select2({
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    ajax: {
        url: URL,
        dataType: "json",
        type: "GET",
        data: function (params) {

            var queryParameters = {
                term: params.term
            }
            return queryParameters;
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    }
});

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

UIImage *image = cell.imageView.image;

UIGraphicsBeginImageContext(CGSizeMake(35,35));
// draw scaled image into thumbnail context

[image drawInRect:CGRectMake(5, 5, 35, 35)]; //
UIImage *newThumbnail = UIGraphicsGetImageFromCurrentImageContext();
// pop the context
UIGraphicsEndImageContext();
if(newThumbnail == nil)
{
    NSLog(@"could not scale image");
    cell.imageView.image = image;
}
else
{
    cell.imageView.image = newThumbnail;
}

Could not load file or assembly ... The parameter is incorrect

You can also clear the packages directory and allow NuGet to re-download missing packages

it solved the issue for me

Plotting time in Python with Matplotlib

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)

Android studio logcat nothing to show

Best way to fix some unnecessary changes is to invalidate caches

Go to FILE -> click "INVALIDATE CACHES/RESTART" then a dialog box will pop-up, Select "INVALIDATE CACHES/RESTART" button.

Android studio will automatically restart and rebuild the index.

What Java ORM do you prefer, and why?

Eclipse Link, for many reasons, but notably I feel like it has less bloat than other main stream solutions (at least less in-your-face bloat).

Oh and Eclipse Link has been chosen to be the reference implementation for JPA 2.0

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

http://msdn.microsoft.com/en-us/library/ms175976.aspx

Hope this helps but please let me know if you need more details.

How can I write maven build to add resources to classpath?

A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

For instance, place your property file in a new folder src/main/config, and add the following to your pom:

 <build>
    <resources>
        <resource>
            <directory>src/main/config</directory>
        </resource>
    </resources>
 </build>

From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>my-config.properties</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>

so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

chart.js load totally new data

Not is necesary destroy the chart. Try with this

function removeData(chart) {

        let total = chart.data.labels.length;

        while (total >= 0) {
            chart.data.labels.pop();
            chart.data.datasets[0].data.pop();
            total--;
        }

        chart.update();
    }

Import PEM into Java Key Store

In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9

...

-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

Here is what I did

Split the file into three separate files, so that each one contains just one entry, starting with ---BEGIN.. and ending with ---END.. lines. Lets assume we now have three files: cert1.pem, cert2.pem, and pkey.pem.

Convert pkey.pem into DER format using openssl and the following syntax:

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a passphrase for pkey.pem: ".

If conversion is successful, you will get a new file called pkey.der.

Create a new java keystore and import the private key and the certificates:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(optional) Verify the content of your new key store:

$ keytool -list -keystore mykeystore -storepass password

Keystore type: JKS Keystore provider: SUN

Your keystore contains 3 entries:

  • cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...

  • importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...

  • cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...

(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

Finally register your certificates with HttpsURLConnection if plan to use it:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

Angular 2 http post params and body

Let said our backend looks like this:

public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
}

We have a HttpService like this:

    post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
        return this.http.post<T>(url, body, { headers: headers, params});
    }

Following is how we can pass the body and the notes as parameter: // how to call it

const headers: HttpHeaders = new HttpHeaders({
    'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
});

const bodyData = this.getBodyData(); // get whatever we want to send as body

let params: HttpParams = new HttpParams();
params = params.set('notes', 'Some notes to send');

this.httpService.post<any>(url, bodyData, headers, params);

It worked for me (using angular 7^), I hope is useful for somebody.

Regular Expressions- Match Anything

The 2018 specification provides the s flag (alias: dotAll), so that . will match any character, including linebreaks:

_x000D_
_x000D_
const regExAll = /.*/s; //notice the 's'

let str = `
Everything
    in  this
            string
                    will
                        be
    matched. Including whitespace (even Linebreaks).
`;

console.log(`Match:`, regExAll.test(str)); //true
console.log(`Index Location:`, str.search(regExAll));

let newStr = str.replace(regExAll,"");
console.log(`Replaced with:`,newStr); //Index: 0
_x000D_
_x000D_
_x000D_

Dynamically fill in form values with jQuery

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

Cannot use Server.MapPath

Your project needs to reference assembly System.Web.dll. Server is an object of type HttpServerUtility. Example:

HttpContext.Current.Server.MapPath(path);

Generate unique random numbers between 1 and 100

The best earlier answer is the answer by sje397. You will get as good random numbers as you can get, as quick as possible.

My solution is very similar to his solution. However, sometimes you want the random numbers in random order, and that is why I decided to post an answer. In addition, I provide a general function.

function selectKOutOfN(k, n) {
  if (k>n) throw "k>n";
  var selection = [];
  var sorted = [];
  for (var i = 0; i < k; i++) {
    var rand = Math.floor(Math.random()*(n - i));
    for (var j = 0; j < i; j++) {
      if (sorted[j]<=rand)
        rand++;
      else
        break;
    }
    selection.push(rand);
    sorted.splice(j, 0, rand);
  }
  return selection;
}

alert(selectKOutOfN(8, 100));

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

PHP/MySQL Insert null values

For fields where NULL is acceptable, you could use var_export($var, true) to output the string, integer, or NULL literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.

For example:

mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");

javascript remove "disabled" attribute from html input

Best answer is just removeAttribute

element.removeAttribute("disabled");

can't access mysql from command line mac

I've tried all the solutions from the answers but couldn't get mysql command to work from the terminal, always getting the message

bash: command not found

The solution is to change the .bash_profile, and add the mysql path to .bash_profile

To do so follow these steps: 1. Open a new Terminal window or make sure you are in the home directory 2. Open .bash_profile using

nano .bash_profile

3. Add the following command to add the mysql path

PATH="/usr/local/mysql/bin:${PATH}"
export PATH

4. Press Ctrl+X, then press y and press enter.

The following is how my .bash_profile looks like enter image description here

Set and Get Methods in java?

I don't see a simple answer to the second question (why) here. So here goes.

Let's say you have a public field that gets used very often in your code. Whenever you decide you need to do something extra before you give or set this field you have a problem. You have to create a special getter and setter for this field and change your complete code from using the field directly to using the getter and setters.

Now imagine you are developing a library widely used by many people. When you need to make a change like the above and set direct access of the field to private the code of all the people using this field will break.

Using getters and setters is about future planning of the code, it makes it more flexible. Of course you can use public fields, especially for simple classes that just hold some data. But it's always a good idea to just make the field privately and code a get and set method for it.

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

Reverse a string in Python

def reverse_string(string):
    length = len(string)
    temp = ''
    for i in range(length):
        temp += string[length - i - 1]
    return temp

print(reverse_string('foo')) #prints "oof"

This works by looping through a string and assigning its values in reverse order to another string.

How to monitor Java memory usage?

JavaMelody might be a solution for your need.

Developed for Java EE applications, this tool measure and build report about the real operation of your applications on any environments. It's free and open-source and easy to integrate into applications with some history, no database nor profiling, really lightweight.

JavaScript loop through json array?

your data snippet need to be expanded a little, and it has to be this way to be proper json. notice I just include the array name attribute "item"

{"item":[
{
  "id": "1",
  "msg": "hi",
  "tid": "2013-05-05 23:35",
  "fromWho": "[email protected]"
}, {
  "id": "2",
  "msg": "there",
  "tid": "2013-05-05 23:45",
  "fromWho": "[email protected]"
}]}

your java script is simply

var objCount = json.item.length;
for ( var x=0; x < objCount ; xx++ ) {
    var curitem = json.item[x];
}

What does .class mean in Java?

If there is no instance available then .class syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object. Since, there is no instance of primitive data type, we have to use .class syntax for primitive data types.

    package test;

    public class Test {
       public static void main(String[] args)
       {
          //there is no instance available for class Test, so use Test.class
          System.out.println("Test.class.getName() ::: " + Test.class.getName());

          // Now create an instance of class Test use getClass()
          Test testObj = new Test();
          System.out.println("testObj.getClass().getName() ::: " + testObj.getClass().getName());

          //For primitive type
          System.out.println("boolean.class.getName() ::: " + boolean.class.getName());
          System.out.println("int.class.getName() ::: " + int.class.getName());
          System.out.println("char.class.getName() ::: " + char.class.getName());
          System.out.println("long.class.getName() ::: " + long.class.getName());
       }
    }

How to handle errors with boto3?

As a few others already mentioned, you can catch certain errors using the service client (service_client.exceptions.<ExceptionClass>) or resource (service_resource.meta.client.exceptions.<ExceptionClass>), however it is not well documented (also which exceptions belong to which clients). So here is how to get the complete mapping at time of writing (January 2020) in region EU (Ireland) (eu-west-1):

import boto3, pprint

region_name = 'eu-west-1'
session = boto3.Session(region_name=region_name)
exceptions = {
  service: list(boto3.client('sts').exceptions._code_to_exception)
  for service in session.get_available_services()
}
pprint.pprint(exceptions, width=20000)

Here is a subset of the pretty large document:

{'acm': ['InvalidArnException', 'InvalidDomainValidationOptionsException', 'InvalidStateException', 'InvalidTagException', 'LimitExceededException', 'RequestInProgressException', 'ResourceInUseException', 'ResourceNotFoundException', 'TooManyTagsException'],
 'apigateway': ['BadRequestException', 'ConflictException', 'LimitExceededException', 'NotFoundException', 'ServiceUnavailableException', 'TooManyRequestsException', 'UnauthorizedException'],
 'athena': ['InternalServerException', 'InvalidRequestException', 'TooManyRequestsException'],
 'autoscaling': ['AlreadyExists', 'InvalidNextToken', 'LimitExceeded', 'ResourceContention', 'ResourceInUse', 'ScalingActivityInProgress', 'ServiceLinkedRoleFailure'],
 'cloudformation': ['AlreadyExistsException', 'ChangeSetNotFound', 'CreatedButModifiedException', 'InsufficientCapabilitiesException', 'InvalidChangeSetStatus', 'InvalidOperationException', 'LimitExceededException', 'NameAlreadyExistsException', 'OperationIdAlreadyExistsException', 'OperationInProgressException', 'OperationNotFoundException', 'StackInstanceNotFoundException', 'StackSetNotEmptyException', 'StackSetNotFoundException', 'StaleRequestException', 'TokenAlreadyExistsException'],
 'cloudfront': ['AccessDenied', 'BatchTooLarge', 'CNAMEAlreadyExists', 'CannotChangeImmutablePublicKeyFields', 'CloudFrontOriginAccessIdentityAlreadyExists', 'CloudFrontOriginAccessIdentityInUse', 'DistributionAlreadyExists', 'DistributionNotDisabled', 'FieldLevelEncryptionConfigAlreadyExists', 'FieldLevelEncryptionConfigInUse', 'FieldLevelEncryptionProfileAlreadyExists', 'FieldLevelEncryptionProfileInUse', 'FieldLevelEncryptionProfileSizeExceeded', 'IllegalFieldLevelEncryptionConfigAssociationWithCacheBehavior', 'IllegalUpdate', 'InconsistentQuantities', 'InvalidArgument', 'InvalidDefaultRootObject', 'InvalidErrorCode', 'InvalidForwardCookies', 'InvalidGeoRestrictionParameter', 'InvalidHeadersForS3Origin', 'InvalidIfMatchVersion', 'InvalidLambdaFunctionAssociation', 'InvalidLocationCode', 'InvalidMinimumProtocolVersion', 'InvalidOrigin', 'InvalidOriginAccessIdentity', 'InvalidOriginKeepaliveTimeout', 'InvalidOriginReadTimeout', 'InvalidProtocolSettings', 'InvalidQueryStringParameters', 'InvalidRelativePath', 'InvalidRequiredProtocol', 'InvalidResponseCode', 'InvalidTTLOrder', 'InvalidTagging', 'InvalidViewerCertificate', 'InvalidWebACLId', 'MissingBody', 'NoSuchCloudFrontOriginAccessIdentity', 'NoSuchDistribution', 'NoSuchFieldLevelEncryptionConfig', 'NoSuchFieldLevelEncryptionProfile', 'NoSuchInvalidation', 'NoSuchOrigin', 'NoSuchPublicKey', 'NoSuchResource', 'NoSuchStreamingDistribution', 'PreconditionFailed', 'PublicKeyAlreadyExists', 'PublicKeyInUse', 'QueryArgProfileEmpty', 'StreamingDistributionAlreadyExists', 'StreamingDistributionNotDisabled', 'TooManyCacheBehaviors', 'TooManyCertificates', 'TooManyCloudFrontOriginAccessIdentities', 'TooManyCookieNamesInWhiteList', 'TooManyDistributionCNAMEs', 'TooManyDistributions', 'TooManyDistributionsAssociatedToFieldLevelEncryptionConfig', 'TooManyDistributionsWithLambdaAssociations', 'TooManyFieldLevelEncryptionConfigs', 'TooManyFieldLevelEncryptionContentTypeProfiles', 'TooManyFieldLevelEncryptionEncryptionEntities', 'TooManyFieldLevelEncryptionFieldPatterns', 'TooManyFieldLevelEncryptionProfiles', 'TooManyFieldLevelEncryptionQueryArgProfiles', 'TooManyHeadersInForwardedValues', 'TooManyInvalidationsInProgress', 'TooManyLambdaFunctionAssociations', 'TooManyOriginCustomHeaders', 'TooManyOriginGroupsPerDistribution', 'TooManyOrigins', 'TooManyPublicKeys', 'TooManyQueryStringParameters', 'TooManyStreamingDistributionCNAMEs', 'TooManyStreamingDistributions', 'TooManyTrustedSigners', 'TrustedSignerDoesNotExist'],
 'cloudtrail': ['CloudTrailARNInvalidException', 'CloudTrailAccessNotEnabledException', 'CloudWatchLogsDeliveryUnavailableException', 'InsufficientDependencyServiceAccessPermissionException', 'InsufficientEncryptionPolicyException', 'InsufficientS3BucketPolicyException', 'InsufficientSnsTopicPolicyException', 'InvalidCloudWatchLogsLogGroupArnException', 'InvalidCloudWatchLogsRoleArnException', 'InvalidEventSelectorsException', 'InvalidHomeRegionException', 'InvalidKmsKeyIdException', 'InvalidLookupAttributesException', 'InvalidMaxResultsException', 'InvalidNextTokenException', 'InvalidParameterCombinationException', 'InvalidS3BucketNameException', 'InvalidS3PrefixException', 'InvalidSnsTopicNameException', 'InvalidTagParameterException', 'InvalidTimeRangeException', 'InvalidTokenException', 'InvalidTrailNameException', 'KmsException', 'KmsKeyDisabledException', 'KmsKeyNotFoundException', 'MaximumNumberOfTrailsExceededException', 'NotOrganizationMasterAccountException', 'OperationNotPermittedException', 'OrganizationNotInAllFeaturesModeException', 'OrganizationsNotInUseException', 'ResourceNotFoundException', 'ResourceTypeNotSupportedException', 'S3BucketDoesNotExistException', 'TagsLimitExceededException', 'TrailAlreadyExistsException', 'TrailNotFoundException', 'TrailNotProvidedException', 'UnsupportedOperationException'],
 'cloudwatch': ['InvalidParameterInput', 'ResourceNotFound', 'InternalServiceError', 'InvalidFormat', 'InvalidNextToken', 'InvalidParameterCombination', 'InvalidParameterValue', 'LimitExceeded', 'MissingParameter'],
 'codebuild': ['AccountLimitExceededException', 'InvalidInputException', 'OAuthProviderException', 'ResourceAlreadyExistsException', 'ResourceNotFoundException'],
 'config': ['InsufficientDeliveryPolicyException', 'InsufficientPermissionsException', 'InvalidConfigurationRecorderNameException', 'InvalidDeliveryChannelNameException', 'InvalidLimitException', 'InvalidNextTokenException', 'InvalidParameterValueException', 'InvalidRecordingGroupException', 'InvalidResultTokenException', 'InvalidRoleException', 'InvalidS3KeyPrefixException', 'InvalidSNSTopicARNException', 'InvalidTimeRangeException', 'LastDeliveryChannelDeleteFailedException', 'LimitExceededException', 'MaxNumberOfConfigRulesExceededException', 'MaxNumberOfConfigurationRecordersExceededException', 'MaxNumberOfDeliveryChannelsExceededException', 'MaxNumberOfRetentionConfigurationsExceededException', 'NoAvailableConfigurationRecorderException', 'NoAvailableDeliveryChannelException', 'NoAvailableOrganizationException', 'NoRunningConfigurationRecorderException', 'NoSuchBucketException', 'NoSuchConfigRuleException', 'NoSuchConfigurationAggregatorException', 'NoSuchConfigurationRecorderException', 'NoSuchDeliveryChannelException', 'NoSuchRetentionConfigurationException', 'OrganizationAccessDeniedException', 'OrganizationAllFeaturesNotEnabledException', 'OversizedConfigurationItemException', 'ResourceInUseException', 'ResourceNotDiscoveredException', 'ValidationException'],
 'dynamodb': ['BackupInUseException', 'BackupNotFoundException', 'ConditionalCheckFailedException', 'ContinuousBackupsUnavailableException', 'GlobalTableAlreadyExistsException', 'GlobalTableNotFoundException', 'IdempotentParameterMismatchException', 'IndexNotFoundException', 'InternalServerError', 'InvalidRestoreTimeException', 'ItemCollectionSizeLimitExceededException', 'LimitExceededException', 'PointInTimeRecoveryUnavailableException', 'ProvisionedThroughputExceededException', 'ReplicaAlreadyExistsException', 'ReplicaNotFoundException', 'RequestLimitExceeded', 'ResourceInUseException', 'ResourceNotFoundException', 'TableAlreadyExistsException', 'TableInUseException', 'TableNotFoundException', 'TransactionCanceledException', 'TransactionConflictException', 'TransactionInProgressException'],
 'ec2': [],
 'ecr': ['EmptyUploadException', 'ImageAlreadyExistsException', 'ImageNotFoundException', 'InvalidLayerException', 'InvalidLayerPartException', 'InvalidParameterException', 'InvalidTagParameterException', 'LayerAlreadyExistsException', 'LayerInaccessibleException', 'LayerPartTooSmallException', 'LayersNotFoundException', 'LifecyclePolicyNotFoundException', 'LifecyclePolicyPreviewInProgressException', 'LifecyclePolicyPreviewNotFoundException', 'LimitExceededException', 'RepositoryAlreadyExistsException', 'RepositoryNotEmptyException', 'RepositoryNotFoundException', 'RepositoryPolicyNotFoundException', 'ServerException', 'TooManyTagsException', 'UploadNotFoundException'],
 'ecs': ['AccessDeniedException', 'AttributeLimitExceededException', 'BlockedException', 'ClientException', 'ClusterContainsContainerInstancesException', 'ClusterContainsServicesException', 'ClusterContainsTasksException', 'ClusterNotFoundException', 'InvalidParameterException', 'MissingVersionException', 'NoUpdateAvailableException', 'PlatformTaskDefinitionIncompatibilityException', 'PlatformUnknownException', 'ResourceNotFoundException', 'ServerException', 'ServiceNotActiveException', 'ServiceNotFoundException', 'TargetNotFoundException', 'UnsupportedFeatureException', 'UpdateInProgressException'],
 'efs': ['BadRequest', 'DependencyTimeout', 'FileSystemAlreadyExists', 'FileSystemInUse', 'FileSystemLimitExceeded', 'FileSystemNotFound', 'IncorrectFileSystemLifeCycleState', 'IncorrectMountTargetState', 'InsufficientThroughputCapacity', 'InternalServerError', 'IpAddressInUse', 'MountTargetConflict', 'MountTargetNotFound', 'NetworkInterfaceLimitExceeded', 'NoFreeAddressesInSubnet', 'SecurityGroupLimitExceeded', 'SecurityGroupNotFound', 'SubnetNotFound', 'ThroughputLimitExceeded', 'TooManyRequests', 'UnsupportedAvailabilityZone'],
 'eks': ['ClientException', 'InvalidParameterException', 'InvalidRequestException', 'ResourceInUseException', 'ResourceLimitExceededException', 'ResourceNotFoundException', 'ServerException', 'ServiceUnavailableException', 'UnsupportedAvailabilityZoneException'],
 'elasticache': ['APICallRateForCustomerExceeded', 'AuthorizationAlreadyExists', 'AuthorizationNotFound', 'CacheClusterAlreadyExists', 'CacheClusterNotFound', 'CacheParameterGroupAlreadyExists', 'CacheParameterGroupNotFound', 'CacheParameterGroupQuotaExceeded', 'CacheSecurityGroupAlreadyExists', 'CacheSecurityGroupNotFound', 'QuotaExceeded.CacheSecurityGroup', 'CacheSubnetGroupAlreadyExists', 'CacheSubnetGroupInUse', 'CacheSubnetGroupNotFoundFault', 'CacheSubnetGroupQuotaExceeded', 'CacheSubnetQuotaExceededFault', 'ClusterQuotaForCustomerExceeded', 'InsufficientCacheClusterCapacity', 'InvalidARN', 'InvalidCacheClusterState', 'InvalidCacheParameterGroupState', 'InvalidCacheSecurityGroupState', 'InvalidParameterCombination', 'InvalidParameterValue', 'InvalidReplicationGroupState', 'InvalidSnapshotState', 'InvalidSubnet', 'InvalidVPCNetworkStateFault', 'NoOperationFault', 'NodeGroupNotFoundFault', 'NodeGroupsPerReplicationGroupQuotaExceeded', 'NodeQuotaForClusterExceeded', 'NodeQuotaForCustomerExceeded', 'ReplicationGroupAlreadyExists', 'ReplicationGroupNotFoundFault', 'ReservedCacheNodeAlreadyExists', 'ReservedCacheNodeNotFound', 'ReservedCacheNodeQuotaExceeded', 'ReservedCacheNodesOfferingNotFound', 'ServiceLinkedRoleNotFoundFault', 'SnapshotAlreadyExistsFault', 'SnapshotFeatureNotSupportedFault', 'SnapshotNotFoundFault', 'SnapshotQuotaExceededFault', 'SubnetInUse', 'TagNotFound', 'TagQuotaPerResourceExceeded', 'TestFailoverNotAvailableFault'],
 'elasticbeanstalk': ['CodeBuildNotInServiceRegionException', 'ElasticBeanstalkServiceException', 'InsufficientPrivilegesException', 'InvalidRequestException', 'ManagedActionInvalidStateException', 'OperationInProgressFailure', 'PlatformVersionStillReferencedException', 'ResourceNotFoundException', 'ResourceTypeNotSupportedException', 'S3LocationNotInServiceRegionException', 'S3SubscriptionRequiredException', 'SourceBundleDeletionFailure', 'TooManyApplicationVersionsException', 'TooManyApplicationsException', 'TooManyBucketsException', 'TooManyConfigurationTemplatesException', 'TooManyEnvironmentsException', 'TooManyPlatformsException', 'TooManyTagsException'],
 'elb': ['LoadBalancerNotFound', 'CertificateNotFound', 'DependencyThrottle', 'DuplicateLoadBalancerName', 'DuplicateListener', 'DuplicatePolicyName', 'DuplicateTagKeys', 'InvalidConfigurationRequest', 'InvalidInstance', 'InvalidScheme', 'InvalidSecurityGroup', 'InvalidSubnet', 'ListenerNotFound', 'LoadBalancerAttributeNotFound', 'OperationNotPermitted', 'PolicyNotFound', 'PolicyTypeNotFound', 'SubnetNotFound', 'TooManyLoadBalancers', 'TooManyPolicies', 'TooManyTags', 'UnsupportedProtocol'],
 'emr': ['InternalServerError', 'InternalServerException', 'InvalidRequestException'],
 'es': ['BaseException', 'DisabledOperationException', 'InternalException', 'InvalidTypeException', 'LimitExceededException', 'ResourceAlreadyExistsException', 'ResourceNotFoundException', 'ValidationException'],
 'events': ['ConcurrentModificationException', 'InternalException', 'InvalidEventPatternException', 'LimitExceededException', 'ManagedRuleException', 'PolicyLengthExceededException', 'ResourceNotFoundException'],
 'firehose': ['ConcurrentModificationException', 'InvalidArgumentException', 'LimitExceededException', 'ResourceInUseException', 'ResourceNotFoundException', 'ServiceUnavailableException'],
 'glacier': ['InsufficientCapacityException', 'InvalidParameterValueException', 'LimitExceededException', 'MissingParameterValueException', 'PolicyEnforcedException', 'RequestTimeoutException', 'ResourceNotFoundException', 'ServiceUnavailableException'],
 'glue': ['AccessDeniedException', 'AlreadyExistsException', 'ConcurrentModificationException', 'ConcurrentRunsExceededException', 'ConditionCheckFailureException', 'CrawlerNotRunningException', 'CrawlerRunningException', 'CrawlerStoppingException', 'EntityNotFoundException', 'GlueEncryptionException', 'IdempotentParameterMismatchException', 'InternalServiceException', 'InvalidInputException', 'NoScheduleException', 'OperationTimeoutException', 'ResourceNumberLimitExceededException', 'SchedulerNotRunningException', 'SchedulerRunningException', 'SchedulerTransitioningException', 'ValidationException', 'VersionMismatchException'],
 'iam': ['ConcurrentModification', 'ReportExpired', 'ReportNotPresent', 'ReportInProgress', 'DeleteConflict', 'DuplicateCertificate', 'DuplicateSSHPublicKey', 'EntityAlreadyExists', 'EntityTemporarilyUnmodifiable', 'InvalidAuthenticationCode', 'InvalidCertificate', 'InvalidInput', 'InvalidPublicKey', 'InvalidUserType', 'KeyPairMismatch', 'LimitExceeded', 'MalformedCertificate', 'MalformedPolicyDocument', 'NoSuchEntity', 'PasswordPolicyViolation', 'PolicyEvaluation', 'PolicyNotAttachable', 'ServiceFailure', 'NotSupportedService', 'UnmodifiableEntity', 'UnrecognizedPublicKeyEncoding'],
 'kinesis': ['ExpiredIteratorException', 'ExpiredNextTokenException', 'InternalFailureException', 'InvalidArgumentException', 'KMSAccessDeniedException', 'KMSDisabledException', 'KMSInvalidStateException', 'KMSNotFoundException', 'KMSOptInRequired', 'KMSThrottlingException', 'LimitExceededException', 'ProvisionedThroughputExceededException', 'ResourceInUseException', 'ResourceNotFoundException'],
 'kms': ['AlreadyExistsException', 'CloudHsmClusterInUseException', 'CloudHsmClusterInvalidConfigurationException', 'CloudHsmClusterNotActiveException', 'CloudHsmClusterNotFoundException', 'CloudHsmClusterNotRelatedException', 'CustomKeyStoreHasCMKsException', 'CustomKeyStoreInvalidStateException', 'CustomKeyStoreNameInUseException', 'CustomKeyStoreNotFoundException', 'DependencyTimeoutException', 'DisabledException', 'ExpiredImportTokenException', 'IncorrectKeyMaterialException', 'IncorrectTrustAnchorException', 'InvalidAliasNameException', 'InvalidArnException', 'InvalidCiphertextException', 'InvalidGrantIdException', 'InvalidGrantTokenException', 'InvalidImportTokenException', 'InvalidKeyUsageException', 'InvalidMarkerException', 'KMSInternalException', 'KMSInvalidStateException', 'KeyUnavailableException', 'LimitExceededException', 'MalformedPolicyDocumentException', 'NotFoundException', 'TagException', 'UnsupportedOperationException'],
 'lambda': ['CodeStorageExceededException', 'EC2AccessDeniedException', 'EC2ThrottledException', 'EC2UnexpectedException', 'ENILimitReachedException', 'InvalidParameterValueException', 'InvalidRequestContentException', 'InvalidRuntimeException', 'InvalidSecurityGroupIDException', 'InvalidSubnetIDException', 'InvalidZipFileException', 'KMSAccessDeniedException', 'KMSDisabledException', 'KMSInvalidStateException', 'KMSNotFoundException', 'PolicyLengthExceededException', 'PreconditionFailedException', 'RequestTooLargeException', 'ResourceConflictException', 'ResourceInUseException', 'ResourceNotFoundException', 'ServiceException', 'SubnetIPAddressLimitReachedException', 'TooManyRequestsException', 'UnsupportedMediaTypeException'],
 'logs': ['DataAlreadyAcceptedException', 'InvalidOperationException', 'InvalidParameterException', 'InvalidSequenceTokenException', 'LimitExceededException', 'MalformedQueryException', 'OperationAbortedException', 'ResourceAlreadyExistsException', 'ResourceNotFoundException', 'ServiceUnavailableException', 'UnrecognizedClientException'],
 'neptune': ['AuthorizationNotFound', 'CertificateNotFound', 'DBClusterAlreadyExistsFault', 'DBClusterNotFoundFault', 'DBClusterParameterGroupNotFound', 'DBClusterQuotaExceededFault', 'DBClusterRoleAlreadyExists', 'DBClusterRoleNotFound', 'DBClusterRoleQuotaExceeded', 'DBClusterSnapshotAlreadyExistsFault', 'DBClusterSnapshotNotFoundFault', 'DBInstanceAlreadyExists', 'DBInstanceNotFound', 'DBParameterGroupAlreadyExists', 'DBParameterGroupNotFound', 'DBParameterGroupQuotaExceeded', 'DBSecurityGroupNotFound', 'DBSnapshotAlreadyExists', 'DBSnapshotNotFound', 'DBSubnetGroupAlreadyExists', 'DBSubnetGroupDoesNotCoverEnoughAZs', 'DBSubnetGroupNotFoundFault', 'DBSubnetGroupQuotaExceeded', 'DBSubnetQuotaExceededFault', 'DBUpgradeDependencyFailure', 'DomainNotFoundFault', 'EventSubscriptionQuotaExceeded', 'InstanceQuotaExceeded', 'InsufficientDBClusterCapacityFault', 'InsufficientDBInstanceCapacity', 'InsufficientStorageClusterCapacity', 'InvalidDBClusterSnapshotStateFault', 'InvalidDBClusterStateFault', 'InvalidDBInstanceState', 'InvalidDBParameterGroupState', 'InvalidDBSecurityGroupState', 'InvalidDBSnapshotState', 'InvalidDBSubnetGroupStateFault', 'InvalidDBSubnetStateFault', 'InvalidEventSubscriptionState', 'InvalidRestoreFault', 'InvalidSubnet', 'InvalidVPCNetworkStateFault', 'KMSKeyNotAccessibleFault', 'OptionGroupNotFoundFault', 'ProvisionedIopsNotAvailableInAZFault', 'ResourceNotFoundFault', 'SNSInvalidTopic', 'SNSNoAuthorization', 'SNSTopicArnNotFound', 'SharedSnapshotQuotaExceeded', 'SnapshotQuotaExceeded', 'SourceNotFound', 'StorageQuotaExceeded', 'StorageTypeNotSupported', 'SubnetAlreadyInUse', 'SubscriptionAlreadyExist', 'SubscriptionCategoryNotFound', 'SubscriptionNotFound'],
 'rds': ['AuthorizationAlreadyExists', 'AuthorizationNotFound', 'AuthorizationQuotaExceeded', 'BackupPolicyNotFoundFault', 'CertificateNotFound', 'DBClusterAlreadyExistsFault', 'DBClusterBacktrackNotFoundFault', 'DBClusterEndpointAlreadyExistsFault', 'DBClusterEndpointNotFoundFault', 'DBClusterEndpointQuotaExceededFault', 'DBClusterNotFoundFault', 'DBClusterParameterGroupNotFound', 'DBClusterQuotaExceededFault', 'DBClusterRoleAlreadyExists', 'DBClusterRoleNotFound', 'DBClusterRoleQuotaExceeded', 'DBClusterSnapshotAlreadyExistsFault', 'DBClusterSnapshotNotFoundFault', 'DBInstanceAlreadyExists', 'DBInstanceAutomatedBackupNotFound', 'DBInstanceAutomatedBackupQuotaExceeded', 'DBInstanceNotFound', 'DBInstanceRoleAlreadyExists', 'DBInstanceRoleNotFound', 'DBInstanceRoleQuotaExceeded', 'DBLogFileNotFoundFault', 'DBParameterGroupAlreadyExists', 'DBParameterGroupNotFound', 'DBParameterGroupQuotaExceeded', 'DBSecurityGroupAlreadyExists', 'DBSecurityGroupNotFound', 'DBSecurityGroupNotSupported', 'QuotaExceeded.DBSecurityGroup', 'DBSnapshotAlreadyExists', 'DBSnapshotNotFound', 'DBSubnetGroupAlreadyExists', 'DBSubnetGroupDoesNotCoverEnoughAZs', 'DBSubnetGroupNotAllowedFault', 'DBSubnetGroupNotFoundFault', 'DBSubnetGroupQuotaExceeded', 'DBSubnetQuotaExceededFault', 'DBUpgradeDependencyFailure', 'DomainNotFoundFault', 'EventSubscriptionQuotaExceeded', 'GlobalClusterAlreadyExistsFault', 'GlobalClusterNotFoundFault', 'GlobalClusterQuotaExceededFault', 'InstanceQuotaExceeded', 'InsufficientDBClusterCapacityFault', 'InsufficientDBInstanceCapacity', 'InsufficientStorageClusterCapacity', 'InvalidDBClusterCapacityFault', 'InvalidDBClusterEndpointStateFault', 'InvalidDBClusterSnapshotStateFault', 'InvalidDBClusterStateFault', 'InvalidDBInstanceAutomatedBackupState', 'InvalidDBInstanceState', 'InvalidDBParameterGroupState', 'InvalidDBSecurityGroupState', 'InvalidDBSnapshotState', 'InvalidDBSubnetGroupFault', 'InvalidDBSubnetGroupStateFault', 'InvalidDBSubnetStateFault', 'InvalidEventSubscriptionState', 'InvalidGlobalClusterStateFault', 'InvalidOptionGroupStateFault', 'InvalidRestoreFault', 'InvalidS3BucketFault', 'InvalidSubnet', 'InvalidVPCNetworkStateFault', 'KMSKeyNotAccessibleFault', 'OptionGroupAlreadyExistsFault', 'OptionGroupNotFoundFault', 'OptionGroupQuotaExceededFault', 'PointInTimeRestoreNotEnabled', 'ProvisionedIopsNotAvailableInAZFault', 'ReservedDBInstanceAlreadyExists', 'ReservedDBInstanceNotFound', 'ReservedDBInstanceQuotaExceeded', 'ReservedDBInstancesOfferingNotFound', 'ResourceNotFoundFault', 'SNSInvalidTopic', 'SNSNoAuthorization', 'SNSTopicArnNotFound', 'SharedSnapshotQuotaExceeded', 'SnapshotQuotaExceeded', 'SourceNotFound', 'StorageQuotaExceeded', 'StorageTypeNotSupported', 'SubnetAlreadyInUse', 'SubscriptionAlreadyExist', 'SubscriptionCategoryNotFound', 'SubscriptionNotFound'],
 'route53': ['ConcurrentModification', 'ConflictingDomainExists', 'ConflictingTypes', 'DelegationSetAlreadyCreated', 'DelegationSetAlreadyReusable', 'DelegationSetInUse', 'DelegationSetNotAvailable', 'DelegationSetNotReusable', 'HealthCheckAlreadyExists', 'HealthCheckInUse', 'HealthCheckVersionMismatch', 'HostedZoneAlreadyExists', 'HostedZoneNotEmpty', 'HostedZoneNotFound', 'HostedZoneNotPrivate', 'IncompatibleVersion', 'InsufficientCloudWatchLogsResourcePolicy', 'InvalidArgument', 'InvalidChangeBatch', 'InvalidDomainName', 'InvalidInput', 'InvalidPaginationToken', 'InvalidTrafficPolicyDocument', 'InvalidVPCId', 'LastVPCAssociation', 'LimitsExceeded', 'NoSuchChange', 'NoSuchCloudWatchLogsLogGroup', 'NoSuchDelegationSet', 'NoSuchGeoLocation', 'NoSuchHealthCheck', 'NoSuchHostedZone', 'NoSuchQueryLoggingConfig', 'NoSuchTrafficPolicy', 'NoSuchTrafficPolicyInstance', 'NotAuthorizedException', 'PriorRequestNotComplete', 'PublicZoneVPCAssociation', 'QueryLoggingConfigAlreadyExists', 'ThrottlingException', 'TooManyHealthChecks', 'TooManyHostedZones', 'TooManyTrafficPolicies', 'TooManyTrafficPolicyInstances', 'TooManyTrafficPolicyVersionsForCurrentPolicy', 'TooManyVPCAssociationAuthorizations', 'TrafficPolicyAlreadyExists', 'TrafficPolicyInUse', 'TrafficPolicyInstanceAlreadyExists', 'VPCAssociationAuthorizationNotFound', 'VPCAssociationNotFound'],
 's3': ['BucketAlreadyExists', 'BucketAlreadyOwnedByYou', 'NoSuchBucket', 'NoSuchKey', 'NoSuchUpload', 'ObjectAlreadyInActiveTierError', 'ObjectNotInActiveTierError'],
 'sagemaker': ['ResourceInUse', 'ResourceLimitExceeded', 'ResourceNotFound'],
 'secretsmanager': ['DecryptionFailure', 'EncryptionFailure', 'InternalServiceError', 'InvalidNextTokenException', 'InvalidParameterException', 'InvalidRequestException', 'LimitExceededException', 'MalformedPolicyDocumentException', 'PreconditionNotMetException', 'ResourceExistsException', 'ResourceNotFoundException'],
 'ses': ['AccountSendingPausedException', 'AlreadyExists', 'CannotDelete', 'ConfigurationSetAlreadyExists', 'ConfigurationSetDoesNotExist', 'ConfigurationSetSendingPausedException', 'CustomVerificationEmailInvalidContent', 'CustomVerificationEmailTemplateAlreadyExists', 'CustomVerificationEmailTemplateDoesNotExist', 'EventDestinationAlreadyExists', 'EventDestinationDoesNotExist', 'FromEmailAddressNotVerified', 'InvalidCloudWatchDestination', 'InvalidConfigurationSet', 'InvalidFirehoseDestination', 'InvalidLambdaFunction', 'InvalidPolicy', 'InvalidRenderingParameter', 'InvalidS3Configuration', 'InvalidSNSDestination', 'InvalidSnsTopic', 'InvalidTemplate', 'InvalidTrackingOptions', 'LimitExceeded', 'MailFromDomainNotVerifiedException', 'MessageRejected', 'MissingRenderingAttribute', 'ProductionAccessNotGranted', 'RuleDoesNotExist', 'RuleSetDoesNotExist', 'TemplateDoesNotExist', 'TrackingOptionsAlreadyExistsException', 'TrackingOptionsDoesNotExistException'],
 'sns': ['AuthorizationError', 'EndpointDisabled', 'FilterPolicyLimitExceeded', 'InternalError', 'InvalidParameter', 'ParameterValueInvalid', 'InvalidSecurity', 'KMSAccessDenied', 'KMSDisabled', 'KMSInvalidState', 'KMSNotFound', 'KMSOptInRequired', 'KMSThrottling', 'NotFound', 'PlatformApplicationDisabled', 'SubscriptionLimitExceeded', 'Throttled', 'TopicLimitExceeded'],
 'sqs': ['AWS.SimpleQueueService.BatchEntryIdsNotDistinct', 'AWS.SimpleQueueService.BatchRequestTooLong', 'AWS.SimpleQueueService.EmptyBatchRequest', 'InvalidAttributeName', 'AWS.SimpleQueueService.InvalidBatchEntryId', 'InvalidIdFormat', 'InvalidMessageContents', 'AWS.SimpleQueueService.MessageNotInflight', 'OverLimit', 'AWS.SimpleQueueService.PurgeQueueInProgress', 'AWS.SimpleQueueService.QueueDeletedRecently', 'AWS.SimpleQueueService.NonExistentQueue', 'QueueAlreadyExists', 'ReceiptHandleIsInvalid', 'AWS.SimpleQueueService.TooManyEntriesInBatchRequest', 'AWS.SimpleQueueService.UnsupportedOperation'],
 'ssm': ['AlreadyExistsException', 'AssociatedInstances', 'AssociationAlreadyExists', 'AssociationDoesNotExist', 'AssociationExecutionDoesNotExist', 'AssociationLimitExceeded', 'AssociationVersionLimitExceeded', 'AutomationDefinitionNotFoundException', 'AutomationDefinitionVersionNotFoundException', 'AutomationExecutionLimitExceededException', 'AutomationExecutionNotFoundException', 'AutomationStepNotFoundException', 'ComplianceTypeCountLimitExceededException', 'CustomSchemaCountLimitExceededException', 'DocumentAlreadyExists', 'DocumentLimitExceeded', 'DocumentPermissionLimit', 'DocumentVersionLimitExceeded', 'DoesNotExistException', 'DuplicateDocumentContent', 'DuplicateDocumentVersionName', 'DuplicateInstanceId', 'FeatureNotAvailableException', 'HierarchyLevelLimitExceededException', 'HierarchyTypeMismatchException', 'IdempotentParameterMismatch', 'InternalServerError', 'InvalidActivation', 'InvalidActivationId', 'InvalidAggregatorException', 'InvalidAllowedPatternException', 'InvalidAssociation', 'InvalidAssociationVersion', 'InvalidAutomationExecutionParametersException', 'InvalidAutomationSignalException', 'InvalidAutomationStatusUpdateException', 'InvalidCommandId', 'InvalidDeleteInventoryParametersException', 'InvalidDeletionIdException', 'InvalidDocument', 'InvalidDocumentContent', 'InvalidDocumentOperation', 'InvalidDocumentSchemaVersion', 'InvalidDocumentVersion', 'InvalidFilter', 'InvalidFilterKey', 'InvalidFilterOption', 'InvalidFilterValue', 'InvalidInstanceId', 'InvalidInstanceInformationFilterValue', 'InvalidInventoryGroupException', 'InvalidInventoryItemContextException', 'InvalidInventoryRequestException', 'InvalidItemContentException', 'InvalidKeyId', 'InvalidNextToken', 'InvalidNotificationConfig', 'InvalidOptionException', 'InvalidOutputFolder', 'InvalidOutputLocation', 'InvalidParameters', 'InvalidPermissionType', 'InvalidPluginName', 'InvalidResourceId', 'InvalidResourceType', 'InvalidResultAttributeException', 'InvalidRole', 'InvalidSchedule', 'InvalidTarget', 'InvalidTypeNameException', 'InvalidUpdate', 'InvocationDoesNotExist', 'ItemContentMismatchException', 'ItemSizeLimitExceededException', 'MaxDocumentSizeExceeded', 'ParameterAlreadyExists', 'ParameterLimitExceeded', 'ParameterMaxVersionLimitExceeded', 'ParameterNotFound', 'ParameterPatternMismatchException', 'ParameterVersionLabelLimitExceeded', 'ParameterVersionNotFound', 'ResourceDataSyncAlreadyExistsException', 'ResourceDataSyncCountExceededException', 'ResourceDataSyncInvalidConfigurationException', 'ResourceDataSyncNotFoundException', 'ResourceInUseException', 'ResourceLimitExceededException', 'StatusUnchanged', 'SubTypeCountLimitExceededException', 'TargetInUseException', 'TargetNotConnected', 'TooManyTagsError', 'TooManyUpdates', 'TotalSizeLimitExceededException', 'UnsupportedInventoryItemContextException', 'UnsupportedInventorySchemaVersionException', 'UnsupportedOperatingSystem', 'UnsupportedParameterType', 'UnsupportedPlatformType'],
 'stepfunctions': ['ActivityDoesNotExist', 'ActivityLimitExceeded', 'ActivityWorkerLimitExceeded', 'ExecutionAlreadyExists', 'ExecutionDoesNotExist', 'ExecutionLimitExceeded', 'InvalidArn', 'InvalidDefinition', 'InvalidExecutionInput', 'InvalidName', 'InvalidOutput', 'InvalidToken', 'MissingRequiredParameter', 'ResourceNotFound', 'StateMachineAlreadyExists', 'StateMachineDeleting', 'StateMachineDoesNotExist', 'StateMachineLimitExceeded', 'TaskDoesNotExist', 'TaskTimedOut', 'TooManyTags'],
 'sts': ['ExpiredTokenException', 'IDPCommunicationError', 'IDPRejectedClaim', 'InvalidAuthorizationMessageException', 'InvalidIdentityToken', 'MalformedPolicyDocument', 'PackedPolicyTooLarge', 'RegionDisabledException'],
 'xray': ['InvalidRequestException', 'RuleLimitExceededException', 'ThrottledException']}

How to "add existing frameworks" in Xcode 4?

Follow the screen shots

Go to linked framework and libraries

enter image description here

you are ready to Go!

RequiredIf Conditional Validation Attribute

If you try to use "ModelState.Remove" or "ModelState["Prop"].Errors.Clear()" the "ModelState.IsValid" stil returns false.

Why not just removing the default "Required" Annotation from Model and make your custom validation before the "ModelState.IsValid" on Controller 'Post' action? Like this:

if (!String.IsNullOrEmpty(yourClass.Property1) && String.IsNullOrEmpty(yourClass.dependantProperty))            
            ModelState.AddModelError("dependantProperty", "It´s necessary to select some 'dependant'.");

URL encoding in Android

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

How to show changed file name only with git log?

I stumbled in here looking for a similar answer without the "git log" restriction. The answers here didn't give me what I needed but this did so I'll add it in case others find it useful:

git diff --name-only

You can also couple this with standard commit pointers to see what has changed since a particular commit:

git diff --name-only HEAD~3
git diff --name-only develop
git diff --name-only 5890e37..ebbf4c0

This succinctly provides file names only which is great for scripting. For example:

git diff --name-only develop | while read changed_file; do echo "This changed from the develop version: $changed_file"; done

#OR

git diff --name-only develop | xargs tar cvf changes.tar

Iterate over object attributes in python

For python 3.6

class SomeClass:

    def attr_list(self, should_print=False):

        items = self.__dict__.items()
        if should_print:
            [print(f"attribute: {k}    value: {v}") for k, v in items]

        return items

Mongoose: Find, modify, save

The user parameter of your callback is an array with find. Use findOne instead of find when querying for a single instance.

User.findOne({username: oldUsername}, function (err, user) {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

What is the use of static synchronized method in java?

Suppose there are multiple static synchronized methods (m1, m2, m3, m4) in a class, and suppose one thread is accessing m1, then no other thread at the same time can access any other static synchronized methods.

How to split page into 4 equal parts?

Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.

The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.

As a bonus, text is responsively centered in the quarters.

HTML:

<head>
  <meta charset="utf-8">
  <title>Box model</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <h1 id="title">Title Bar</h1>
  <div id="dividedbox">
    <div class="quarter" id="NW">
      <p>NW</p>
    </div>
    <div class="quarter" id="NE">
      <p>NE</p>
    </div>
    <div class="quarter" id="SE">
      <p>SE</p>
    </div>?
    <div class="quarter" id="SW">
      <p>SW</p>
    </div>
  </div>
</body>

</html>

CSS:

html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%}   /* for div growth */
.quarter {position: absolute; width:50%; height:50%;  /* gives quarters their size */
  display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0;    left:0;     background:orange;     }
#NE { top:0;    left:50%;   background:lightblue;  }
#SW { top:50%;  left:0;     background:green;      }
#SE { top:50%;  left:50%;   background:red;        }

http://jsfiddle.net/og0j2d3v/

Execute PHP function with onclick

Try this it will work fine.

<script>
function echoHello(){
 alert("<?PHP hello(); ?>");
 }
</script>

<?PHP
FUNCTION hello(){
 echo "Call php function on onclick event.";
 }

?>

<button onclick="echoHello()">Say Hello</button>

Android toolbar center title and custom font

To use a custom title in your Toolbar you can add a custom title like :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="5dp"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark">


        <LinearLayout
            android:id="@+id/lnrTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txvHeader"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center"
                android:gravity="center"
                android:ellipsize="end"
                android:maxLines="1"
                android:text="Header"
                android:textColor="@color/white"
                android:textSize="18sp" />


        </LinearLayout>


</android.support.v7.widget.Toolbar>

Java Code:

Toolbar toolbar = findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

if (getSupportActionBar() == null)
    return;

getSupportActionBar().setTitle("Title");

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Call php function from JavaScript

This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.

After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.

You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .

Plain Javascript

In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.

The javascript

// handles the click event for link 1, sends the query
function getOutput() {
  getRequest(
      'myAjax.php', // URL for the PHP file
       drawOutput,  // handle successful request
       drawError    // handle error
  );
  return false;
}  
// handles drawing an error message
function drawError() {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? 
                success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

The HTML

<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>

The PHP

// file myAjax.php
<?php
  echo 'hello world!';
?>

Try it out: http://jsfiddle.net/GRMule/m8CTk/


With a javascript library (jQuery et al)

Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.

Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:

// handles the click event, sends the query
function getOutput() {
   $.ajax({
      url:'myAjax.php',
      complete: function (response) {
          $('#output').html(response.responseText);
      },
      error: function () {
          $('#output').html('Bummer: there was an error!');
      }
  });
  return false;
}

Try it out: http://jsfiddle.net/GRMule/WQXXT/

Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.

If this is all you need to do, write the plain javascript once and you're done.

Documentation

FB OpenGraph og:image not pulling images (possibly https?)

As I accidentally found, transparent blank image comes with response header indicating possible cause of the problem.

  1. Go to the debugger at https://developers.facebook.com/tools/debug/og/object/
  2. Put your URL
  3. In the bottom, facebook shows your "image" (transparent 1x1 GIF)
    1. Image is linked to your original image - no point pressing it
    2. Press right and view image (you'll get something like https://external-ams3-1.xx.fbcdn.net/safe_image.php?d=...&url=...)
  4. Turn on Net tab on firebug/developer tools, refresh page if needed
  5. You'll get x-error-detail response header with explanation

For example, in my case it was Invalid image extension for URL: https://[mydomain]/[myfilename].jpg

The real issue in my case was related to prerender.io.

As it turns out, if image is requested via prerender, it's converted to HTML. Something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head>
<body style="margin: 0px;"><img style="-webkit-user-select: none; cursor: -webkit-zoom-in; " src="https://[yourdomain].com/[yourfilename].jpg" width="1078" height="718"></body>
</html>

It's either bug in prerender itself, or it's supposed to be configured in your proxy to not use prerender for *.jpg requests (even if they are requested by Facebook bot).

It's really hard to notice this, as prerender is used only on certain user-agent headers.

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

This happened to me on Windows 7 and VS 2013 while viewing a project on the browser after build. I only had to close the browser "Chrome" then made sure that the port is not in use in my Network Activities using some utility (Kaspersky) then tried again and worked without any problems.

How do I erase an element from std::vector<> by index?

Erase an element with index :

vec.erase(vec.begin() + index);

Erase an element with value:

vec.erase(find(vec.begin(),vec.end(),value));

Flexbox: how to get divs to fill up 100% of the container width without wrapping?

To prevent the flex items from shrinking, set the flex shrink factor to 0:

The flex shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed. When omitted, it is set to 1.

.boxcontainer .box {
  flex-shrink: 0;
}

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.wrapper {_x000D_
  width: 200px;_x000D_
  background-color: #EEEEEE;_x000D_
  border: 2px solid #DDDDDD;_x000D_
  padding: 1rem;_x000D_
}_x000D_
.boxcontainer {_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  border: 2px solid #BDC3C7;_x000D_
  transition: all 0.4s ease;_x000D_
  display: flex;_x000D_
}_x000D_
.boxcontainer .box {_x000D_
  width: 100%;_x000D_
  padding: 1rem;_x000D_
  flex-shrink: 0;_x000D_
}_x000D_
.boxcontainer .box:first-child {_x000D_
  background-color: #F47983;_x000D_
}_x000D_
.boxcontainer .box:nth-child(2) {_x000D_
  background-color: #FABCC1;_x000D_
}_x000D_
#slidetrigger:checked ~ .wrapper .boxcontainer {_x000D_
  left: -100%;_x000D_
}_x000D_
#overflowtrigger:checked ~ .wrapper {_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<input type="checkbox" id="overflowtrigger" />_x000D_
<label for="overflowtrigger">Hide overflow</label><br />_x000D_
<input type="checkbox" id="slidetrigger" />_x000D_
<label for="slidetrigger">Slide!</label>_x000D_
<div class="wrapper">_x000D_
  <div class="boxcontainer">_x000D_
    <div class="box">_x000D_
      First bunch of content._x000D_
    </div>_x000D_
    <div class="box">_x000D_
      Second load  of content._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Package doesn't exist error in intelliJ

Maven reimport, rebuild and invalidate caches did not work. I solved it by opening a terminal and executing maven clean install in the root folder project. (IntelliJ was opened and I was able to see the IDE updating and triggering reindexation while maven was doing his job)

Convert Map<String,Object> to Map<String,String>

If your Objects are containing of Strings only, then you can do it like this:

Map<String,Object> map = new HashMap<String,Object>(); //Object is containing String
Map<String,String> newMap =new HashMap<String,String>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
       if(entry.getValue() instanceof String){
            newMap.put(entry.getKey(), (String) entry.getValue());
          }
 }

If every Objects are not String then you can replace (String) entry.getValue() into entry.getValue().toString().

Get timezone from DateTime

You could use TimeZoneInfo class

The TimeZone class recognizes local time zone, and can convert times between Coordinated Universal Time (UTC) and local time. A TimeZoneInfo object can represent any time zone, and methods of the TimeZoneInfo class can be used to convert the time in one time zone to the corresponding time in any other time zone. The members of the TimeZoneInfo class support the following operations:

  1. Retrieving a time zone that is already defined by the operating system.

  2. Enumerating the time zones that are available on a system.

  3. Converting times between different time zones.

  4. Creating a new time zone that is not already defined by the operating system.

    Serializing a time zone for later retrieval.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This happened to me when using java sdk. The problem was for me was i wasnt using the session token from assumed role.

Working code example ( in kotlin )

        val identityUserPoolProviderClient = AWSCognitoIdentityProviderClientBuilder
            .standard()
            .withCredentials(AWSStaticCredentialsProvider(BasicSessionCredentials("accessKeyId", ""secretAccessKey, "sessionToken")))
            .build()

How can I save multiple documents concurrently in Mongoose/Node.js?

Newer versions of MongoDB support bulk operations:

var col = db.collection('people');
var batch = col.initializeUnorderedBulkOp();

batch.insert({name: "John"});
batch.insert({name: "Jane"});
batch.insert({name: "Jason"});
batch.insert({name: "Joanne"});

batch.execute(function(err, result) {
    if (err) console.error(err);
    console.log('Inserted ' + result.nInserted + ' row(s).');
}

How to obtain the number of CPUs/cores in Linux from the command line?

Count "core id" per "physical id" method using awk with fall-back on "processor" count if "core id" are not available (like raspberry)

echo $(awk '{ if ($0~/^physical id/) { p=$NF }; if ($0~/^core id/) { cores[p$NF]=p$NF }; if ($0~/processor/) { cpu++ } } END { for (key in cores) { n++ } } END { if (n) {print n} else {print cpu} }' /proc/cpuinfo)

Parsing a CSV file using NodeJS

  • This solution uses csv-parser instead of csv-parse used in some of the answers above.
  • csv-parser came around 2 years after csv-parse.
  • Both of them solve the same purpose, but personally I have found csv-parser better, as it is easy to handle headers through it.

Install the csv-parser first:

npm install csv-parser

So suppose you have a csv-file like this:

NAME, AGE
Lionel Messi, 31
Andres Iniesta, 34

You can perform the required operation as:

const fs = require('fs'); 
const csv = require('csv-parser');

fs.createReadStream(inputFilePath)
.pipe(csv())
.on('data', function(data){
    try {
        console.log("Name is: "+data.NAME);
        console.log("Age is: "+data.AGE);

        //perform the operation
    }
    catch(err) {
        //error handler
    }
})
.on('end',function(){
    //some final operation
});  

For further reading refer

How to execute an SSIS package from .NET?

You can use this Function if you have some variable in the SSIS.

    Package pkg;

    Microsoft.SqlServer.Dts.Runtime.Application app;
    DTSExecResult pkgResults;
    Variables vars;

    app = new Microsoft.SqlServer.Dts.Runtime.Application();
    pkg = app.LoadPackage(" Location of your SSIS package", null);

    vars = pkg.Variables;

    // your variables
    vars["somevariable1"].Value = "yourvariable1";
    vars["somevariable2"].Value = "yourvariable2";

    pkgResults = pkg.Execute(null, vars, null, null, null);

    if (pkgResults == DTSExecResult.Success)
    {
        Console.WriteLine("Package ran successfully");
    }
    else
    {

        Console.WriteLine("Package failed");
    }

Using css transform property in jQuery

If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you. It can be as simple as this : $("#element").transition({x:'90px'}).

Take it from this link : http://ricostacruz.com/jquery.transit/

best way to get the key of a key/value javascript object

Given your Object:

var foo = { 'bar' : 'baz' }

To get bar, use:

Object.keys(foo)[0]

To get baz, use:

foo[Object.keys(foo)[0]]

Assuming a single object

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

How to read a text file directly from Internet using Java?

try something like this

 URL u = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
 InputStream in = u.openStream();

Then use it as any plain old input stream

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

When to use <span> instead <p>?

tag is a block-level element but tag is inline element.Normally we use span tag to style inside block elements.but you don't need to use span tag to inline style.you have to do is; convert block element to inline element using "display: inline"

Single vs double quotes in JSON

Two issues with answers given so far, if , for instance, one streams such non-standard JSON. Because then one might have to interpret an incoming string (not a python dictionary).

Issue 1 - demjson: With Python 3.7.+ and using conda I wasn't able to install demjson since obviosly it does not support Python >3.5 currently. So I need a solution with simpler means, for instance astand/or json.dumps.

Issue 2 - ast & json.dumps: If a JSON is both single quoted and contains a string in at least one value, which in turn contains single quotes, the only simple yet practical solution I have found is applying both:

In the following example we assume line is the incoming JSON string object :

>>> line = str({'abc':'008565','name':'xyz','description':'can control TV\'s and more'})

Step 1: convert the incoming string into a dictionary using ast.literal_eval()
Step 2: apply json.dumps to it for the reliable conversion of keys and values, but without touching the contents of values:

>>> import ast
>>> import json
>>> print(json.dumps(ast.literal_eval(line)))
{"abc": "008565", "name": "xyz", "description": "can control TV's and more"}

json.dumps alone would not do the job because it does not interpret the JSON, but only see the string. Similar for ast.literal_eval(): although it interprets correctly the JSON (dictionary), it does not convert what we need.

What is the purpose of backbone.js?

Is an MVC design pattern on the client side, believe me.. It's gonna save you tons of code, not to mention a more clean and clear code, a more easy to maintain code. Could be a little tricky at first, but believe me it's a great library.

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

How to check internet access on Android? InetAddress never times out

Use method:

private fun isInternetAvailable(context: Context): Boolean {
    (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).run {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return this.getNetworkCapabilities(this.activeNetwork)?.hasCapability(
                NetworkCapabilities.NET_CAPABILITY_INTERNET
            ) ?: false
        } else {
            (@Suppress("DEPRECATION")
            return this.activeNetworkInfo?.isConnected ?: false)
        }
    }
}

And permissions required:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

If list index exists, do X

You can try something like this

list = ["a", "b", "C", "d", "e", "f", "r"]

for i in range(0, len(list), 2):
    print list[i]
    if len(list) % 2 == 1 and  i == len(list)-1:
        break
    print list[i+1];

geom_smooth() what are the methods available?

The method argument specifies the parameter of the smooth statistic. You can see stat_smooth for the list of all possible arguments to the method argument.

Loop code for each file in a directory

Check out the DirectoryIterator class.

From one of the comments on that page:

// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

The recursive version is RecursiveDirectoryIterator.

ERROR: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it

Just restart your wamp server and then run php bin/magento cache:clean

"unrecognized selector sent to instance" error in Objective-C

Another really silly cause of this is having the selector defined in the interface(.h) but not in the implementation(.m) (p.e. typo)

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

There is Mozilla official solution: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

(function() {
    /**Array*/
    // Production steps of ECMA-262, Edition 5, 15.4.4.14
    // Reference: http://es5.github.io/#x15.4.4.14
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(searchElement, fromIndex) {
            var k;
            // 1. Let O be the result of calling ToObject passing
            //    the this value as the argument.
            if (null === this || undefined === this) {
                throw new TypeError('"this" is null or not defined');
            }
            var O = Object(this);
            // 2. Let lenValue be the result of calling the Get
            //    internal method of O with the argument "length".
            // 3. Let len be ToUint32(lenValue).
            var len = O.length >>> 0;
            // 4. If len is 0, return -1.
            if (len === 0) {
                return -1;
            }
            // 5. If argument fromIndex was passed let n be
            //    ToInteger(fromIndex); else let n be 0.
            var n = +fromIndex || 0;
            if (Math.abs(n) === Infinity) {
                n = 0;
            }
            // 6. If n >= len, return -1.
            if (n >= len) {
                return -1;
            }
            // 7. If n >= 0, then Let k be n.
            // 8. Else, n<0, Let k be len - abs(n).
            //    If k is less than 0, then let k be 0.
            k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
            // 9. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ToString(k).
                //   This is implicit for LHS operands of the in operator
                // b. Let kPresent be the result of calling the
                //    HasProperty internal method of O with argument Pk.
                //   This step can be combined with c
                // c. If kPresent is true, then
                //    i.  Let elementK be the result of calling the Get
                //        internal method of O with the argument ToString(k).
                //   ii.  Let same be the result of applying the
                //        Strict Equality Comparison Algorithm to
                //        searchElement and elementK.
                //  iii.  If same is true, return k.
                if (k in O && O[k] === searchElement) {
                    return k;
                }
                k++;
            }
            return -1;
        };
    }
})();

Range of values in C Int and Long 32 - 64 bits

In C and C++ you have these least requirements (i.e actual implementations can have larger magnitudes)

signed char: -2^07+1 to +2^07-1
short:       -2^15+1 to +2^15-1
int:         -2^15+1 to +2^15-1
long:        -2^31+1 to +2^31-1
long long:   -2^63+1 to +2^63-1

Now, on particular implementations, you have a variety of bit ranges. The wikipedia article describes this nicely.

What is (x & 1) and (x >>= 1)?

It is similar to x = (x >> 1).

(operand1)(operator)=(operand2)  implies(=>)  (operand1)=(operand1)(operator)(operand2) 

It shifts the binary value of x by one to the right.

E.g.

int x=3;    // binary form (011) 
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
            // x=1, binary form (001)

Decorators with parameters?

In my instance, I decided to solve this via a one-line lambda to create a new decorator function:

def finished_message(function, message="Finished!"):

    def wrapper(*args, **kwargs):
        output = function(*args,**kwargs)
        print(message)
        return output

    return wrapper

@finished_message
def func():
    pass

my_finished_message = lambda f: finished_message(f, "All Done!")

@my_finished_message
def my_func():
    pass

if __name__ == '__main__':
    func()
    my_func()

When executed, this prints:

Finished!
All Done!

Perhaps not as extensible as other solutions, but worked for me.

Converting a String to a List of Words?

This is from my attempt on a coding challenge that can't use regex,

outputList = "".join((c if c.isalnum() or c=="'" else ' ') for c in inputStr ).split(' ')

The role of apostrophe seems interesting.

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

It can be resolved as follows:

  1. Go to Project properties.

  2. Then 'Java Compiler' -> Check the box ('Enable project specific settings')

  3. Change the compiler compliance level to '5.0' & click ok.

Do rebuild. It will be resolved.

Also, click the checkbox for "Use default compliance settings".

Cannot set content-type to 'application/json' in jQuery.ajax

Hi These two lines worked for me.

contentType:"application/json; charset=utf-8", dataType:"json"

 $.ajax({
            type: "POST",
            url: "/v1/candidates",
            data: obj,
            **contentType:"application/json; charset=utf-8",
            dataType:"json",**
            success: function (data) {
                table.row.add([
                    data.name, data.title
                ]).draw(false);
            }

Thanks, Prashant

Clear screen in shell

Rather than importing all of curses or shelling out just to get one control character, you can simply use (on Linux/macOS):

print(chr(27) + "[2J")

(Source: Clear terminal in Python)

Twitter Bootstrap 3 Sticky Footer

The push div should go right after the wrap, NOT within.. just like this

<div id="wrap">
  *content goes here*
</div>

<div id="push">
</div>

<div id="footer">
  <div class="container credit">
  </div>
  <div class="container">
    <p class="muted credit">© Your Page 2013</p>
  </div>
</div>

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

How to add parameters to an external data query in Excel which can't be displayed graphically?

Easy Workaround (no VBA required)

  1. Right Click Table, expand "Table" context manu, select "External Data Properties"
  2. Click button "Connection Properties" (labelled in tooltip only)
  3. Go-to Tab "Definition"

From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.

I keep getting "Uncaught SyntaxError: Unexpected token o"

SyntaxError: Unexpected token o in JSON

This also happens when you forget to use the await keyword for a method that returns JSON data.

For example:

async function returnJSONData()
{
   return "{\"prop\": 2}";
}

var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);

will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.

To fix just add await as you're supposed to:

var json_str = await returnJSONData();

This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.

How to get all Errors from ASP.Net MVC modelState?

Anybody looking for asp.net core 3.1. Slightly updated than the above answer. I found that this is what [ApiController] returns

 Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();

                foreach (KeyValuePair<string, ModelStateEntry> kvp in ViewData.ModelState)
                {
                    string key = kvp.Key;
                    ModelStateEntry entry = kvp.Value;

                    if (entry.Errors.Count > 0)
                    {
                        List<string> errorList = new List<string>();
                        foreach (ModelError error in entry.Errors)
                        {
                            errorList.Add(error.ErrorMessage);
                        }

                        errors[key] = errorList;
                    }
                }

                return  new JsonResult(new {Errors = errors});

how to get selected row value in the KendoUI

If you want to select particular element use below code

var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    scan.useDelimiter("/");
    // Printing the tokenized Strings
    while(scan.hasNext()){
        System.out.println(scan.next());
    }
    // closing the scanner stream
    scan.close();
}

Prints this output:

Anna Mills
Female
18