Programs & Examples On #Graphing

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):

    bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
    bbox = mtransforms.Bbox.union(bboxes)
    bottom = bbox.y0
    x, y = self.label.get_position()
    self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))

You can set the label position independently of the ticks by using:

    ax.xaxis.set_label_coords(x0, y0)

that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.

How to label scatterplot points by name?

For all those who don't have the option in Excel (like me), there is a macro which works and is explained here: https://www.get-digital-help.com/2015/08/03/custom-data-labels-in-x-y-scatter-chart/ Very useful

Replace line break characters with <br /> in ASP.NET MVC Razor view

Applying the DRY principle to Omar's solution, here's an HTML Helper extension:

using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace System.Web.Mvc.Html {
    public static class MyHtmlHelpers {
        public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
            return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
        }
    }
}

Usage (with improved regex):

@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "<br />")

This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.


My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

I was never able to get any of these answers to work for me, but this is the command that I used to make it work for me. This way you don't need to use install_name_tool every time you update your mysql

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

How do I increase the capacity of the Eclipse output console?

Open the Windows > Preferences menu.

Expand the Run/Debug > Console preferences.

Set the Console buffer size (characters) to something much bigger. 2147383647 / ~2GB is the upper limit (or 1000000 / ~1MB in older releases). Or just uncheck the Limit console output.

What is use of c_str function In c++

c_str returns a const char* that points to a null-terminated string (i.e. a C-style string). It is useful when you want to pass the "contents"¹ of an std::string to a function that expects to work with a C-style string.

For example, consider this code:

std::string str("Hello world!");
int pos1 = str.find_first_of('w');

int pos2 = strchr(str.c_str(), 'w') - str.c_str();

if (pos1 == pos2) {
    printf("Both ways give the same result.\n");
}

See it in action.

Notes:

¹ This is not entirely true because an std::string (unlike a C string) can contain the \0 character. If it does, the code that receives the return value of c_str() will be fooled into thinking that the string is shorter than it really is, since it will interpret \0 as the end of the string.

How to create empty text file from a batch file?

Techniques I gathered from other answers:

Makes a 0 byte file a very clear, backward-compatible way:

type nul >EmptyFile.txt

idea via: anonymous, Danny Backett, possibly others, myself inspired by JdeBP's work

A 0 byte file another way, it's backward-compatible-looking:

REM. >EmptyFile.txt

idea via: Johannes

A 0 byte file 3rd way backward-compatible-looking, too:

echo. 2>EmptyFile.txt

idea via: TheSmurf

A 0 byte file the systematic way probably available since Windows 2000:

fsutil file createnew EmptyFile.txt 0

idea via: Emm

A 0 bytes file overwriting readonly files

ATTRIB -R filename.ext>NUL
(CD.>filename.ext)2>NUL

idea via: copyitright

A single newline (2 bytes: 0x0D 0x0A in hex notation, alternatively written as \r\n):

echo.>AlmostEmptyFile.txt

Note: no space between echo, . and >.

idea via: How can you echo a newline in batch files?


edit It seems that any invalid command redirected to a file would create an empty file. heh, a feature! compatibility: uknown

TheInvisibleFeature <nul >EmptyFile.txt

A 0 bytes file: invalid command/ with a random name (compatibility: uknown):

%RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt

via: great source for random by Hung Huynh

edit 2 Andriy M points out the probably most amusing/provoking way to achieve this via invalid command

A 0 bytes file: invalid command/ the funky way (compatibility: unknown)

*>EmptyFile.txt

idea via: Andriy M

A 0 bytes file 4th-coming way:

break > file.txt

idea via: foxidrive thanks to comment of Double Gras!

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Upgrading React version and it's dependencies by reading package.json

Yes, you can use Yarn or NPM to edit your package.json.

yarn upgrade [package | package@tag | package@version | @scope/]... [--ignore-engines] [--pattern]

Something like:

yarn upgrade react@^16.0.0

Then I'd see what warns or errors out and then run yarn upgrade [package]. No need to edit the file manually. Can do everything from the CLI.

Or just run yarn upgrade to update all packages to latest, probably a bad idea for a large project. APIs may change, things may break.

Alternatively, with NPM run npm outdated to see what packages will be affected. Then

npm update

https://yarnpkg.com/lang/en/docs/cli/upgrade/

https://docs.npmjs.com/getting-started/updating-local-packages

How do I get rid of an element's offset using CSS?

define margin and padding for the element is facing the problem:

#element_id {margin: 0; padding: 0}  

and see if problem exists. IE renders the page with to more unwanted inheritance. you should stop it from doing so.

missing private key in the distribution certificate on keychain

Check whether you are using Login or not to add the certificates, if you are checking in System at top left hand side then we wont be able to see it.

So drag and drop the .cer into login then check you are able to get the private key or not.

How does one sum only those rows in excel not filtered out?

If you aren't using an auto-filter (i.e. you have manually hidden rows), you will need to use the AGGREGATE function instead of SUBTOTAL.

How to get the first word of a sentence in PHP?

public function getStringFirstAlphabet($string){
    $data='';
    $string=explode(' ', $string);
    $i=0;
    foreach ($string as $key => $value) {
        $data.=$value[$i];
    }
    return $data;
}

angular2 manually firing click event on particular element

I also wanted similar functionality where I have a File Input Control with display:none and a Button control where I wanted to trigger click event of File Input Control when I click on the button, below is the code to do so

<input type="button" (click)="fileInput.click()" class="btn btn-primary" value="Add From File">
<input type="file" style="display:none;" #fileInput/>

as simple as that and it's working flawlessly...

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
}
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
if(file_exists($filePath)){
    unlink($filePath);
}
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */
fclose($fp);

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
set_time_limit(0);
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

Sizing elements to percentage of screen width/height

There are several possibilities:

1- The first one is the use of the MediaQuery :

Code :

MediaQuery.of(context).size.width //to get the width of screen
MediaQuery.of(context).size.height //to get height of screen

Example of use :

Container(
        color: Colors.yellow,
        height: MediaQuery.of(context).size.height * 0.65,
        width: MediaQuery.of(context).size.width,
      )

Output :

enter image description here

2- The use of FractionallySizedBox

Creates a widget that sizes its child to a fraction of the total available space.

Example :

FractionallySizedBox(
           widthFactor: 0.65, // between 0 and 1 
           heightFactor: 1.0,
           child:Container(color: Colors.red
           ,),
         )

Output :

enter image description here

3- The use of other widgets such as Expanded , Flexible and AspectRatio and more .

HTML/CSS font color vs span style

1st preference external style sheet.

<span class="myClass">test</span>

css

.myClass
{
color:red;
}

2nd preference inline style

<span style="color:red">test</span>

<font> as mentioned is deprecated.

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

Objects inside objects in javascript

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};

then:

pause_menu.pause_button.someProperty //evaluates to "prop1"

etc etc.

Convert decimal to binary in python

all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)

>>> bin(10)
'0b1010'
>>> 0b1010
10

How To Run PHP From Windows Command Line in WAMPServer

If you want to just run a quick code snippet you can use the -r option:

php -r "echo 'hi';"

-r allows to run code without using script tags <?..?>

Disable all dialog boxes in Excel while running VB script?

In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:

DoCmd.SetWarnings False

After running all the updates, the last step in my VBA script is:

DoCmd.SetWarnings True

Hope this helps.

How can I stop Chrome from going into debug mode?

If you were unfamiliar with the tools, it was likely that at some point while in the debugger you toggled a setting that was causing the debugger to stop the application.

I suggest you "Disable all break points":

Enter image description here

Source:

https://javascript.info/debugging-chrome

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

I ran into this problem with my new Nexus 4 and an APK built with Adobe AIR. I already had android:installLocation="preferExternal" in my manifest. I noticed I was also calling adb install with the -s option (Install package on the shared mass storage such as sdcard.) which seemed like overkill.

Removing the -s flag from adb install fixed the issue for me.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Sometimes, if you have opened two windows of Android Studio, and when you try to compile, this issue might happen. For me, when I was compiling a backed Google Cloud Endpoint module which was not embedded in a project, rather shared among different Android Studio projects, and when there is more than once instance open, this error use to spring up for me. But as soon as you close other windows, everything will be fine. Sometimes, you might have to restart Android Studio altogether.

iterating over and removing from a map

Set s=map.entrySet();
Iterator iter = s.iterator();

while (iter.hasNext()) {
    Map.Entry entry =(Map.Entry)iter.next();

    if("value you need to remove".equals(entry.getKey())) {
         map.remove();
    }
}

Overloading operators in typedef structs (c++)

The breakdown of your declaration and its members is somewhat littered:

Remove the typedef

The typedef is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos as-written, which is core to your current compilation failure.

Change this:

typedef struct {....} pos;

To this:

struct pos { ... };

Remove extraneous inlines

You're both declaring and defining your member operators within the class definition itself. The inline keyword is not needed so long as your implementations remain in their current location (the class definition)


Return references to *this where appropriate

This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:

a = b = c;

This assigns c to b, and the resulting value b is then assigned to a. This is not equivalent to the following code, contrary to what you may think:

a = c;
b = c;

Therefore, your assignment operator should be implemented as such:

pos& operator =(const pos& a)
{
    x = a.x;
    y = a.y;
    return *this;
}

Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)

Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:

pos& operator=(pos a) // by-value param invokes class copy-ctor
{
    this->swap(a);
    return *this;
}

Then a swap method is implemented:

void pos::swap(pos& obj)
{
    // TODO: swap object guts with obj
}

You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.


Pass objects by const reference when appropriate

All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:

Change this:

bool operator==(pos a) const{
    if(a.x==x && a.y== y)return true;
    else return false;
}

To this: (also simplified)

bool operator==(const pos& a) const
{
    return (x == a.x && y == a.y);
}

No copies of anything are made, resulting in more efficient code.


Finally, in answering your question, what is the difference between a member function or operator declared as const and one that is not?

A const member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const member functions can be invoked against const objects, or const references and pointers. For example, your operator +() does not modify your local object and thus should be declared as const. Your operator =() clearly modifies the local object, and therefore the operator should not be const.


Summary

struct pos
{
    int x;
    int y;

    // default + parameterized constructor
    pos(int x=0, int y=0) 
        : x(x), y(y)
    {
    }

    // assignment operator modifies object, therefore non-const
    pos& operator=(const pos& a)
    {
        x=a.x;
        y=a.y;
        return *this;
    }

    // addop. doesn't modify object. therefore const.
    pos operator+(const pos& a) const
    {
        return pos(a.x+x, a.y+y);
    }

    // equality comparison. doesn't modify object. therefore const.
    bool operator==(const pos& a) const
    {
        return (x == a.x && y == a.y);
    }
};

EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:

a = b = c;

Is equivalent to this:

b = c;
a = b;

And that this does not always equate to this:

a = c;
b = c;

Sample code:

#include <iostream>
#include <string>
using namespace std;

struct obj
{
    std::string name;
    int value;

    obj(const std::string& name, int value)
        : name(name), value(value)
    {
    }

    obj& operator =(const obj& o)
    {
        cout << name << " = " << o.name << endl;
        value = (o.value+1); // note: our value is one more than the rhs.
        return *this;
    }    
};

int main(int argc, char *argv[])
{

    obj a("a", 1), b("b", 2), c("c", 3);

    a = b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    a = c;
    b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    return 0;
}

Output

b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3

Check for special characters (/*-+_@&$#%) in a string?

String test_string = "tesintg#$234524@#";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
  // Good-to-go
}

An example can be found here: http://ideone.com/B1HxA

Wget output document and headers to STDOUT

This worked for me for printing response with header:

wget --server-response http://www.example.com/

How to stop BackgroundWorker correctly

I agree with guys. But sometimes you have to add more things.

IE

1) Add this worker.WorkerSupportsCancellation = true;

2) Add to you class some method to do the following things

public void KillMe()
{
   worker.CancelAsync();
   worker.Dispose();
   worker = null;
   GC.Collect();
}

So before close your application your have to call this method.

3) Probably you can Dispose, null all variables and timers which are inside of the BackgroundWorker.

How do I use brew installed Python as the default Python?

Quick fix:

  1. Open /etc/paths
  2. Change the order of the lines (highest priority on top)

In my case /etc/paths looks like:

/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin

If you want to know more about paths in OSX I found this article quite useful:

http://muttsnutts.github.com/blog/2011/09/12/manage-path-on-mac-os-x-lion/

A Simple, 2d cross-platform graphics library for c or c++?

Heavy-weight:

  • GTK
  • QT
  • WxWidgets

Lightweight:

  • FLTK
  • Fox
  • Tk
  • Lua IUP
  • Ultimate++
  • dlib

Drawing frameworks without GUI widgets:

  • SDL
  • Cairo

Is there a way I can retrieve sa password in sql server 2005

Granted you have administrative Windows privileges on the server, another option would be to start SQL Server in Single User Mode, using the Startup parameter "-m". Doing this, you can login using SQLCMD, create a new user and give it sysadmin privileges. Finally, you have to disable Single User Mode, login to SSMS using your new user, and go to Segurity/Logins and change "sa" user password.

You can check this post: http://v-consult.be/2011/05/26/recover-sa-password-microsoft-sql-server-2008-r2/

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

How can you debug a CORS request with cURL?

Updated answer that covers most cases

curl -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost" --head http://www.example.com/
  1. Replace http://www.example.com/ with URL you want to test.
  2. If response includes Access-Control-Allow-* then your resource supports CORS.

Rationale for alternative answer

I google this question every now and then and the accepted answer is never what I need. First it prints response body which is a lot of text. Adding --head outputs only headers. Second when testing S3 URLs we need to provide additional header -H "Access-Control-Request-Method: GET".

Hope this will save time.

How do I change the UUID of a virtual disk?

Same solution as @Al3x for Windows x64, in cmd.exe:

cd %programfiles%\Oracle\VirtualBox

VBoxManage internalcommands sethduuid "full/path/to/.vdi"

This randomizes the UUID of the disk. Pro tip: Right click the .vdi file while holding shift and select "Copy as path" to obtain "full/path/to/.vdi" and enable quick edit in cmd.exe, then right click to paste.

Android read text raw resource file

Here is an implementation in Kotlin

    try {
        val inputStream: InputStream = this.getResources().openRawResource(R.raw.**)
        val inputStreamReader = InputStreamReader(inputStream)
        val sb = StringBuilder()
        var line: String?
        val br = BufferedReader(inputStreamReader)
        line = br.readLine()
        while (line != null) {
            sb.append(line)
            line = br.readLine()
        }
        br.close()

        var content : String = sb.toString()
        Log.d(TAG, content)
    } catch (e:Exception){
        Log.d(TAG, e.toString())
    }

IOError: [Errno 32] Broken pipe: Python

I know this is not the "proper" way to do it, but if you are simply interested in getting rid of the error message, you could try this workaround:

python your_python_code.py 2> /dev/null | other_command

How do you post to an iframe?

If you want to change inputs in an iframe then submit the form from that iframe, do this

...
var el = document.getElementById('targetFrame');

var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below

if (frame_win) {
  doc = (window.contentDocument || window.document);
}

if (doc) {
  doc.forms[0].someInputName.value = someValue;
  ...
  doc.forms[0].submit();
}
...

Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

limit text length in php and provide 'Read more' link

Basically, you need to integrate a word limiter (e.g. something like this) and use something like shadowbox. Your read more link should link to a PHP script that displays the entire article. Just setup Shadowbox on those links and you're set. (See instructions on their site. Its easy.)

Vim clear last search highlighting

This will clear the search highlight after updatetime milliseconds of inactivity.

updatetime defaults to 4000ms or 4s but I set mine to 10s. It is important to note that updatetime does more than just this so read the docs before you change it.

function! SearchHlClear()
    let @/ = ''
endfunction
augroup searchhighlight
    autocmd!
    autocmd CursorHold,CursorHoldI * call SearchHlClear()
augroup END

Which SchemaType in Mongoose is Best for Timestamp?

The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

You tried to do a.setText(a1). a1 is an int value, but setText() requires a string value. For this reason you need use String.valueOf(a1) to pass the value of a1 as a String and not as an int to a.setText(), like so:

a.setText(String.valueOf(a1))

that was the exact solution to the problem with my case.

Adding a leading zero to some values in column in MySQL

A previous answer using LPAD() is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.

UPDATE
    mytable
SET
    mycolumn = CONCAT(
        REPEAT(
            "0",
            8 - LENGTH(mycolumn)
        ),
        mycolumn
    )
WHERE
    LENGTH(mycolumn) < 8;

python - checking odd/even numbers and changing outputs on number size

Simple but yet fast:

>>> def is_odd(a):
...     return bool(a - ((a>>1)<<1))
...
>>> print(is_odd(13))
True
>>> print(is_odd(12))
False
>>>

Or even simpler:

>>> def is_odd(a):
...   return bool(a & 1)

How to format date in angularjs

Ok the issue it seems to come from this line:
https://github.com/angular-ui/ui-date/blob/master/src/date.js#L106.

Actually this line it's the binding with jQuery UI which it should be the place to inject the data format.

As you can see in var opts there is no property dateFormat with the value from ng-date-format as you could espect.

Anyway the directive has a constant called uiDateConfig to add properties to opts.

The flexible solution (recommended):

From here you can see you can insert some options injecting in the directive a controller variable with the jquery ui options.

<input ui-date="dateOptions" ui-date-format="mm/dd/yyyy" ng-model="valueofdate" />

myAppModule.controller('MyController', function($scope) {
    $scope.dateOptions = {
        dateFormat: "dd-M-yy"
    };
});

The hardcoded solution:

If you don't want to repeat this procedure all the time change the value of uiDateConfig in date.js to:

.constant('uiDateConfig', { dateFormat: "dd-M-yy" })

Is there a C# String.Format() equivalent in JavaScript?

I created it a long time ago, related question

String.Format = function (b) {
    var a = arguments;
    return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
        if (b.substring(0, 2) == "{{") return b;
        var c = parseInt(b.match(/\d/)[0]);
        return a[c + 1]
    })
};

Get visible items in RecyclerView

You can use recyclerView.getChildAt() to get each visible child, and setting some tag convertview.setTag(index) on these view in adapter code will help you to relate it with adapter data.

What are the obj and bin folders (created by Visual Studio) used for?

One interesting fact about the obj directory: If you have publishing set up in a web project, the files that will be published are staged to obj\Release\Package\PackageTmp. If you want to publish the files yourself rather than use the integrated VS feature, you can grab the files that you actually need to deploy here, rather than pick through all the digital debris in the bin directory.

How to sort a Collection<T>?

You have two basic options provided by java.util.Collections:

Depending on what the Collection is, you can also look at SortedSet or SortedMap.

Alter a SQL server function to accept new optional parameter

The way to keep SELECT dbo.fCalculateEstimateDate(647) call working is:

ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100)  AS
   Declare @Result varchar(100)
   SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
   Return @Result
Begin
End

CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100)  AS
Begin
  <Function Body>
End

How to load all the images from one of my folder into my web page, using Jquery/Javascript

If interested in doing this without jQuery - here's a pure JS variant (from here) of the answer currently most upvoted:

var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
  if (xhr.status === 200) {
    var elements = xhr.response.getElementsByTagName("a");
    for (x of elements) {
      if ( x.href.match(/\.(jpe?g|png|gif)$/) ) { 
          let img = document.createElement("img");
          img.src = x.href;
          document.body.appendChild(img);
      } 
    };
  } 
  else {
    alert('Request failed. Returned status of ' + xhr.status);
  }
}
xhr.send()

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I had the same on my project.

I tried " super.setIntegerProperty("loadUrlTimeoutValue", 70000); " but to no avail.

I ensured all files were linked properly [ CSS, JS files etc ], validated the HTML using w3c validator [ http://validator.w3.org/#validate_by_upload ] , and cleaned the project [ Project -> Clean ]

It now loads and executes without the same error.

Hope this helps

Binding IIS Express to an IP Address

I think you can.

To do this you need to edit applicationhost.config file manually (edit bindingInformation '<ip-address>:<port>:<host-name>')

To start iisexpress, you need administrator privileges

Java List.contains(Object with field value equal to x)

If you need to perform this List.contains(Object with field value equal to x) repeatedly, a simple and efficient workaround would be:

List<field obj type> fieldOfInterestValues = new ArrayList<field obj type>;
for(Object obj : List) {
    fieldOfInterestValues.add(obj.getFieldOfInterest());
}

Then the List.contains(Object with field value equal to x) would be have the same result as fieldOfInterestValues.contains(x);

Pandas aggregate count distinct

How about either of:

>>> df
         date  duration user_id
0  2013-04-01        30    0001
1  2013-04-01        15    0001
2  2013-04-01        20    0002
3  2013-04-02        15    0002
4  2013-04-02        30    0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1

Maximum length for MySQL type text

Type       | Approx. Length     | Exact Max. Length Allowed
-----------------------------------------------------------
TINYTEXT   | 256 Bytes          |           255 characters
TEXT       |  64 Kilobytes      |        65,535 characters
MEDIUMTEXT |  16 Megabytes      |    16,777,215 characters
LONGTEXT   |   4 Gigabytes      | 4,294,967,295 characters

Basically, it's like:

"Exact Max. Length Allowed" = "Approx. Length" in bytes - 1

Note: If using multibyte characters (like Arabic, where each Arabic character takes 2 bytes), the column "Exact Max. Length Allowed" for TINYTEXT can hold be up to 127 Arabic characters (Note: space, dash, underscore, and other such characters, are 1-byte characters).

What is @RenderSection in asp.net MVC

If you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()
        @RenderSection("scripts", required: false)
    </body>
</html>

then you can have an index.cshtml content view like this

@section scripts {
     <script type="text/javascript">alert('hello');</script>
}

the required indicates whether or not the view using the layout page must have a scripts section

How to hide element label by element id in CSS?

If you don't care about IE6 users, use the equality attribute selector.

label[for="foo"] { display:none; }

No assembly found containing an OwinStartupAttribute Error

Add below code to your web.config file then run the project...

    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
    </dependentAssembly>
    </runtime>

Search all of Git history for a string?

Try the following commands to search the string inside all previous tracked files:

git log --patch  | less +/searching_string

or

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

which needs to be run from the parent directory where you'd like to do the searching.

How Does Modulus Divison Work

Most explanations miss one important step, let's fill the gap using another example.

Given the following:

Dividend: 16
Divisor: 6

The modulus function looks like this:

16 % 6 = 4

Let's determine why this is.

First, perform integer division, which is similar to normal division, except any fractional number (a.k.a. remainder) is discarded:

16 / 6 = 2

Then, multiply the result of the above division (2) with our divisor (6):

2 * 6 = 12

Finally, subtract the result of the above multiplication (12) from our dividend (16):

16 - 12 = 4

The result of this subtraction, 4, the remainder, is the same result of our modulus above!

What is a regular expression which will match a valid domain name without a subdomain?

I did the below to simple fetch the domain along with the protocol. Example: https://www.facebook.com/profile/user/ ftp://182.282.34.337/movies/M

use the below Regex pattern : [a-zA-Z0-9]+://.*?/

will get you the output : https://www.facebook.com/ ftp://192.282.34.337/

How do detect Android Tablets in general. Useragent?

Mo’ better to also detect “mobile” user-agent

While you may still want to detect “android” in the User-Agent to implement Android-specific features, such as touch-screen optimizations, our main message is: Should your mobile site depends on UA sniffing, please detect the strings “mobile” and “android,” rather than just “android,” in the User-Agent. This helps properly serve both your mobile and tablet visitors.

Detecting Android device via Browser

 < script language="javascript"> <!--
     var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
              if (mobile) {
                  alert("MOBILE DEVICE DETECTED");
                  document.write("<b>----------------------------------------<br>")
                  document.write("<b>" + navigator.userAgent + "<br>")
                  document.write("<b>----------------------------------------<br>")
                  var userAgent = navigator.userAgent.toLowerCase();
                  if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
                         document.write("<b> ANDROID MOBILE <br>")
                   else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
                       document.write("<b> ANDROID TABLET <br>")
              }
              else
                  alert("NO MOBILE DEVICE DETECTED"); //--> </script>

Stop MySQL service windows

Easy way to shutdown mySQL server for Windows7 :

My Computer > Manage > Services and Application > Services > select "MySQL 56"(the name depends upon the version of MySQL installed.) three options are present at left top corner. Stop the Service pause the Service Restart the Service

choose Stop the service > to stop the server

Again to start you can come to the same location or we can chose tools options on mySQL GUI Server > Startup/Shutdown > Choose to Startup or Shutdown

PS: some times it is not possible to stop the server from the GUI even though the options are provided. so is the reason the above alternative method is provided.

share the ans. to improve. thanks

Open new Terminal Tab from command line (Mac OS X)

Update: This answer gained popularity based on the shell function posted below, which still works as of OSX 10.10 (with the exception of the -g option).
However, a more fully featured, more robust, tested script version is now available at the npm registry as CLI ttab, which also supports iTerm2:

  • If you have Node.js installed, simply run:

    npm install -g ttab
    

    (depending on how you installed Node.js, you may have to prepend sudo).

  • Otherwise, follow these instructions.

  • Once installed, run ttab -h for concise usage information, or man ttab to view the manual.


Building on the accepted answer, below is a bash convenience function for opening a new tab in the current Terminal window and optionally executing a command (as a bonus, there's a variant function for creating a new window instead).

If a command is specified, its first token will be used as the new tab's title.

Sample invocations:

    # Get command-line help.
newtab -h
    # Simpy open new tab.
newtab
    # Open new tab and execute command (quoted parameters are supported).
newtab ls -l "$Home/Library/Application Support"
    # Open a new tab with a given working directory and execute a command;
    # Double-quote the command passed to `eval` and use backslash-escaping inside.
newtab eval "cd ~/Library/Application\ Support; ls"
    # Open new tab, execute commands, close tab.
newtab eval "ls \$HOME/Library/Application\ Support; echo Press a key to exit.; read -s -n 1; exit"
    # Open new tab and execute script.
newtab /path/to/someScript
    # Open new tab, execute script, close tab.
newtab exec /path/to/someScript
    # Open new tab and execute script, but don't activate the new tab.
newtab -G /path/to/someScript

CAVEAT: When you run newtab (or newwin) from a script, the script's initial working folder will be the working folder in the new tab/window, even if you change the working folder inside the script before invoking newtab/newwin - pass eval with a cd command as a workaround (see example above).

Source code (paste into your bash profile, for instance):

# Opens a new tab in the current Terminal window and optionally executes a command.
# When invoked via a function named 'newwin', opens a new Terminal *window* instead.
function newtab {

    # If this function was invoked directly by a function named 'newwin', we open a new *window* instead
    # of a new tab in the existing window.
    local funcName=$FUNCNAME
    local targetType='tab'
    local targetDesc='new tab in the active Terminal window'
    local makeTab=1
    case "${FUNCNAME[1]}" in
        newwin)
            makeTab=0
            funcName=${FUNCNAME[1]}
            targetType='window'
            targetDesc='new Terminal window'
            ;;
    esac

    # Command-line help.
    if [[ "$1" == '--help' || "$1" == '-h' ]]; then
        cat <<EOF
Synopsis:
    $funcName [-g|-G] [command [param1 ...]]

Description:
    Opens a $targetDesc and optionally executes a command.

    The new $targetType will run a login shell (i.e., load the user's shell profile) and inherit
    the working folder from this shell (the active Terminal tab).
    IMPORTANT: In scripts, \`$funcName\` *statically* inherits the working folder from the
    *invoking Terminal tab* at the time of script *invocation*, even if you change the
    working folder *inside* the script before invoking \`$funcName\`.

    -g (back*g*round) causes Terminal not to activate, but within Terminal, the new tab/window
      will become the active element.
    -G causes Terminal not to activate *and* the active element within Terminal not to change;
      i.e., the previously active window and tab stay active.

    NOTE: With -g or -G specified, for technical reasons, Terminal will still activate *briefly* when
    you create a new tab (creating a new window is not affected).

    When a command is specified, its first token will become the new ${targetType}'s title.
    Quoted parameters are handled properly.

    To specify multiple commands, use 'eval' followed by a single, *double*-quoted string
    in which the commands are separated by ';' Do NOT use backslash-escaped double quotes inside
    this string; rather, use backslash-escaping as needed.
    Use 'exit' as the last command to automatically close the tab when the command
    terminates; precede it with 'read -s -n 1' to wait for a keystroke first.

    Alternatively, pass a script name or path; prefix with 'exec' to automatically
    close the $targetType when the script terminates.

Examples:
    $funcName ls -l "\$Home/Library/Application Support"
    $funcName eval "ls \\\$HOME/Library/Application\ Support; echo Press a key to exit.; read -s -n 1; exit"
    $funcName /path/to/someScript
    $funcName exec /path/to/someScript
EOF
        return 0
    fi

    # Option-parameters loop.
    inBackground=0
    while (( $# )); do
        case "$1" in
            -g)
                inBackground=1
                ;;
            -G)
                inBackground=2
                ;;
            --) # Explicit end-of-options marker.
                shift   # Move to next param and proceed with data-parameter analysis below.
                break
                ;;
            -*) # An unrecognized switch.
                echo "$FUNCNAME: PARAMETER ERROR: Unrecognized option: '$1'. To force interpretation as non-option, precede with '--'. Use -h or --h for help." 1>&2 && return 2
                ;;
            *)  # 1st argument reached; proceed with argument-parameter analysis below.
                break
                ;;
        esac
        shift
    done

    # All remaining parameters, if any, make up the command to execute in the new tab/window.

    local CMD_PREFIX='tell application "Terminal" to do script'

        # Command for opening a new Terminal window (with a single, new tab).
    local CMD_NEWWIN=$CMD_PREFIX    # Curiously, simply executing 'do script' with no further arguments opens a new *window*.
        # Commands for opening a new tab in the current Terminal window.
        # Sadly, there is no direct way to open a new tab in an existing window, so we must activate Terminal first, then send a keyboard shortcut.
    local CMD_ACTIVATE='tell application "Terminal" to activate'
    local CMD_NEWTAB='tell application "System Events" to keystroke "t" using {command down}'
        # For use with -g: commands for saving and restoring the previous application
    local CMD_SAVE_ACTIVE_APPNAME='tell application "System Events" to set prevAppName to displayed name of first process whose frontmost is true'
    local CMD_REACTIVATE_PREV_APP='activate application prevAppName'
        # For use with -G: commands for saving and restoring the previous state within Terminal
    local CMD_SAVE_ACTIVE_WIN='tell application "Terminal" to set prevWin to front window'
    local CMD_REACTIVATE_PREV_WIN='set frontmost of prevWin to true'
    local CMD_SAVE_ACTIVE_TAB='tell application "Terminal" to set prevTab to (selected tab of front window)'
    local CMD_REACTIVATE_PREV_TAB='tell application "Terminal" to set selected of prevTab to true'

    if (( $# )); then # Command specified; open a new tab or window, then execute command.
            # Use the command's first token as the tab title.
        local tabTitle=$1
        case "$tabTitle" in
            exec|eval) # Use following token instead, if the 1st one is 'eval' or 'exec'.
                tabTitle=$(echo "$2" | awk '{ print $1 }') 
                ;;
            cd) # Use last path component of following token instead, if the 1st one is 'cd'
                tabTitle=$(basename "$2")
                ;;
        esac
        local CMD_SETTITLE="tell application \"Terminal\" to set custom title of front window to \"$tabTitle\""
            # The tricky part is to quote the command tokens properly when passing them to AppleScript:
            # Step 1: Quote all parameters (as needed) using printf '%q' - this will perform backslash-escaping.
        local quotedArgs=$(printf '%q ' "$@")
            # Step 2: Escape all backslashes again (by doubling them), because AppleScript expects that.
        local cmd="$CMD_PREFIX \"${quotedArgs//\\/\\\\}\""
            # Open new tab or window, execute command, and assign tab title.
            # '>/dev/null' suppresses AppleScript's output when it creates a new tab.
        if (( makeTab )); then
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active tab after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_SAVE_ACTIVE_TAB" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_APP" -e "$CMD_REACTIVATE_PREV_TAB" >/dev/null
                else
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_APP" >/dev/null
                fi
            else
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$cmd in front window" -e "$CMD_SETTITLE" >/dev/null
            fi
        else # make *window*
            # Note: $CMD_NEWWIN is not needed, as $cmd implicitly creates a new window.
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active window after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_WIN" -e "$cmd" -e "$CMD_SETTITLE" -e "$CMD_REACTIVATE_PREV_WIN" >/dev/null
                else
                    osascript -e "$cmd" -e "$CMD_SETTITLE" >/dev/null
                fi
            else
                    # Note: Even though we do not strictly need to activate Terminal first, we do it, as assigning the custom title to the 'front window' would otherwise sometimes target the wrong window.
                osascript -e "$CMD_ACTIVATE" -e "$cmd" -e "$CMD_SETTITLE" >/dev/null
            fi
        fi        
    else    # No command specified; simply open a new tab or window.
        if (( makeTab )); then
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active tab after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_SAVE_ACTIVE_TAB" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$CMD_REACTIVATE_PREV_APP" -e "$CMD_REACTIVATE_PREV_TAB" >/dev/null
                else
                    osascript -e "$CMD_SAVE_ACTIVE_APPNAME" -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" -e "$CMD_REACTIVATE_PREV_APP" >/dev/null
                fi
            else
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWTAB" >/dev/null
            fi
        else # make *window*
            if (( inBackground )); then
                # !! Sadly, because we must create a new tab by sending a keystroke to Terminal, we must briefly activate it, then reactivate the previously active application.
                if (( inBackground == 2 )); then # Restore the previously active window after creating the new one.
                    osascript -e "$CMD_SAVE_ACTIVE_WIN" -e "$CMD_NEWWIN" -e "$CMD_REACTIVATE_PREV_WIN" >/dev/null
                else
                    osascript -e "$CMD_NEWWIN" >/dev/null
                fi
            else
                    # Note: Even though we do not strictly need to activate Terminal first, we do it so as to better visualize what is happening (the new window will appear stacked on top of an existing one).
                osascript -e "$CMD_ACTIVATE" -e "$CMD_NEWWIN" >/dev/null
            fi
        fi
    fi

}

# Opens a new Terminal window and optionally executes a command.
function newwin {
    newtab "$@" # Simply pass through to 'newtab', which will examine the call stack to see how it was invoked.
}

How to get your Netbeans project into Eclipse

There's a very easy way if you were using a web application just follow this link.

just do in eclipse :

File > import > web > war file

Then select the war file of your app :)) very easy !!

get url content PHP

Use cURL,

Check if you have it via phpinfo();

And for the code:

function getHtml($url, $post = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    if(!empty($post)) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    } 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

How does the stack work in assembly language?

You are correct that a stack is a data structure. Often, data structures (stacks included) you work with are abstract and exist as a representation in memory.

The stack you are working with in this case has a more material existence- it maps directly to real physical registers in the processor. As a data structure, stacks are FILO (first in, last out) structures that ensure data is removed in the reverse order it was entered. See the StackOverflow logo for a visual! ;)

You are working with the instruction stack. This is the stack of actual instructions you are feeding the processor.

What is REST? Slightly confused

REST is a software design pattern typically used for web applications. In layman's terms this means that it is a commonly used idea used in many different projects. It stands for REpresentational State Transfer. The basic idea of REST is treating objects on the server-side (as in rows in a database table) as resources than can be created or destroyed.

The most basic way of thinking about REST is as a way of formatting the URLs of your web applications. For example, if your resource was called "posts", then:

/posts Would be how a user would access ALL the posts, for displaying.

/posts/:id Would be how a user would access and view an individual post, retrieved based on their unique id.

/posts/new Would be how you would display a form for creating a new post.

Sending a POST request to /users would be how you would actually create a new post on the database level.

Sending a PUT request to /users/:id would be how you would update the attributes of a given post, again identified by a unique id.

Sending a DELETE request to /users/:id would be how you would delete a given post, again identified by a unique id.

As I understand it, the REST pattern was mainly popularized (for web apps) by the Ruby on Rails framework, which puts a big emphasis on RESTful routes. I could be wrong about that though.

I may not be the most qualified to talk about it, but this is how I've learned it (specifically for Rails development).

When someone refers to a "REST api," generally what they mean is an api that uses RESTful urls for retrieving data.

Eclipse: How do you change the highlight color of the currently selected method/expression?

1 - right click the highlight whose color you want to change

2 - select "Properties" in the popup menu

3 - choose the new color (as coobird suggested)

This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.

How does Spring autowire by name when more than one matching bean is found?

Another way of achieving the same result is to use the @Value annotation:

public class Main {
     private Country country;

     @Autowired
     public void setCountry(@Value("#{country}") Country country) {
          this.country = country;
     }
}

In this case, the "#{country} string is an Spring Expression Language (SpEL) expression which evaluates to a bean named country.

Downcasting in Java

Downcasting is very useful in the following code snippet I use this all the time. Thus proving that downcasting is useful.

private static String printAll(LinkedList c)
{
    Object arr[]=c.toArray();
    String list_string="";
    for(int i=0;i<c.size();i++)
    {
        String mn=(String)arr[i];
        list_string+=(mn);
    }
    return list_string;
}

I store String in the Linked List. When I retrieve the elements of Linked List, Objects are returned. To access the elements as Strings(or any other Class Objects), downcasting helps me.

Java allows us to compile downcast code trusting us that we are doing the wrong thing. Still if humans make a mistake, it is caught at runtime.

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

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

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

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

What is the official "preferred" way to install pip and virtualenv systemwide?

Starting from distro packages, you can either use:

sudo apt-get install python-virtualenv

which lets you create virtualenvs, or

sudo apt-get install python{,3}-pip

which lets you install arbitrary packages to your home directory.

If you're used to virtualenv, the first command gives you everything you need (remember, pip is bundled and will be installed in any virtualenv you create).

If you just want to install packages, the second command gives you what you need. Use pip like this:

pip install --user something

and put something like

PATH=~/.local/bin:$PATH

in your ~/.bashrc.


If your distro is ancient and you don't want to use its packages at all (except for Python itself, probably), you can download virtualenv, either as a tarball or as a standalone script:

wget -O ~/bin/virtualenv https://raw.github.com/pypa/virtualenv/master/virtualenv.py
chmod +x ~/bin/virtualenv

If your distro is more of the bleeding edge kind, Python3.3 has built-in virtualenv-like abilities:

python3 -m venv ./venv

This runs way faster, but setuptools and pip aren't included.

Can anonymous class implement interface?

Casting anonymous types to interfaces has been something I've wanted for a while but unfortunately the current implementation forces you to have an implementation of that interface.

The best solution around it is having some type of dynamic proxy that creates the implementation for you. Using the excellent LinFu project you can replace

select new
{
  A = value.A,
  B = value.C + "_" + value.D
};

with

 select new DynamicObject(new
 {
   A = value.A,
   B = value.C + "_" + value.D
 }).CreateDuck<DummyInterface>();

Using GregorianCalendar with SimpleDateFormat

  1. You are putting there a two-digits year. The first century. And the Gregorian calendar started in the 16th century. I think you should add 2000 to the year.

  2. Month in the function new GregorianCalendar(year, month, days) is 0-based. Subtract 1 from the month there.

  3. Change the body of the second function as follows:

        String dateFormatted = null;
        SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
        try {
            dateFormatted = fmt.format(date);
        }
        catch ( IllegalArgumentException e){
            System.out.println(e.getMessage());
        }
        return dateFormatted;
    

After debugging, you'll see that simply GregorianCalendar can't be an argument of the fmt.format();.

Really, nobody needs GregorianCalendar as output, even you are told to return "a string".

Change the header of your format function to

public static String format(final Date date) 

and make the appropriate changes. fmt.format() will take the Date object gladly.

  1. Always after an unexpected exception arises, catch it yourself, don't allow the Java machine to do it. This way, you'll understand the problem.

Sort a Map<Key, Value> by values

Create customized comparator and use it while creating new TreeMap object.

class MyComparator implements Comparator<Object> {

    Map<String, Integer> map;

    public MyComparator(Map<String, Integer> map) {
        this.map = map;
    }

    public int compare(Object o1, Object o2) {

        if (map.get(o2) == map.get(o1))
            return 1;
        else
            return ((Integer) map.get(o2)).compareTo((Integer)     
                                                            map.get(o1));

    }
}

Use the below code in your main func

    Map<String, Integer> lMap = new HashMap<String, Integer>();
    lMap.put("A", 35);
    lMap.put("B", 75);
    lMap.put("C", 50);
    lMap.put("D", 50);

    MyComparator comparator = new MyComparator(lMap);

    Map<String, Integer> newMap = new TreeMap<String, Integer>(comparator);
    newMap.putAll(lMap);
    System.out.println(newMap);

Output:

{B=75, D=50, C=50, A=35}

How to redirect to an external URL in Angular2?

An Angular approach to the methods previously described is to import DOCUMENT from @angular/common (or @angular/platform-browser in Angular < 4) and use

document.location.href = 'https://stackoverflow.com';

inside a function.

some-page.component.ts

import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: Document) { }

goToUrl(): void {
    this.document.location.href = 'https://stackoverflow.com';
}

some-page.component.html

<button type="button" (click)="goToUrl()">Click me!</button>

Check out the plateformBrowser repo for more info.

Settings to Windows Firewall to allow Docker for Windows to share drive

Even after ensuring that the inbound firewall rule is set up properly and even after uninstalling and reinstalling the File and Printing Sharing Service it didn't work for me.

Solution: on top of that I also had to do a third thing. I had to deactivate the checkbox Prevent incoming connections when on a public network in the specific firewall settings for public networks. After doing that it started working for me as well. See screenshots attached at the end of this message.

Don't know how long this option has been there already. I'm currently working on Win 10 Pro 1709 16299.402.


1. Open specific firewall settings for public networks Open specific firewall settings for public networks

2. Uncheck this checkbox Uncheck this checkbox

How to strip HTML tags from a string in SQL Server?

While Arvin Amir's answer comes close to a full one-line solution you can drop in anywhere; he's got a slight bug in his select statement (missing the end of the line), and I wanted to handle the most common character references.

What I ended up doing was this:

SELECT replace(replace(replace(CAST(CAST(replace([columnNameHere], '&', '&amp;') as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max)), '&amp;', '&'), '&nbsp;', ' '), '&#x20;', ' ')
FROM [tableName]

Without the character reference code it can be simplified to this:

SELECT CAST(CAST([columnNameHere] as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max))
FROM [tableName]

What is the way of declaring an array in JavaScript?

In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.

Be careful when using new Array().

var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]

The preferred way is using the [] syntax.

var x = []; // array of size 0
var y = [10] // array of size 1: [1]

var z = []; // array of size 0
z[2] = 12;  // z is now size 3: [undefined, undefined, 12]

How do I install the OpenSSL libraries on Ubuntu?

As a general rule, when on Debian or Ubuntu and you're missing a development file (or any other file for that matter), use apt-file to figure out which package provides that file:

~ apt-file search openssl/bio.h
android-libboringssl-dev: /usr/include/android/openssl/bio.h
libssl-dev: /usr/include/openssl/bio.h
libwolfssl-dev: /usr/include/cyassl/openssl/bio.h
libwolfssl-dev: /usr/include/wolfssl/openssl/bio.h

A quick glance at each of the packages that are returned by the command, using apt show will tell you which among the packages is the one you're looking for:

~ apt show libssl-dev
Package: libssl-dev
Version: 1.1.1d-2
Priority: optional
Section: libdevel
Source: openssl
Maintainer: Debian OpenSSL Team <[email protected]>
Installed-Size: 8,095 kB
Depends: libssl1.1 (= 1.1.1d-2)
Suggests: libssl-doc
Conflicts: libssl1.0-dev
Homepage: https://www.openssl.org/
Tag: devel::lang:c, devel::library, implemented-in::TODO, implemented-in::c,
 protocol::ssl, role::devel-lib, security::cryptography
Download-Size: 1,797 kB
APT-Sources: http://ftp.fr.debian.org/debian unstable/main amd64 Packages
Description: Secure Sockets Layer toolkit - development files
 This package is part of the OpenSSL project's implementation of the SSL
 and TLS cryptographic protocols for secure communication over the
 Internet.
 .
 It contains development libraries, header files, and manpages for libssl
 and libcrypto.

N: There is 1 additional record. Please use the '-a' switch to see it

how to stop a for loop

There are several ways to do it:

The simple Way: a sentinel variable

n = L[0][0]
m = len(A)
found = False
for i in range(m):
   if found:
      break
   for j in range(m):
     if L[i][j] != n: 
       found = True
       break

Pros: easy to understand Cons: additional conditional statement for every loop

The hacky Way: raising an exception

n = L[0][0]
m = len(A)

try:
  for x in range(3):
    for z in range(3):
     if L[i][j] != n: 
       raise StopIteration
except StopIteration:
   pass

Pros: very straightforward Cons: you use Exception outside of their semantic

The clean Way: make a function

def is_different_value(l, elem, size):
  for x in range(size):
    for z in range(size):
     if l[i][j] != elem: 
       return True
  return False

if is_different_value(L, L[0][0], len(A)):
  print "Doh"

pros: much cleaner and still efficient cons: yet feels like C

The pythonic way: use iteration as it should be

def is_different_value(iterable):
  first = iterable[0][0]
  for l in iterable:
    for elem in l:
       if elem != first: 
          return True
  return False

if is_different_value(L):
  print "Doh"

pros: still clean and efficient cons: you reinvdent the wheel

The guru way: use any():

def is_different_value(iterable):
  first = iterable[0][0]
  return  any(any((cell != first for cell in col)) for elem in iterable)):

if is_different_value(L):
  print "Doh"

pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

Working with select using AngularJS's ng-options

I hope the following will work for you.

<select class="form-control"
        ng-model="selectedOption"
        ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
</select>

Dependency injection with Jersey 2.0

Late but I hope this helps someone.

I have my JAX RS defined like this:

@Path("/examplepath")
@RequestScoped //this make the diference
public class ExampleResource {

Then, in my code finally I can inject:

@Inject
SomeManagedBean bean;

In my case, the SomeManagedBean is an ApplicationScoped bean.

Hope this helps to anyone.

How to add days to the current date?

Two or three ways (depends what you want), say we are at Current Date is (in tsql code) -

DECLARE @myCurrentDate datetime = '11Apr2014 10:02:25 AM'

(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)

  1. SELECT @myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.

  2. SELECT DateADD(DAY, 365, @myCurrentDate) or DateADD(dd, 365, @myCurrentDate) will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE @myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).

  3. So what I think you meant was

    SELECT DateADD(year, 1, @myCurrentDate)
    

    which gives 2015-04-11 10:02:25.000.

  4. or better yet

    SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, @myCurrentDate), 0))
    

    which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?

How to vertically align elements in a div?

Vertically and Horizontally Align Element

Use either of these, result would be the same:

  1. Bootstrap 4
  2. CSS3

enter image description here

1. Bootstrap 4.3+

for vertical alignment: d-flex align-items-center

for horizontal alignment: d-flex justify-content-center

for vertical and horizontal d-flex align-items-center justify-content-center

_x000D_
_x000D_
.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" 
rel="stylesheet"/>

<div class="d-flex align-items-center justify-content-center container">
  <div>I am in Center</div>
</div>
_x000D_
_x000D_
_x000D_

2. CSS3

_x000D_
_x000D_
.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
_x000D_
<div class="container center">
    <div>I am in Center</div>
</div>
_x000D_
_x000D_
_x000D_

Purpose of ESI & EDI registers?

In addition to the registers being used for mass operations, they are useful for their property of being preserved through a function call (call-preserved) in 32-bit calling convention. The ESI, EDI, EBX, EBP, ESP are call-preserved whereas EAX, ECX and EDX are not call-preserved. Call-preserved registers are respected by C library function and their values persist through the C library function calls.

Jeff Duntemann in his assembly language book has an example assembly code for printing the command line arguments. The code uses esi and edi to store counters as they will be unchanged by the C library function printf. For other registers like eax, ecx, edx, there is no guarantee of them not being used by the C library functions.

https://www.amazon.com/Assembly-Language-Step-Step-Programming/dp/0470497025

See section 12.8 How C sees Command-Line Arguments.

Note that 64-bit calling conventions are different from 32-bit calling conventions, and I am not sure if these registers are call-preserved or not.

How to print Boolean flag in NSLog?

Apple's FixIt supplied %hhd, which correctly gave me the value of my BOOL.

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

How to change the remote a branch is tracking?

I've found @critikaster's post helpful, except that I had to perform these commands with GIT 2.21:

$ git remote set-url origin https://some_url/some_repo
$ git push --set-upstream origin master

Is there a RegExp.escape function in JavaScript?

For anyone using Lodash, since v3.0.0 a _.escapeRegExp function is built-in:

_.escapeRegExp('[lodash](https://lodash.com/)');
// ? '\[lodash\]\(https:\/\/lodash\.com\/\)'

And, in the event that you don't want to require the full Lodash library, you may require just that function!

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I also faced this issue you just need to make 2 changes:

File Name : android/build.gradle mention this below code

subprojects {
   afterEvaluate { 
     project -> if (project.hasProperty("android")) { 
       android { 
        compileSdkVersion 26 buildToolsVersion '26.0.2' 
       } 
      }
    } 
}

File Name :android/app/build.gradle change your compliesdk version and buildToolVersion like this:

compileSdkVersion 26 buildToolsVersion "26.0.2"

and in

dependencies {
    compile 'com.android.support:appcompat-v7:26.0.2'
}

Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

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

You can't specify an exact sleep time in Windows. You need a real-time OS for that. The best you can do is specify a minimum sleep time. Then it's up to the scheduler to wake up your thread after that. And never call .Sleep() on the GUI thread.

Convert InputStream to JSONObject

Another solution: use flexjson.jar: http://mvnrepository.com/artifact/net.sf.flexjson/flexjson/3.2

List<yourEntity> yourEntityList = deserializer.deserialize(new InputStreamReader(input));

Find the number of employees in each department - SQL Oracle

select  d.dname
       ,count(e.empno) as count 
from dept d 
left outer join emp e 
  on e.deptno=d.deptno 
group by d.dname;

How to check empty object in angular 2 template using *ngIf

This should do what you want:

<div class="comeBack_up" *ngIf="(previous_info | json) != ({} | json)">

or shorter

<div class="comeBack_up" *ngIf="(previous_info | json) != '{}'">

Each {} creates a new instance and ==== comparison of different objects instances always results in false. When they are convert to strings === results to true

Plunker example

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

This question comes up ALL THE TIME on SO. It's one of the first things that new Swift developers struggle with.

Background:

Swift uses the concept of "Optionals" to deal with values that could contain a value, or not. In other languages like C, you might store a value of 0 in a variable to indicate that it contains no value. However, what if 0 is a valid value? Then you might use -1. What if -1 is a valid value? And so on.

Swift optionals let you set up a variable of any type to contain either a valid value, or no value.

You put a question mark after the type when you declare a variable to mean (type x, or no value).

An optional is actually a container than contains either a variable of a given type, or nothing.

An optional needs to be "unwrapped" in order to fetch the value inside.

The "!" operator is a "force unwrap" operator. It says "trust me. I know what I am doing. I guarantee that when this code runs, the variable will not contain nil." If you are wrong, you crash.

Unless you really do know what you are doing, avoid the "!" force unwrap operator. It is probably the largest source of crashes for beginning Swift programmers.

How to deal with optionals:

There are lots of other ways of dealing with optionals that are safer. Here are some (not an exhaustive list)

You can use "optional binding" or "if let" to say "if this optional contains a value, save that value into a new, non-optional variable. If the optional does not contain a value, skip the body of this if statement".

Here is an example of optional binding with our foo optional:

if let newFoo = foo //If let is called optional binding. {
  print("foo is not nil")
} else {
  print("foo is nil")
}

Note that the variable you define when you use optional biding only exists (is only "in scope") in the body of the if statement.

Alternately, you could use a guard statement, which lets you exit your function if the variable is nil:

func aFunc(foo: Int?) {
  guard let newFoo = input else { return }
  //For the rest of the function newFoo is a non-optional var
}

Guard statements were added in Swift 2. Guard lets you preserve the "golden path" through your code, and avoid ever-increasing levels of nested ifs that sometimes result from using "if let" optional binding.

There is also a construct called the "nil coalescing operator". It takes the form "optional_var ?? replacement_val". It returns a non-optional variable with the same type as the data contained in the optional. If the optional contains nil, it returns the value of the expression after the "??" symbol.

So you could use code like this:

let newFoo = foo ?? "nil" // "??" is the nil coalescing operator
print("foo = \(newFoo)")

You could also use try/catch or guard error handling, but generally one of the other techniques above is cleaner.

EDIT:

Another, slightly more subtle gotcha with optionals is "implicitly unwrapped optionals. When we declare foo, we could say:

var foo: String!

In that case foo is still an optional, but you don't have to unwrap it to reference it. That means any time you try to reference foo, you crash if it's nil.

So this code:

var foo: String!


let upperFoo = foo.capitalizedString

Will crash on reference to foo's capitalizedString property even though we're not force-unwrapping foo. the print looks fine, but it's not.

Thus you want to be really careful with implicitly unwrapped optionals. (and perhaps even avoid them completely until you have a solid understanding of optionals.)

Bottom line: When you are first learning Swift, pretend the "!" character is not part of the language. It's likely to get you into trouble.

How to get the unix timestamp in C#

This is what I use.

 public class TimeStamp
    {
        public Int32 UnixTimeStampUTC()
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
}

What is the default access specifier in Java?

The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.

Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

$_FILES["file"]["tmp_name"] contains the actual copy of your file content on the server while
$_FILES["file"]["name"] contains the name of the file which you have uploaded from the client computer.

jquery append div inside div with id and manipulate

You're overcomplicating things:

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);

For example: http://jsfiddle.net/ambiguous/Dm5J2/

Sequelize, convert entity to plain object

Best and the simple way of doing is :

Just use the default way from Sequelize

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    },
    raw : true // <----------- Magic is here
}).success(function (sensors) {
        console.log(sensors);
});

Note : [options.raw] : Return raw result. See sequelize.query for more information.


For the nested result/if we have include model , In latest version of sequlize ,

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    },
    include : [
        { model : someModel }
    ]
    raw : true , // <----------- Magic is here
    nest : true // <----------- Magic is here
}).success(function (sensors) {
        console.log(sensors);
});

Only detect click event on pseudo-element

This is edited answer by Fasoeu with latest CSS3 and JS ES6

Edited demo without using JQuery.

Shortest example of code:

<p><span>Some text</span></p>
p {
    position: relative;
    pointer-events: none;
}
p::before {
    content: "";
    position: absolute;
    pointer-events: auto;
}
p span {
    display: contents;
    pointer-events: auto;
}
const all_p = Array.from(document.querySelectorAll('p'));

for (let p of all_p) {
    p.addEventListener("click", listener, false);
};

Explanation:

pointer-events control detection of events, removing receiving events from target, but keep receiving from pseudo-elements make possible to click on ::before and ::after and you will always know what you are clicking on pseudo-element, however if you still need to click, you put all content in nested element (span in example), but because we don't want to apply any additional styles, display: contents; become very handy solution and it supported by most browsers. pointer-events: none; as already mentioned in original post also widely supported.

The JavaScript part also used widely supported Array.from and for...of, however they are not necessary to use in code.

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

Import Excel Spreadsheet Data to an EXISTING sql table?

You can copy-paste data from en excel-sheet to an SQL-table by doing so:

  • Select the data in Excel and press Ctrl + C
  • In SQL Server Management Studio right click the table and choose Edit Top 200 Rows
  • Scroll to the bottom and select the entire empty row by clicking on the row header
  • Paste the data by pressing Ctrl + V

Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.

Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).

PHP and MySQL Select a Single Value

try this

session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
      $_SESSION['myid'] = $row['id'];
}

Can scripts be inserted with innerHTML?

Gabriel Garcia's mention of MutationObservers is on the right track, but didn't quite work for me. I am not sure if that was because of a browser quirk or due to a mistake on my end, but the version that ended up working for me was the following:

document.addEventListener("DOMContentLoaded", function(event) {
    var observer = new MutationObserver(mutations=>{
        mutations.map(mutation=>{
            Array.from(mutation.addedNodes).map(node=>{
                if (node.tagName === "SCRIPT") {
                    var s = document.createElement("script");
                    s.text=node.text;
                    if (typeof(node.parentElement.added) === 'undefined')
                        node.parentElement.added = [];
                    node.parentElement.added[node.parentElement.added.length] = s;
                    node.parentElement.removeChild(node);
                    document.head.appendChild(s);
                }
            })
        })
    })
    observer.observe(document.getElementById("element_to_watch"), {childList: true, subtree: true,attributes: false});
};

Of course, you should replace element_to_watch with the name of the element that is being modified.

node.parentElement.added is used to store the script tags that are added to document.head. In the function used to load the external page, you can use something like the following to remove no longer relevant script tags:

function freeScripts(node){
    if (node === null)
        return;
    if (typeof(node.added) === 'object') {
        for (var script in node.added) {
            document.head.removeChild(node.added[script]);
        }
        node.added = {};
    }
    for (var child in node.children) {
        freeScripts(node.children[child]);
    }
}

And an example of the beginning of a load function:

function load(url, id, replace) {
    if (document.getElementById(id) === null) {
        console.error("Element of ID "+id + " does not exist!");
        return;
    }
    freeScripts(document.getElementById(id));
    var xhttp = new XMLHttpRequest();
    // proceed to load in the page and modify innerHTML
}

Why is list initialization (using curly braces) better than the alternatives?

There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.

struct Foo {
    Foo() {}

    Foo(std::initializer_list<Foo>) {
        std::cout << "initializer list" << std::endl;
    }

    Foo(const Foo&) {
        std::cout << "copy ctor" << std::endl;
    }
};

int main() {
    Foo a;
    Foo b(a); // copy ctor
    Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}

Assuming you don't encounter such classes there is little reason not to use the intializer list.

Select first row in each GROUP BY group?

In SQL Server you can do this:

SELECT *
FROM (
SELECT ROW_NUMBER()
OVER(PARTITION BY customer
ORDER BY total DESC) AS StRank, *
FROM Purchases) n
WHERE StRank = 1

Explaination:Here Group by is done on the basis of customer and then order it by total then each such group is given serial number as StRank and we are taking out first 1 customer whose StRank is 1

MongoDB Show all contents from all collections

var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++){    
   print('Collection: ' + collections[i]); // print the name of each collection
   db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}

I think this script might get what you want. It prints the name of each collection and then prints its elements in json.

error: pathspec 'test-branch' did not match any file(s) known to git

Solution:

To fix it you need to fetch first

$ git fetch origin

$ git rebase origin/master

Current branch master is up to date.

$ git checkout develop

Branch develop set up to track remote branch develop from origin.

Switched to a new branch ‘develop’

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

Where is the Java SDK folder in my computer? Ubuntu 12.04

Location of JRE in Ubuntu:

/usr/lib/jvm/java-7-oracle/jre

Delete first character of a string in Javascript

var test = '0test';
test = test.replace(/0(.*)/, '$1');

How to Select Every Row Where Column Value is NOT Distinct

Rather than using sub queries in where condition which will increase the query time where records are huge.

I would suggest to use Inner Join as a better option to this problem.

Considering the same table this could give the result

SELECT EmailAddress, CustomerName FROM Customers as a 
Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress

For still better results I would suggest you to use CustomerID or any unique field of your table. Duplication of CustomerName is possible.

AWK: Access captured group from line pattern

That was a stroll down memory lane...

I replaced awk by perl a long time ago.

Apparently the AWK regular expression engine does not capture its groups.

you might consider using something like :

perl -n -e'/test(\d+)/ && print $1'

the -n flag causes perl to loop over every line like awk does.

In STL maps, is it better to use map::insert than []?

Another thing to note with std::map:

myMap[nonExistingKey]; will create a new entry in the map, keyed to nonExistingKey initialized to a default value.

This scared the hell out of me the first time I saw it (while banging my head against a nastly legacy bug). Wouldn't have expected it. To me, that looks like a get operation, and I didn't expect the "side-effect." Prefer map.find() when getting from your map.

What is a "cache-friendly" code?

It needs to be clarified that not only data should be cache-friendly, it is just as important for the code. This is in addition to branch predicition, instruction reordering, avoiding actual divisions and other techniques.

Typically the denser the code, the fewer cache lines will be required to store it. This results in more cache lines being available for data.

The code should not call functions all over the place as they typically will require one or more cache lines of their own, resulting in fewer cache lines for data.

A function should begin at a cache line-alignment-friendly address. Though there are (gcc) compiler switches for this be aware that if the the functions are very short it might be wasteful for each one to occupy an entire cache line. For example, if three of the most often used functions fit inside one 64 byte cache line, this is less wasteful than if each one has its own line and results in two cache lines less available for other usage. A typical alignment value could be 32 or 16.

So spend some extra time to make the code dense. Test different constructs, compile and review the generated code size and profile.

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

Verifying a specific parameter with Moq

A simpler way would be to do:

ObjectA.Verify(
    a => a.Execute(
        It.Is<Params>(p => p.Id == 7)
    )
);

How do I add a new column to a Spark DataFrame (using PySpark)?

The simplest way to add a column is to use "withColumn". Since the dataframe is created using sqlContext, you have to specify the schema or by default can be available in the dataset. If the schema is specified, the workload becomes tedious when changing every time.

Below is an example that you can consider:

from pyspark.sql import SQLContext
from pyspark.sql.types import *
sqlContext = SQLContext(sc) # SparkContext will be sc by default 

# Read the dataset of your choice (Already loaded with schema)
Data = sqlContext.read.csv("/path", header = True/False, schema = "infer", sep = "delimiter")

# For instance the data has 30 columns from col1, col2, ... col30. If you want to add a 31st column, you can do so by the following:
Data = Data.withColumn("col31", "Code goes here")

# Check the change 
Data.printSchema()

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

REST API 404: Bad URI, or Missing Resource?

This old but excellent article... http://www.infoq.com/articles/webber-rest-workflow says this about it...

404 Not Found - The service is far too lazy (or secure) to give us a real reason why our request failed, but whatever the reason, we need to deal with it.

Should I use Java's String.format() if performance is important?

Here is modified version of hhafez entry. It includes a string builder option.

public class BLA
{
public static final String BLAH = "Blah ";
public static final String BLAH2 = " Blah";
public static final String BLAH3 = "Blah %d Blah";


public static void main(String[] args) {
    int i = 0;
    long prev_time = System.currentTimeMillis();
    long time;
    int numLoops = 1000000;

    for( i = 0; i< numLoops; i++){
        String s = BLAH + i + BLAH2;
    }
    time = System.currentTimeMillis() - prev_time;

    System.out.println("Time after for loop " + time);

    prev_time = System.currentTimeMillis();
    for( i = 0; i<numLoops; i++){
        String s = String.format(BLAH3, i);
    }
    time = System.currentTimeMillis() - prev_time;
    System.out.println("Time after for loop " + time);

    prev_time = System.currentTimeMillis();
    for( i = 0; i<numLoops; i++){
        StringBuilder sb = new StringBuilder();
        sb.append(BLAH);
        sb.append(i);
        sb.append(BLAH2);
        String s = sb.toString();
    }
    time = System.currentTimeMillis() - prev_time;
    System.out.println("Time after for loop " + time);

}

}

Time after for loop 391 Time after for loop 4163 Time after for loop 227

Running an outside program (executable) in Python?

Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.system, subprocess methods, or whatever...

If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

Copyed the *.jar into my WEB-INF/lib folder -> Worked for me. When including over buildpath there was everytime this errormsg.

JavaScript Chart.js - Custom data formatting to display on tooltip

tooltips: {
            enabled: true,
                  mode: 'single',
                  callbacks: {
                    label: function(tooltipItems, data) { 
                      return data.datasets[tooltipItems.datasetIndex].label+": "+tooltipItems.yLabel;
                    }
                  }
                }

How to disable margin-collapsing?

I had similar problem with margin collapse because of parent having position set to relative. Here are list of commands you can use to disable margin collapsing.

HERE IS PLAYGROUND TO TEST

Just try to assign any parent-fix* class to div.container element, or any class children-fix* to div.margin. Pick the one that fits your needs best.

When

  • margin collapsing is disabled, div.absolute with red background will be positioned at the very top of the page.
  • margin is collapsing div.absolute will be positioned at the same Y coordinate as div.margin

_x000D_
_x000D_
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
  width: 100%;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 50px;_x000D_
  right: 50px;_x000D_
  height: 100px;_x000D_
  border: 5px solid #F00;_x000D_
  background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
  width: 100%;_x000D_
  height: 20px;_x000D_
  background-color: #444;_x000D_
  margin-top: 50px;_x000D_
  color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before {  content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
  <div class="margin children-fix">margin</div>_x000D_
  <div class="absolute"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is jsFiddle with example you can edit

How to deal with SQL column names that look like SQL keywords?

Your question seems to be well answered here, but I just want to add one more comment to this subject.

Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.

More information:

"Reserved keywords should not be used as object names. Databases upgraded from earlier versions of SQL Server may contain identifiers that include words not reserved in the earlier version, but that are reserved words for the current version of SQL Server. You can refer to the object by using delimited identifiers until the name can be changed." http://msdn.microsoft.com/en-us/library/ms176027.aspx

and

"If your database does contain names that match reserved keywords, you must use delimited identifiers when you refer to those objects. For more information, see Identifiers (DMX)." http://msdn.microsoft.com/en-us/library/ms132178.aspx

Declaring multiple variables in JavaScript

ECMAScript 2015 introduced destructuring assignment which works pretty nice:

[a, b] = [1, 2]

a will equal 1 and b will equal 2.

for loop in Python

Use this instead of a for loop:

k = 1
while k <= c:
   #code
   k += 1

Fastest check if row exists in PostgreSQL

as @MikeM pointed out.

select exists(select 1 from contact where id=12)

with index on contact, it can usually reduce time cost to 1 ms.

CREATE INDEX index_contact on contact(id);

How to add to an NSDictionary

When ever the array is declared, then only we have to add the key-value's in NSDictionary like

NSDictionary *normalDict = [[NSDictionary alloc]initWithObjectsAndKeys:@"Value1",@"Key1",@"Value2",@"Key2",@"Value3",@"Key3",nil];

we cannot add or remove the key values in this NSDictionary

Where as in NSMutableDictionary we can add the objects after intialization of array also by using this method

NSMutableDictionary *mutableDict = [[NSMutableDictionary alloc]init];'
[mutableDict setObject:@"Value1" forKey:@"Key1"];
[mutableDict setObject:@"Value2" forKey:@"Key2"];
[mutableDict setObject:@"Value3" forKey:@"Key3"];

for removing the key value we have to use the following code

[mutableDict removeObject:@"Value1" forKey:@"Key1"];

Creating a list/array in excel using VBA to get a list of unique names in a column

Inspired by VB.Net Generics List(Of Integer), I created my own module for that. Maybe you find it useful, too or you'd like to extend for additional methods e.g. to remove items again:

'Save module with name: ListOfInteger

Public Function ListLength(list() As Integer) As Integer
On Error Resume Next
ListLength = UBound(list) + 1
On Error GoTo 0
End Function

Public Sub ListAdd(list() As Integer, newValue As Integer)
ReDim Preserve list(ListLength(list))
list(UBound(list)) = newValue
End Sub

Public Function ListContains(list() As Integer, value As Integer) As Boolean
ListContains = False
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
    If list(MyCounter) = value Then
        ListContains = True
        Exit For
    End If
Next
End Function

Public Sub DebugOutputList(list() As Integer)
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
    Debug.Print list(MyCounter)
Next
End Sub

You might use it as follows in your code:

Public Sub IntegerListDemo_RowsOfAllSelectedCells()
Dim rows() As Integer

Set SelectedCellRange = Excel.Selection
For Each MyCell In SelectedCellRange
    If IsEmpty(MyCell.value) = False Then
        If ListOfInteger.ListContains(rows, MyCell.Row) = False Then
            ListAdd rows, MyCell.Row
        End If
    End If
Next
ListOfInteger.DebugOutputList rows

End Sub

If you need another list type, just copy the module, save it at e.g. ListOfLong and replace all types Integer by Long. That's it :-)

load scripts asynchronously

A couple solutions for async loading:

//this function will work cross-browser for loading scripts asynchronously
function loadScript(src, callback)
{
  var s,
      r,
      t;
  r = false;
  s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = src;
  s.onload = s.onreadystatechange = function() {
    //console.log( this.readyState ); //uncomment this line to see which ready states are called.
    if ( !r && (!this.readyState || this.readyState == 'complete') )
    {
      r = true;
      callback();
    }
  };
  t = document.getElementsByTagName('script')[0];
  t.parentNode.insertBefore(s, t);
}

If you've already got jQuery on the page, just use:

$.getScript(url, successCallback)*

Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.

It's not possible to tell specifically what your issue is without seeing the code.

The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.

If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).

* scripts loaded with $.getScript will likely not be cached


For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:

function loadScript(src) {
    return new Promise(function (resolve, reject) {
        var s;
        s = document.createElement('script');
        s.src = src;
        s.onload = resolve;
        s.onerror = reject;
        document.head.appendChild(s);
    });
}

Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).

This has the added bonus of being able to detect and handle failures, for example one could call...

loadScript(cdnSource)
    .catch(loadScript.bind(null, localSource))
    .then(successCallback, failureCallback);

...and it would handle CDN outages gracefully.

Angular 2 'component' is not a known element

In my case, my app had multiple layers of modules, so the module I was trying to import had to be added into the module parent that actually used it pages.module.ts, instead of app.module.ts.

How to convert float to int with Java

Actually, there are different ways to downcast float to int, depending on the result you want to achieve: (for int i, float f)

  • round (the closest integer to given float)

    i = Math.round(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3
    

    note: this is, by contract, equal to (int) Math.floor(f + 0.5f)

  • truncate (i.e. drop everything after the decimal dot)

    i = (int) f;
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
  • ceil/floor (an integer always bigger/smaller than a given value if it has any fractional part)

    i = (int) Math.ceil(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  3 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
    i = (int) Math.floor(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
    

For rounding positive values, you can also just use (int)(f + 0.5), which works exactly as Math.Round in those cases (as per doc).

You can also use Math.rint(f) to do the rounding to the nearest even integer; it's arguably useful if you expect to deal with a lot of floats with fractional part strictly equal to .5 (note the possible IEEE rounding issues), and want to keep the average of the set in place; you'll introduce another bias, where even numbers will be more common than odd, though.

See

http://mindprod.com/jgloss/round.html

http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

for more information and some examples.

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

Dependency Injection vs Factory Pattern

Theory

There are two important points to consider:

  1. Who creates objects

    • [Factory]: You have to write HOW object should be created. You have separate Factory class which contains creation logic.
    • [Dependency Injection]: In practical cases are done by external frameworks (for example in Java that would be spring/ejb/guice). Injection happens "magically" without explicite creation of new objects
  2. What kind of objects it manages:

    • [Factory]: Usually responsible for creation of stateful objects
    • [Dependency Injections] More likely to create stateless objects

Practical example how to use both factory and dependency injection in single project

  1. What we want to build

Application module for creating order which contains multiple entries called orderline.

  1. Architecture

Let's assume we want to create following layer architecture:

enter image description here

Domain objects may be objects stored inside database. Repository (DAO) helps with retrievar of objects from database. Service provides API to other modules. Alows for operations on order module

  1. Domain Layer and usage of factories

Entities which will be in the database are Order and OrderLine. Order can have multiple OrderLines. Relationship between Order and OrderLine

Now comes important design part. Should modules outside this one create and manage OrderLines on their own? No. Order Line should exist only when you have Order associated with it. It would be best if you could hide internal implementaiton to outside classes.

But how to create Order without knowledge about OrderLines?

Factory

Someone who wants to create new order used OrderFactory (which will hide details about the fact how we create Order).

enter image description here

Thats how it will look inside IDE. Classes outside domain package will use OrderFactory instead of constructor inside Order

  1. Dependency Injection Dependency injection is more commonly used with stateless layers such as repository and service.

OrderRepository and OrderService are managed by dependency injection framework. Repository is responsible for managing CRUD operations on database. Service injects Repository and uses it to save/find correct domain classes.

enter image description here

How to install python-dateutil on Windows?

Just run command prompt as administrator and type this in.

easy_install python-dateutil

WCF Exception: Could not find a base address that matches scheme http for the endpoint

You can get this if you ONLY configure https as a site binding inside IIS.

You need to add http(80) as well as https(443) - at least I did :-)

resource error in android studio after update: No Resource Found

if you have :

/Users/james/Development/AndroidProjects/myapp/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.0/res/values-v23/values-v23.xml
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.

error , you must change your appcompat , buildtools , sdk to 23 but , if you don't like to change it and must be in 22 do this :

  • compile 23
  • target 22

Cannot change column used in a foreign key constraint

The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field.

One solution would be this:

LOCK TABLES 
    favorite_food WRITE,
    person WRITE;

ALTER TABLE favorite_food
    DROP FOREIGN KEY fk_fav_food_person_id,
    MODIFY person_id SMALLINT UNSIGNED;

Now you can change you person_id

ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;

recreate foreign key

ALTER TABLE favorite_food
    ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)
          REFERENCES person (person_id);

UNLOCK TABLES;

EDIT: Added locks above, thanks to comments

You have to disallow writing to the database while you do this, otherwise you risk data integrity problems.

I've added a write lock above

All writing queries in any other session than your own ( INSERT, UPDATE, DELETE ) will wait till timeout or UNLOCK TABLES; is executed

http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html

EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."

From MySQL 5.5 Reference Manual: FOREIGN KEY Constraints

Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.

Can’t delete docker image with dependent child images

Expanding on the answer provided by @Nguyen - this function can be added to your .bashrc etc and then called from the commandline to help clean up any image has dependent child images errors...

You can run the function as yourself, and if a docker ps fails, then it will run the docker command with sudo and prompt you for your password.

Does NOT delete images for any running containers!

docker_rmi_dependants ()                                                                                                                                                         
{ 
  DOCKER=docker
  [ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"

  echo "Docker: ${DOCKER}"

  for n in $(${DOCKER} images | awk '$2 == "<none>" {print $3}');
  do  
    echo "ImageID: $n";
    ${DOCKER} inspect --format='{{.Id}} {{.Parent}}' $(${DOCKER} images --filter since=$n -q);
  done;

  ${DOCKER} rmi $(${DOCKER} images | awk '$2 == "<none>" {print $3}')
}

I also have this in my .bashrc file...

docker_rm_dangling ()  
{ 
  DOCKER=docker
  [ docker ps >/dev/null 2>&1 ] || DOCKER="sudo docker"

  echo "Docker: ${DOCKER}"

  ${DOCKER} images -f dangling=true 2>&1 > /dev/null && YES=$?;                                                                                                                  
  if [ $YES -eq 1 ]; then
    read -t 30 -p "Press ENTER to remove, or CTRL-C to quit.";
    ${DOCKER} rmi $(${DOCKER} images -f dangling=true -q);
  else
    echo "Nothing to do... all groovy!";
  fi  
}

Works with:

$ docker --version 
Docker version 17.05.0-ce, build 89658be

How do I hide the status bar in a Swift iOS app?

if you prefer a visual approach rather than coding it use this method: in your info.plist

enter image description here simply add View controller-based status bar appearance to NO

and Status bar is initially hidden as YES

How to check that an element is in a std::set?

Another way of simply telling if an element exists is to check the count()

if (myset.count(x)) {
   // x is in the set, count is 1
} else {
   // count zero, i.e. x not in the set
}

Most of the times, however, I find myself needing access to the element wherever I check for its existence.

So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end too.

set< X >::iterator it = myset.find(x);
if (it != myset.end()) {
   // do something with *it
}

C++ 20

In C++20 set gets a contains function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245

if (myset.contains(x)) {
  // x is in the set
} else {
  // no x 
}

SQL statement to get column type

Another variation using MS SQL:

SELECT TYPE_NAME(system_type_id) 
FROM sys.columns 
WHERE name = 'column_name'
AND [object_id] = OBJECT_ID('[dbo].[table_name]');

How can apply multiple background color to one div

You could apply both background-color and border to make it look like 2 colors.

div.A { width: 50px; background-color: #9c9e9f; border-right: 50px solid #f6f6f6; }

The border should have the same size as the width.

How to Reload ReCaptcha using JavaScript?

Or you could just simulate a click on the refresh button

// If recaptcha object exists, refresh it
    if (typeof Recaptcha != "undefined") {
      jQuery('#recaptcha_reload').click();
    }

What are Maven goals and phases and what is their difference?

There are following three built-in build lifecycles:

  • default
  • clean
  • site

Lifecycle default -> [validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy]

Lifecycle clean -> [pre-clean, clean, post-clean]

Lifecycle site -> [pre-site, site, post-site, site-deploy]

The flow is sequential, for example, for default lifecycle, it starts with validate, then initialize and so on...

You can check the lifecycle by enabling debug mode of mvn i.e., mvn -X <your_goal>

You must enable the openssl extension to download files via https

PHP CLI SAPI is using different php.ini than CGI or Apache module.

Find line ;extension=php_openssl.dll in wamp/bin/php/php#.#.##/php.ini and uncomment it by removing the semicolon (;) from the beginning of the line.

"Missing return statement" within if / for / while

If you put return statement in if, while or for statement then it may or may not return value. If it will not go inside these statement then also that method should return some value ( that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.

But if you write if / else block and each one of them is having return in it then compiler knows that either if or else will get execute and method will return a value. So this time compiler will not force you.

if(condition)
{
 return;
}
else
{
 return;
}

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

I had this issue on Mac OS Sierra on my way to running a React Native Android App for the first time:

Execution failed for task ':app:compileDebugJavaWithJavac'.

> Could not find tools.jar

I changed my JAVA HOME environment variable for Java Development Kit (JDK) from:

export JAVA_HOME='/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home'

to :

export JAVA_HOME='/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home'

I figured out where the correct version was after creating a project in Android Studio and looking for the JDK location in the project settings.

What's the best way to send a signal to all members of a process group?

The following shell function is similar to many of the other answers, but it works both on Linux and BSD (OS X, etc) without external dependencies like pgrep:

killtree() {
    local parent=$1 child
    for child in $(ps -o ppid= -o pid= | awk "\$1==$parent {print \$2}"); do
        killtree $child
    done
    kill $parent
}

TypeError: ObjectId('') is not JSON serializable

If you don't want _id in response, you can refactor your code something like this:

jsonResponse = getResponse(mock_data)
del jsonResponse['_id'] # removes '_id' from the final response
return jsonResponse

This will remove the TypeError: ObjectId('') is not JSON serializable error.

WCF on IIS8; *.svc handler mapping doesn't work

turn ON the following on 'Turn Windows Features on or off'

a) .Net Framework 3.5 - WCF HTTP Activation and Non-Http Activation

b) all under WCF Services

Passing an array using an HTML form hidden element

<input type="hidden" name="item[]" value="[anyvalue]">

Let it be in a repeated mode it will post this element in the form as an array and use the

print_r($_POST['item'])

To retrieve the item

How to trigger jQuery change event in code

for me $('#element').val('...').change() is the best way.

What does question mark and dot operator ?. mean in C# 6.0?

It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:

if (Model.Model2 == null
  || Model.Model2.Model3 == null
  || Model.Model2.Model3.Model4 == null
  || Model.Model2.Model3.Model4.Name == null)
{
  mapped.Name = "N/A"
}
else
{
  mapped.Name = Model.Model2.Model3.Model4.Name;
}

It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";

DotNetFiddle.Net Working Example.

(the ?? or null-coalescing operator is different than the ? or null conditional operator).

It can also be used out side of assignment operators with Action. Instead of

Action<TValue> myAction = null;

if (myAction != null)
{
  myAction(TValue);
}

It can be simplified to:

myAction?.Invoke(TValue);

DotNetFiddle Example:

using System;

public class Program
{
  public static void Main()
  {
    Action<string> consoleWrite = null;

    consoleWrite?.Invoke("Test 1");

    consoleWrite = (s) => Console.WriteLine(s);

    consoleWrite?.Invoke("Test 2");
  }
}

Result:

Test 2

'any' vs 'Object'

any is something specific to TypeScript is explained quite well by alex's answer.

Object refers to the JavaScript object type. Commonly used as {} or sometimes new Object. Most things in javascript are compatible with the object data type as they inherit from it. But any is TypeScript specific and compatible with everything in both directions (not inheritance based). e.g. :

var foo:Object; 
var bar:any;
var num:number;

foo = num; // Not an error
num = foo; // ERROR 

// Any is compatible both ways 
bar = num;
num = bar;  

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

VB.NET VERSION

Okay, so I have just spent several hours looking for a viable method for posting multiple parameters to an MVC 4 WEB API, but most of what I found was either for a 'GET' action or just flat out did not work. However, I finally got this working and I thought I'd share my solution.

  1. Use NuGet packages to download JSON-js json2 and Json.NET. Steps to install NuGet packages:

    (1) In Visual Studio, go to Website > Manage NuGet Packages... enter image description here

    (2) Type json (or something to that effect) into the search bar and find JSON-js json2 and Json.NET. Double-clicking them will install the packages into the current project.enter image description here

    (3) NuGet will automatically place the json file in ~/Scripts/json2.min.js in your project directory. Find the json2.min.js file and drag/drop it into the head of your website. Note: for instructions on installing .js (javascript) files, read this solution.

  2. Create a class object containing the desired parameters. You will use this to access the parameters in the API controller. Example code:

    Public Class PostMessageObj
    
    Private _body As String
    Public Property body As String
        Get
            Return _body
        End Get
        Set(value As String)
            _body = value
        End Set
    End Property
    
    
    Private _id As String
    Public Property id As String
        Get
            Return _id
        End Get
        Set(value As String)
            _id = value
        End Set
    End Property
    End Class
    
  3. Then we setup the actual MVC 4 Web API controller that we will be using for the POST action. In it, we will use Json.NET to deserialize the string object when it is posted. Remember to use the appropriate namespaces. Continuing with the previous example, here is my code:

    Public Sub PostMessage(<FromBody()> ByVal newmessage As String)
    
    Dim t As PostMessageObj = Newtonsoft.Json.JsonConvert.DeserializeObject(Of PostMessageObj)(newmessage)
    
    Dim body As String = t.body
    Dim i As String = t.id
    
    End Sub
    
  4. Now that we have our API controller set up to receive our stringified JSON object, we can call the POST action freely from the client-side using $.ajax; Continuing with the previous example, here is my code (replace localhost+rootpath appropriately):

    var url = 'http://<localhost+rootpath>/api/Offers/PostMessage';
    var dataType = 'json'
    var data = 'nothn'
    var tempdata = { body: 'this is a new message...Ip sum lorem.',
        id: '1234'
    }
    var jsondata = JSON.stringify(tempdata)
    $.ajax({
        type: "POST",
        url: url,
        data: { '': jsondata},
        success: success(data),
        dataType: 'text'
    });
    

As you can see we are basically building the JSON object, converting it into a string, passing it as a single parameter, and then rebuilding it via the JSON.NET framework. I did not include a return value in our API controller so I just placed an arbitrary string value in the success() function.


Author's notes

This was done in Visual Studio 2010 using ASP.NET 4.0, WebForms, VB.NET, and MVC 4 Web API Controller. For anyone having trouble integrating MVC 4 Web API with VS2010, you can download the patch to make it possible. You can download it from Microsoft's Download Center.

Here are some additional references which helped (mostly in C#):

Please add a @Pipe/@Directive/@Component annotation. Error

In my case I mistakenly added this:

@Component({
    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]
})

declare var configuration: any;

while the correct form is:

declare var configuration: any;

@Component({
    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]
})    

How to use local docker images with Minikube?

minikube addons enable registry -p minikube

Registry addon on with docker uses 32769 please use that instead of default 5000
For more information see: https://minikube.sigs.k8s.io/docs/drivers/docker

docker tag ubuntu $(minikube ip -p minikube):32769/ubuntu
docker push $(minikube ip -p minikube):32769/ubuntu

OR

minikube addons enable registry
docker tag ubuntu $(minikube ip):32769/ubuntu
docker push $(minikube ip):32769/ubuntu

The above is good enough for development purpose. I am doing this on archlinux.

Java Swing - how to show a panel on top of another panel?

JOptionPane.showInternalInputDialog probably does what you want. If not, it would be helpful to understand what it is missing.

How to send an email using PHP?

<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer


$response = array();
$params = json_decode(file_get_contents("php://input"));

if(!empty($params->email_id)){

    $email_id = $params->email_id;
    $flag=false;
    echo "something";
    if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
    {
        $response['ERROR']='EMAIL address format error'; 
        echo json_encode($response,JSON_UNESCAPED_SLASHES);
        return;
    }
    $sql="SELECT * from sales where email_id ='$email_id' ";

    $result = mysqli_query($conn,$sql);
    $count = mysqli_num_rows($result);

    $to = "[email protected]";
    $subject = "DEMO Subject";
    $messageBody ="demo message .";

    if($count ==0){
        $response["valid"] = false;
        $response["message"] = "User is not registered yet";
        echo json_encode($response);
        return;
    }

    else {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; // authentication enabled
        $mail->IsHTML(true); 
        $mail->SMTPSecure = 'ssl';//turn on to send html email
        // $mail->Host = "ssl://smtp.zoho.com";
        $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail 
        $mail->Port = 465;
        $mail->Username = "[email protected]";
        $mail->Password = "demopassword";
        $mail->SetFrom("[email protected]", "Any demo alert");
        $mail->Subject = $subject;

        $mail->Body = $messageBody;
        $mail->AddAddress($to);
        echo "yes";

        if(!$mail->send()) {
           echo "Mailer Error: " . $mail->ErrorInfo;
       } 
       else {
           echo "Message has been sent successfully";
      }
    }

}
else{
    $response["valid"] = false;
    $response["message"] = "Required field(s) missing";
    echo json_encode($response);
}


?>

The above code is working for me.

Convert double/float to string

See if the BSD C Standard Library has fcvt(). You could start with the source for it that rather than writing your code from scratch. The UNIX 98 standard fcvt() apparently does not output scientific notation so you would have to implement it yourself, but I don't think it would be hard.

How to save data file into .RData?

Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier

date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")

This was you can always keep a check of when it was run

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

You may need to go to Window -> Android SDK Manager -> Packages -> Reload to fetch latest updates and then update the SDK.

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

The format specifers matter: "%s" says that the next string is a narrow string ("ascii" and typically 8 bits per character). "%S" means wide char string. Mixing the two will give "undefined behaviour", which includes printing garbage, just one character or nothing.

One character is printed because wide chars are, for example, 16 bits wide, and the first byte is non-zero, followed by a zero byte -> end of string in narrow strings. This depends on byte-order, in a "big endian" machine, you'd get no string at all, because the first byte is zero, and the next byte contains a non-zero value.

How to convert XML to java.util.Map and vice versa

XStream!

Updated: I added unmarshal part as requested in comments..

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String[] args) {

        Map<String,String> map = new HashMap<String,String>();
        map.put("name","chris");
        map.put("island","faranga");

        XStream magicApi = new XStream();
        magicApi.registerConverter(new MapEntryConverter());
        magicApi.alias("root", Map.class);

        String xml = magicApi.toXML(map);
        System.out.println("Result of tweaked XStream toXml()");
        System.out.println(xml);

        Map<String, String> extractedMap = (Map<String, String>) magicApi.fromXML(xml);
        assert extractedMap.get("name").equals("chris");
        assert extractedMap.get("island").equals("faranga");

    }

    public static class MapEntryConverter implements Converter {

        public boolean canConvert(Class clazz) {
            return AbstractMap.class.isAssignableFrom(clazz);
        }

        public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

            AbstractMap map = (AbstractMap) value;
            for (Object obj : map.entrySet()) {
                Map.Entry entry = (Map.Entry) obj;
                writer.startNode(entry.getKey().toString());
                Object val = entry.getValue();
                if ( null != val ) {
                    writer.setValue(val.toString());
                }
                writer.endNode();
            }

        }

        public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

            Map<String, String> map = new HashMap<String, String>();

            while(reader.hasMoreChildren()) {
                reader.moveDown();

                String key = reader.getNodeName(); // nodeName aka element's name
                String value = reader.getValue();
                map.put(key, value);

                reader.moveUp();
            }

            return map;
        }

    }

}

Format timedelta to string

I suggest the following method so that we can utilize the standard formatting function, pandas.Timestamp.strftime!

from pandas import Timestamp, Timedelta

(Timedelta("2 hours 30 min") + Timestamp("00:00:00")).strftime("%H:%M")

How to disable Python warnings?

If you know what are the useless warnings you usually encounter, you can filter them by message.

import warnings

#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered") 
warnings.filterwarnings("ignore", message="invalid value encountered")

html table span entire width?

<table border="1"; width=100%>

works for me.

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

First go to Wamp->Apache->Service->Test Port 80

If its being user by Microsoft HTTPAPI / 2.0

Then the solution is to manually stop the service named web deployment agent service

If you have Microsoft Sql Server installed, even though the IIS service is disabled, it keeps a web service named httpapi2.0 running.

How to change the font color in the textbox in C#?

RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.

How to embed YouTube videos in PHP?

You can do this simple with Joomla. Let me assume a sample YouTube URL - https://www.youtube.com/watch?v=ndmXkyohT1M

<?php 
$youtubeUrl =  JUri::getInstance('https://www.youtube.com/watch?v=ndmXkyohT1M');
$videoId = $youtubeUrl->getVar('v'); ?>

<iframe id="ytplayer" type="text/html" width="640" height="390"  src="http://www.youtube.com/embed/<?php echo $videoId; ?>"  frameborder="0"/>

javascript object max size limit

Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:

var str;

document.getElementById('theButton').onclick = function() {
  var build, counter;

  if (!str) {
    str = "0123456789";
    build = [];
    for (counter = 0; counter < 900; ++counter) {
      build.push(str);
    }
    str = build.join("");
  }
  else {
    str += str;
  }
  display("str.length = " + str.length);
};

Live copy

Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:

str.length = 9000
str.length = 18000
str.length = 36000
str.length = 72000
str.length = 144000
str.length = 288000
str.length = 576000
str.length = 1152000
str.length = 2304000
str.length = 4608000
str.length = 9216000
str.length = 18432000

...and I'm quite sure I could got a lot higher than that.

So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET which means you're running into the length limit of a GET request, because GET parameters are put in the query string. Details here.

You need to switch to using POST instead. In a POST request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.

Oracle - how to remove white spaces?

Say, we have a column with values consisting of alphanumeric characters and underscore only. We need to trim this column off all spaces, tabs or whatever white characters. The below example will solve the problem. The trimmed one and the original one both are being displayed for comparison. select '/'||REGEXP_REPLACE(my_column,'[^A-Z,^0-9,^_]','')||'/' my_column,'/'||my_column||'/' from my_table;

ASP.NET Core Web API exception handling

Your best bet is to use middleware to achieve logging you're looking for. You want to put your exception logging in one middleware and then handle your error pages displayed to the user in a different middleware. That allows separation of logic and follows the design Microsoft has laid out with the 2 middleware components. Here's a good link to Microsoft's documentation: Error Handling in ASP.Net Core

For your specific example, you may want to use one of the extensions in the StatusCodePage middleware or roll your own like this.

You can find an example here for logging exceptions: ExceptionHandlerMiddleware.cs

public void Configure(IApplicationBuilder app)
{
    // app.UseErrorPage(ErrorPageOptions.ShowAll);
    // app.UseStatusCodePages();
    // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
    // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
    // app.UseStatusCodePagesWithRedirects("~/errors/{0}");
    // app.UseStatusCodePagesWithRedirects("/base/errors/{0}");
    // app.UseStatusCodePages(builder => builder.UseWelcomePage());
    app.UseStatusCodePagesWithReExecute("/Errors/{0}");  // I use this version

    // Exception handling logging below
    app.UseExceptionHandler();
}

If you don't like that specific implementation, then you can also use ELM Middleware, and here are some examples: Elm Exception Middleware

public void Configure(IApplicationBuilder app)
{
    app.UseStatusCodePagesWithReExecute("/Errors/{0}");
    // Exception handling logging below
    app.UseElmCapture();
    app.UseElmPage();
}

If that doesn't work for your needs, you can always roll your own Middleware component by looking at their implementations of the ExceptionHandlerMiddleware and the ElmMiddleware to grasp the concepts for building your own.

It's important to add the exception handling middleware below the StatusCodePages middleware but above all your other middleware components. That way your Exception middleware will capture the exception, log it, then allow the request to proceed to the StatusCodePage middleware which will display the friendly error page to the user.

How to manage exceptions thrown in filters in Spring?

If you want a generic way, you can define an error page in web.xml:

<error-page>
  <exception-type>java.lang.Throwable</exception-type>
  <location>/500</location>
</error-page>

And add mapping in Spring MVC:

@Controller
public class ErrorController {

    @RequestMapping(value="/500")
    public @ResponseBody String handleException(HttpServletRequest req) {
        // you can get the exception thrown
        Throwable t = (Throwable)req.getAttribute("javax.servlet.error.exception");

        // customize response to what you want
        return "Internal server error.";
    }
}

use jQuery's find() on JSON object

Another option I wanted to mention, you could convert your data into XML and then use jQuery.find(":id='A'") the way you wanted.

There are jQuery plugins to that effect, like json2xml.

Probably not worth the conversion overhead, but that's a one time cost for static data, so it might be useful.

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

TLDR? Try: file = open(filename, encoding='cp437)

Why? When one use:

file = open(filename)
text = file.read()

Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.

If such characters are unneeded, one may decide to replace them by question marks, with:

file = open(filename, errors='replace')

Another workaround is to use:

file = open(filename, errors='ignore')

The characters are then left intact, but other errors will be masked too.

Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):

file = open(filename, encoding='cp437')

Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).

Center Div inside another (100% width) div

The below style to the inner div will center it.

margin: 0 auto;

Django: multiple models in one template using forms

I just was in about the same situation a day ago, and here are my 2 cents:

1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ .

In a nutshell: Make a form for each model, submit them both to template in a single <form>, using prefix keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent" model before dependant, and use parent's ID for foreign key before commiting save of "child" model. The link has the demo.

2) Maybe formsets can be beaten into doing this, but as far as I delved in, formsets are primarily for entering multiples of the same model, which may be optionally tied to another model/models by foreign keys. However, there seem to be no default option for entering more than one model's data and that's not what formset seems to be meant for.

how to console.log result of this ajax call?

Ajax call error handler will be triggered if the call itself fails.

You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.

e.preventDefault();
$.ajax(
{
    type: 'POST',
    url: requestURI,
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function(result){
        if(result.hasError == true)
        {
            if(result.error_code == 'AUTH_FAILURE')
            {
                //wrong password
                console.log('Recieved authentication error');
                $('#login_errors_auth').fadeIn();
            }
            else
            {
                //generic error here
                $('#login_errors_unknown').fadeIn();
            }
        }
    }
});

Here, "result" is the json object returned form the server which could have a structure like:

$return = array(
        'hasError' => !$validPassword,
        'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));

Python: How do I make a subclass from a superclass?

class Mammal(object): 
#mammal stuff

class Dog(Mammal): 
#doggie stuff

Java: Array with loop

this is actually the summation of an arithmatic progression with common difference as 1. So this is a special case of sum of natural numbers. Its easy can be done with a single line of code.

int i = 100;
// Implement the fomrulae n*(n+1)/2
int sum = (i*(i+1))/2;
System.out.println(sum);

What is the difference between `sorted(list)` vs `list.sort()`?

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

C - reading command line parameters

When you write your main function, you typically see one of two definitions:

  • int main(void)
  • int main(int argc, char **argv)

The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).

The arguments to main are:

  • int argc - the number of arguments passed into your program when it was run. It is at least 1.
  • char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.

Basic Example

For example, you could do this to print out the arguments passed to your C program:

#include <stdio.h>

int main(int argc, char **argv)
{
    for (int i = 0; i < argc; ++i)
    {
        printf("argv[%d]: %s\n", i, argv[i]);
    }
}

I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.

[birryree@lilun c_code]$ gcc -std=c99 args.c

Now run it...

[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there

So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.

So basically, if you wanted a single parameter, you could say...

./myprogram integral


A Simple Case for You

And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.

So in your code...

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

int main(int argc, char **argv)
{
    if (argc < 2) // no arguments were passed
    {
        // do something
    }

    if (strcmp("integral", argv[1]) == 0)
    {
        runIntegral(...); //or something
    }
    else
    {
        // do something else.
    }
}

Better command line parsing

Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.

Set Google Chrome as the debugging browser in Visual Studio

If you don't see the "Browse With..." option stop debugging first. =)

How to search contents of multiple pdf files?

There is another utility called ripgrep-all, which is based on ripgrep.

It can handle more than just PDF documents, like Office documents and movies, and the author claims it is faster than pdfgrep.

Command syntax for recursively searching the current directory, and the second one limits to PDF files only:

rga 'pattern' .
rga --type pdf 'pattern' .

How to center div vertically inside of absolutely positioned parent div

You may use display:table/table-cell;

_x000D_
_x000D_
.a{_x000D_
   position: absolute; _x000D_
  left: 50px; _x000D_
  top: 50px;_x000D_
  display:table;_x000D_
}_x000D_
.b{_x000D_
  text-align: left; _x000D_
  display:table-cell;_x000D_
  height: 56px;_x000D_
  vertical-align: middle;_x000D_
  background-color: pink;_x000D_
}_x000D_
.c {_x000D_
  background-color: lightblue;_x000D_
}
_x000D_
<div class="a">_x000D_
  <div  class="b">_x000D_
    <div class="c" >test</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

builder for HashMap

You can use:

HashMap<String,Integer> m = Maps.newHashMap(
    ImmutableMap.of("a",1,"b",2)
);

It's not as classy and readable, but does the work.

How to run only one task in ansible playbook?

I would love the ability to use a role as a collection of tasks such that, in my playbook, I can choose which subset of tasks to run. Unfortunately, the playbook can only load them all in and then you have to use the --tags option on the cmdline to choose which tasks to run. The problem with this is that all of the tasks will run unless you remember to set --tags or --skip-tags.

I have set up some tasks, however, with a when: clause that will only fire if a var is set.

e.g.

# role/stuff/tasks/main.yml
- name: do stuff
  when: stuff|default(false)

Now, this task will not fire by default, but only if I set the stuff=true

$ ansible-playbook -e '{"stuff":true}'

or in a playbook:

roles:
- {"role":"stuff", "stuff":true}

How to check if a value is not null and not empty string in JS

When we code empty in essence could mean any one of the following given the circumstances;

  • 0 as in number value
  • 0.0 as in float value
  • '0' as in string value
  • '0.0' as in string value
  • null as in Null value, as per chance it could also capture undefined or it may not
  • undefined as in undefined value
  • false as in false truthy value, as per chance 0 also as truthy but what if we want to capture false as it is
  • '' empty sting value with no white space or tab
  • ' ' string with white space or tab only

In real life situation as OP stated we may wish to test them all or at times we may only wish to test for limited set of conditions.

Generally if(!a){return true;} serves its purpose most of the time however it will not cover wider set of conditions.

Another hack that has made its round is return (!value || value == undefined || value == "" || value.length == 0);

But what if we need control on whole process?

There is no simple whiplash solution in native core JavaScript it has to be adopted. Considering we drop support for legacy IE11 (to be honest even windows has so should we) below solution born out of frustration works in all modern browsers;

 function empty (a,b=[])
 {if(!Array.isArray(b)) return; 
 var conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
 if(conditions.includes(a)|| (typeof a === 'string' && conditions.includes(a.toString().trim())))
 {return true;};
 return false;};`

Logic behind the solution is function has two parameters a and b, a is value we need to check, b is a array with set conditions we need to exclude from predefined conditions as listed above. Default value of b is set to an empty array [].

First run of function is to check if b is an array or not, if not then early exit the function.

next step is to compute array difference from [null,'0','0.0',false,undefined,''] and from array b. if b is an empty array predefined conditions will stand else it will remove matching values.

conditions = [predefined set] - [to be excluded set] filter function does exactly that make use of it. Now that we have conditions in array set all we need to do is check if value is in conditions array. includes function does exactly that no need to write nasty loops of your own let JS engine do the heavy lifting.

Gotcha if we are to convert a into string for comparison then 0 and 0.0 would run fine however Null and Undefined would through error blocking whole script. We need edge case solution. Below simple || covers the edge case if first condition is not satisfied. Running another early check through include makes early exit if not met.

if(conditions.includes(a)||  (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim())))

trim() function will cover for wider white spaces and tabs only value and will only come into play in edge case scenario.

Play ground

_x000D_
_x000D_
function empty (a,b=[]){
if(!Array.isArray(b)) return;
conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
if(conditions.includes(a)|| 
(['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
 return true;
} 
return false;
}

console.log('1 '+empty());
console.log('2 '+empty(''));
console.log('3 '+empty('      '));
console.log('4 '+empty(0));
console.log('5 '+empty('0'));
console.log('6 '+empty(0.0));
console.log('7 '+empty('0.0'));
console.log('8 '+empty(false));
console.log('9 '+empty(null));
console.log('10 '+empty(null,[null]));
console.log('11 dont check 0 as number '+empty(0,['0']));
console.log('12 dont check 0 as string '+empty('0',['0']));
console.log('13 as number for false as value'+empty(false,[false]));
_x000D_
_x000D_
_x000D_

Lets make it complex - what if our value to compare is array its self and can be as deeply nested it can be. what if we are to check if any value in array is empty, it can be an edge business case.

_x000D_
_x000D_
function empty (a,b=[]){
    if(!Array.isArray(b)) return;

    conditions=[null,'0','0.0',false,undefined,''].filter(x => !b.includes(x));
    if(Array.isArray(a) && a.length > 0){
    for (i = 0; i < a.length; i++) { if (empty(a[i],b))return true;} 
    } 
    
    if(conditions.includes(a)|| 
    (['string', 'number'].includes(typeof a) && conditions.includes(a.toString().trim()))){
     return true;
    } 
    return false;
    }

console.log('checking for all values '+empty([1,[0]]));
console.log('excluding for 0 from condition '+empty([1,[0]], ['0']));
_x000D_
_x000D_
_x000D_

it simple and wider use case function that I have adopted in my framework;

  • Gives control over as to what exactly is the definition of empty in a given situation
  • Gives control over to redefine conditions of empty
  • Can compare for almost for every thing from string, number, float, truthy, null, undefined and deep arrays
  • Solution is drawn keeping in mind the resuability and flexibility. All other answers are suited in case if simple one or two cases are to be dealt with. However, there is always a case when definition of empty changes while coding above snippets make work flawlessly in that case.

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.