Programs & Examples On #Opengrok

OpenGrok is a code search tool from Oracle.

Why number 9 in kill -9 command in unix?

I think a better answer here is simply this:

mike@sleepycat:~?  kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL   5) SIGTRAP  
 6) SIGABRT  7) SIGBUS   8) SIGFPE   9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT   17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF 28) SIGWINCH    29) SIGIO   30) SIGPWR
31) SIGSYS  34) SIGRTMIN    35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3
38) SIGRTMIN+4  39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7
58) SIGRTMAX-6  59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

As for the "significance" of 9... I would say there is probably none. According to The Linux Programming Interface(p 388):

Each signal is defined as a unique (small) integer, starting sequentially from 1. These integers are defined in with symbolic names of the form SIGxxxx . Since the actual numbers used for each signal vary across implementations, it is these symbolic names that are always used in programs.

multiprocessing.Pool: When to use apply, apply_async or map?

Regarding apply vs map:

pool.apply(f, args): f is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args).

pool.map(f, iterable): This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.

Items in JSON object are out of order using "json.dumps"?

As others have mentioned the underlying dict is unordered. However there are OrderedDict objects in python. ( They're built in in recent pythons, or you can use this: http://code.activestate.com/recipes/576693/ ).

I believe that newer pythons json implementations correctly handle the built in OrderedDicts, but I'm not sure (and I don't have easy access to test).

Old pythons simplejson implementations dont handle the OrderedDict objects nicely .. and convert them to regular dicts before outputting them.. but you can overcome this by doing the following:

class OrderedJsonEncoder( simplejson.JSONEncoder ):
   def encode(self,o):
      if isinstance(o,OrderedDict.OrderedDict):
         return "{" + ",".join( [ self.encode(k)+":"+self.encode(v) for (k,v) in o.iteritems() ] ) + "}"
      else:
         return simplejson.JSONEncoder.encode(self, o)

now using this we get:

>>> import OrderedDict
>>> unordered={"id":123,"name":"a_name","timezone":"tz"}
>>> ordered = OrderedDict.OrderedDict( [("id",123), ("name","a_name"), ("timezone","tz")] )
>>> e = OrderedJsonEncoder()
>>> print e.encode( unordered )
{"timezone": "tz", "id": 123, "name": "a_name"}
>>> print e.encode( ordered )
{"id":123,"name":"a_name","timezone":"tz"}

Which is pretty much as desired.

Another alternative would be to specialise the encoder to directly use your row class, and then you'd not need any intermediate dict or UnorderedDict.

Find out where MySQL is installed on Mac OS X

for me it was installed in /usr/local/opt

The command I used for installation is brew install [email protected]

ASP.NET MVC: What is the purpose of @section?

A good example is Javascript. You want this to be at the bottom of the page that is rendered in the browser because this is best practice.

How would you do this from a View based on a Layout/Masterpage where you can only access the middle of the page?

You do this by declaring a Scripts section at the bottom of the Layout page. Then you can add content, in this case Javascript includes (I hope!), from your View page to the bottom of your layout page.

what exactly is device pixel ratio?

Device Pixel Ratio == CSS Pixel Ratio

In the world of web development, the device pixel ratio (also called CSS Pixel Ratio) is what determines how a device's screen resolution is interpreted by the CSS.

A browser's CSS calculates a device's logical (or interpreted) resolution by the formula:

formula

For example:

Apple iPhone 6s

  • Actual Resolution: 750 x 1334
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

When viewing a web page, the CSS will think the device has a 375x667 resolution screen and Media Queries will respond as if the screen is 375x667. But the rendered elements on the screen will be twice as sharp as an actual 375x667 screen because there are twice as many physical pixels in the physical screen.

Some other examples:

Samsung Galaxy S4

  • Actual Resolution: 1080 x 1920
  • CSS Pixel Ratio: 3
  • Logical Resolution:

formula

iPhone 5s

  • Actual Resolution: 640 x 1136
  • CSS Pixel Ratio: 2
  • Logical Resolution:

formula

Why does the Device Pixel Ratio exist?

The reason that CSS pixel ratio was created is because as phones screens get higher resolutions, if every device still had a CSS pixel ratio of 1 then webpages would render too small to see.

A typical full screen desktop monitor is a roughly 24" at 1920x1080 resolution. Imagine if that monitor was shrunk down to about 5" but had the same resolution. Viewing things on the screen would be impossible because they would be so small. But manufactures are coming out with 1920x1080 resolution phone screens consistently now.

So the device pixel ratio was invented by phone makers so that they could continue to push the resolution, sharpness and quality of phone screens, without making elements on the screen too small to see or read.

Here is a tool that also tells you your current device's pixel density:

http://bjango.com/articles/min-device-pixel-ratio/

Subtract days from a DateTime

DateTime dateForButton = DateTime.Now.AddDays(-1);

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

"Port 4200 is already in use" when running the ng serve command

Port 4200 is already in use. Use '--port' to specify a different port

This means that you already have another service running on port 4200. If this is the case you can either . shut down the other service. use the --port flag when running ng serve like this:

 ng serve --port 9001

Another thing to notice is that, on some machines, the domain localhost may not work. You may see a set of numbers such as 127.0.0.1. When you run ng serve it should show you what URL the server is running on, so be sure to read the messages on your machine to find your exact development URL.

How to check if a folder exists

import java.io.File;
import java.nio.file.Paths;

public class Test
{

  public static void main(String[] args)
  {

    File file = new File("C:\\Temp");
    System.out.println("File Folder Exist" + isFileDirectoryExists(file));
    System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));

  }

  public static boolean isFileDirectoryExists(File file)

  {
    if (file.exists())
    {
      return true;
    }
    return false;
  }

  public static boolean isDirectoryExists(String directoryPath)

  {
    if (!Paths.get(directoryPath).toFile().isDirectory())
    {
      return false;
    }
    return true;
  }

}

Oracle TNS names not showing when adding new connection to SQL Developer

The steps mentioned by Jason are very good and should work. There is a little twist with SQL Developer, though. It caches the connection specifications (host, service name, port) the first time it reads the tnsnames.ora file. Then, it does not invalidate the specs when the original entry is removed from the tnsname.ora file. The cache persists even after SQL Developer has been terminated and restarted. This is not such an illogical way of handling the situation. Even if a tnsnames.ora file is temporarily unavailable, SQL Developer can still make the connection as long as the original specifications are still true. The problem comes with their next little twist. SQL Developer treats service names in the tnsnames.ora file as case-sensitive values when resolving the connection. So if you used to have an entry name ABCD.world in the file and you replaced it with an new entry named abcd.world, SQL Developer would NOT update its connection specs for ABCD.world - it will treat abcd.world as a different connection altogether. Why am I not surprised that an Oracle product would treat as case-sensitive the contents of an oracle-developed file format that is expressly case-insensitive?

Calculate business days

https://github.com/Arbitr108/useful_php Here is a class which can estimate the working days into calendar. So after estimation simply add calendar period to the date you need

Toad for Oracle..How to execute multiple statements?

I prefer the Execute via SQL*Plus option. It's in the little down-arrow menu under the "Execute as script" toolbar button.

Eclipse Bug: Unhandled event loop exception No more handles

I have the same problem. It is caused by a screen capture software hypersnap7. So I think the hotkey conflict is the reason. Reboot computer, don't start other software, start Android Development Tools and watch which software triger the bug.

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

Check if it's visible.

$("#singlechatpanel-1").is(':visible');

Check if it's hidden.

$("#singlechatpanel-1").is(':hidden');

Getting pids from ps -ef |grep keyword

This is available on linux: pidof keyword

Formula to determine brightness of RGB color

The "Accepted" Answer is Incorrect and Incomplete

The only answers that are accurate are the @jive-dadson and @EddingtonsMonkey answers, and in support @nils-pipenbrinck. The other answers (including the accepted) are linking to or citing sources that are either wrong, irrelevant, obsolete, or broken.

Briefly:

  • sRGB must be LINEARIZED before applying the coefficients.
  • Luminance (L or Y) is linear as is light.
  • Perceived lightness (L*) is nonlinear as is human perception.
  • HSV and HSL are not even remotely accurate in terms of perception.
  • The IEC standard for sRGB specifies a threshold of 0.04045 it is NOT 0.03928 (that was from an obsolete early draft).
  • The be useful (i.e. relative to perception), Euclidian distances require a perceptually uniform Cartesian vector space such as CIELAB. sRGB is not one.

What follows is a correct and complete answer:

Because this thread appears highly in search engines, I am adding this answer to clarify the various misconceptions on the subject.

Luminance is a linear measure of light, spectrally weighted for normal vision but not adjusted for the non-linear perception of lightness. It can be a relative measure, Y as in CIEXYZ, or as L, an absolute measure in cd/m2 (not to be confused with L*).

Perceived lightness is used by some vision models such as CIELAB, here L* (Lstar) is a value of perceptual lightness, and is non-linear to approximate the human vision non-linear response curve.

Brightness is a perceptual attribute, it does not have a "physical" measure. However some color appearance models do have a value, usualy denoted as "Q" for perceived brightness, which is different than perceived lightness.

Luma ( prime) is a gamma encoded, weighted signal used in some video encodings (Y´I´Q´). It is not to be confused with linear luminance.

Gamma or transfer curve (TRC) is a curve that is often similar to the perceptual curve, and is commonly applied to image data for storage or broadcast to reduce perceived noise and/or improve data utilization (and related reasons).

To determine perceived lightness, first convert gamma encoded R´G´B´ image values to linear luminance (L or Y ) and then to non-linear perceived lightness (L*)


TO FIND LUMINANCE:

...Because apparently it was lost somewhere...

Step One:

Convert all sRGB 8 bit integer values to decimal 0.0-1.0

  vR = sR / 255;
  vG = sG / 255;
  vB = sB / 255;

Step Two:

Convert a gamma encoded RGB to a linear value. sRGB (computer standard) for instance requires a power curve of approximately V^2.2, though the "accurate" transform is:

sRGB to Linear

Where V´ is the gamma-encoded R, G, or B channel of sRGB.
Pseudocode:

function sRGBtoLin(colorChannel) {
        // Send this function a decimal sRGB gamma encoded color value
        // between 0.0 and 1.0, and it returns a linearized value.

    if ( colorChannel <= 0.04045 ) {
            return colorChannel / 12.92;
        } else {
            return pow((( colorChannel + 0.055)/1.055),2.4));
        }
    }

Step Three:

To find Luminance (Y) apply the standard coefficients for sRGB:

Apply coefficients Y = R * 0.2126 + G * 0.7152 + B *  0.0722

Pseudocode using above functions:

Y = (0.2126 * sRGBtoLin(vR) + 0.7152 * sRGBtoLin(vG) + 0.0722 * sRGBtoLin(vB))

TO FIND PERCEIVED LIGHTNESS:

Step Four:

Take luminance Y from above, and transform to L*

L* from Y equation
Pseudocode:

function YtoLstar(Y) {
        // Send this function a luminance value between 0.0 and 1.0,
        // and it returns L* which is "perceptual lightness"

    if ( Y <= (216/24389) {       // The CIE standard states 0.008856 but 216/24389 is the intent for 0.008856451679036
            return Y * (24389/27);  // The CIE standard states 903.3, but 24389/27 is the intent, making 903.296296296296296
        } else {
            return pow(Y,(1/3)) * 116 - 16;
        }
    }

L* is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey". L* = 50 is the equivalent of Y = 18.4, or in other words an 18% grey card, representing the middle of a photographic exposure (Ansel Adams zone V).

References:

IEC 61966-2-1:1999 Standard
Wikipedia sRGB
Wikipedia CIELAB
Wikipedia CIEXYZ
Charles Poynton's Gamma FAQ

Django: save() vs update() to update the database?

Using update directly is more efficient and could also prevent integrity problems.

From the official documentation https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.update

If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:

e = Entry.objects.get(id=10)
e.comments_on = False
e.save()

…do this:

Entry.objects.filter(id=10).update(comments_on=False)

Using update() also prevents a race condition wherein something might change in your database in the short period of time between loading the object and calling save().

CREATE DATABASE permission denied in database 'master' (EF code-first)

I encountered what appeared to be this error. I was running on windows and found my administrator windows user did not have administrator privileges to database.

  1. Shut down SQL Server from ‘Services’

Disable Services

  1. Open cmd window (as administrator) and run single-user mode as local admin with this command (the version of MSSQL may differ):
"C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" -m -s SQLEXPRESS
  1. Open another cmd window (as administrator)
  2. Open sqlcmd on that terminal with:
sqlcmd -S .\SQLEXPRESS
  1. Now add the sysadmin role to your user:
sp_addsrvrolemember 'domain\user', 'sysadmin'
GO
  1. Re-enable SQL Server from ‘Services’

Credit to: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/76fc84f9-437c-4e71-ba3d-3c9ae794a7c4/

Formatting code in Notepad++

No. Notepad++ can't format by itself. Formatting can easily be accomplished in many IDEs like Eclipse, NetBeans, Visual Studio [Code].

Help needed with Median If in Excel

Make a third column that has values like:

=IF(A1="Airline",B1)

=IF(A2="Airline",B2) etc

Then just perform a median on the new column.

String variable interpolation Java

Note that there is no variable interpolation in Java. Variable interpolation is variable substitution with its value inside a string. An example in Ruby:

#!/usr/bin/ruby

age = 34
name = "William"

puts "#{name} is #{age} years old"

The Ruby interpreter automatically replaces variables with its values inside a string. The fact, that we are going to do interpolation is hinted by sigil characters. In Ruby, it is #{}. In Perl, it could be $, % or @. Java would only print such characters, it would not expand them.

Variable interpolation is not supported in Java. Instead of this, we have string formatting.

package com.zetcode;

public class StringFormatting 
{
    public static void main(String[] args) 
    {
        int age = 34;
        String name = "William";

        String output = String.format("%s is %d years old.", name, age);
    
        System.out.println(output);
    }
}

In Java, we build a new string using the String.format() method. The outcome is the same, but the methods are different.

See http://en.wikipedia.org/wiki/Variable_interpolation

Edit As of 2019, JEP 326 (Raw String Literals) was withdrawn and superseded by multiple JEPs eventually leading to JEP 378: Text Blocks delivered in Java 15.

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over the format when desired.

However, still no string interpolation:

Non-Goals: … Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method String::formatted aids in situations where interpolation might be desired.

How to handle calendar TimeZones using Java?

java.time

The modern approach uses the java.time classes that supplanted the troublesome legacy date-time classes bundled with the earliest versions of Java.

The java.sql.Timestamp class is one of those legacy classes. No longer needed. Instead use Instant or other java.time classes directly with your database using JDBC 4.2 and later.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myResultSet.getObject( … , Instant.class ) ; 

If you must interoperate with an existing Timestamp, convert immediately into java.time via the new conversion methods added to the old classes.

Instant instant = myTimestamp.toInstant() ;

To adjust into another time zone, specify the time zone as a ZoneId object. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;

Apply to the Instant to produce a ZonedDateTime object.

ZonedDateTime zdt = instant.atZone( z ) ;

To generate a string for display to the user, search Stack Overflow for DateTimeFormatter to find many discussions and examples.

Your Question is really about going the other direction, from user data-entry to the date-time objects. Generally best to break your data-entry into two parts, a date and a time-of-day.

LocalDate ld = LocalDate.parse( dateInput , DateTimeFormatter.ofPattern( "M/d/uuuu" , Locale.US ) ) ;
LocalTime lt = LocalTime.parse( timeInput , DateTimeFormatter.ofPattern( "H:m a" , Locale.US ) ) ;

Your Question is not clear. Do you want to interpret the date and the time entered by the user to be in UTC? Or in another time zone?

If you meant UTC, create a OffsetDateTime with an offset using the constant for UTC, ZoneOffset.UTC.

OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;

If you meant another time zone, combine along with a time zone object, a ZoneId. But which time zone? You might detect a default time zone. Or, if critical, you must confirm with the user to be certain of their intention.

ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

To get a simpler object that is always in UTC by definition, extract an Instant.

Instant instant = odt.toInstant() ;

…or…

Instant instant = zdt.toInstant() ; 

Send to your database.

myPreparedStatement.setObject( … , instant ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

Based on Cameron's initial answer, here is what I've just added at my enhanced version of SilverFlow library's FloatingWindowHost (copying from FloatingWindowHost.cs at http://clipflair.codeplex.com source code)

    public int MaxZIndex
    {
      get {
        return FloatingWindows.Aggregate(-1, (maxZIndex, window) => {
          int w = Canvas.GetZIndex(window);
          return (w > maxZIndex) ? w : maxZIndex;
        });
      }
    }

    private void SetTopmost(UIElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        Canvas.SetZIndex(element, MaxZIndex + 1);
    }

Worth noting regarding the code above that Canvas.ZIndex is an attached property available for UIElements in various containers, not just used when being hosted in a Canvas (see Controlling rendering order (ZOrder) in Silverlight without using the Canvas control). Guess one could even make a SetTopmost and SetBottomMost static extension method for UIElement easily by adapting this code.

Google maps Marker Label with multiple characters

A much simpler solution to this problem that allows letters, numbers and words as the label is the following code. More specifically, the line of code starting with "icon:". Any string or variable could be substituted for 'k'.

for (i = 0; i < locations.length; i++) 
      { 
      k = i + 1;
      marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),     
      map: map,
      icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});

--- the locations array holds the lat and long and k is the row number for the address I was mapping. In other words if I had a 100 addresses to map my marker labels would be 1 to 100.

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

How to recover the deleted files using "rm -R" command in linux server?

Not possible with standard unix commands. You might have luck with a file recovery utility. Also, be aware, using rm changes the table of contents to mark those blocks as available to be overwritten, so simply using your computer right now risks those blocks being overwritten permanently. If it's critical data, you should turn off the computer before the file sectors gets overwritten. Good luck!

Some restore utility: http://www.ubuntugeek.com/recover-deleted-files-with-foremostscalpel-in-ubuntu.html

Forum where this was previously answered: http://webcache.googleusercontent.com/search?q=cache:m4hiPw-_GekJ:ubuntuforums.org/archive/index.php/t-1134955.html+&cd=1&hl=en&ct=clnk&gl=us

Delete the first five characters on any line of a text file in Linux with sed

sed 's/^.....//'

means

replace ("s", substitute) beginning-of-line then 5 characters (".") with nothing.

There are more compact or flexible ways to write this using sed or cut.

How to uninstall Jenkins?

run this on Terminal:

sh "/Library/Application Support/Jenkins/Uninstall.command"

How to search a specific value in all tables (PostgreSQL)?

How about dumping the contents of the database, then using grep?

$ pg_dump --data-only --inserts -U postgres your-db-name > a.tmp
$ grep United a.tmp
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('GB', 'United Kingdom');

The same utility, pg_dump, can include column names in the output. Just change --inserts to --column-inserts. That way you can search for specific column names, too. But if I were looking for column names, I'd probably dump the schema instead of the data.

$ pg_dump --data-only --column-inserts -U postgres your-db-name > a.tmp
$ grep country_code a.tmp
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('US', 'United  States');
INSERT INTO countries (iso_country_code, iso_country_name) VALUES ('GB', 'United Kingdom');

Convert/cast an stdClass object to another class

I have a very similar problem. Simplified reflection solution worked just fine for me:

public static function cast($destination, \stdClass $source)
{
    $sourceReflection = new \ReflectionObject($source);
    $sourceProperties = $sourceReflection->getProperties();
    foreach ($sourceProperties as $sourceProperty) {
        $name = $sourceProperty->getName();
        $destination->{$name} = $source->$name;
    }
    return $destination;
}

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

Make sure the target window that you (or Facebook) is posting a message to, has completed loading. Most of the times I've gotten this error were when an iframe I was sending messages to had failed to load.

Disable building workspace process in Eclipse

You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically from the main menu is unchecked.

Bootstrap get div to align in the center

When I align elements in center I use the bootstrap class text-center:

<div class="text-center">Centered content goes here</div>

Bootstrap full-width text-input within inline-form

As stated in a similar question, try removing instances of the input-group class and see if that helps.

refering to bootstrap:

Individual form controls automatically receive some global styling. All textual , , and elements with .form-control are set to width: 100%; by default. Wrap labels and controls in .form-group for optimum spacing.

How do I programmatically determine operating system in Java?

I think following can give broader coverage in fewer lines

import org.apache.commons.exec.OS;

if (OS.isFamilyWindows()){
                //load some property
            }
else if (OS.isFamilyUnix()){
                //load some other property
            }

More details here: https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html

Eclipse CDT: Symbol 'cout' could not be resolved

For me it helped to enable the automated discovery in Properties -> C/C++-Build -> Discovery Options to resolve this problem.

How to read a .properties file which contains keys that have a period character using Shell script

I found using while IFS='=' read -r to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop.

I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).

The solution does sourcing but massages the contents before sourcing:

#!/usr/bin/env bash

source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')

echo $db_uat_user

Explanation:

grep -v '^ *#': discard comment lines grep '[^ ] *=': discards lines without = split($0,a,"="): splits line at = and stores into array a, i.e. a[1] is the key, a[2] is the value gensub(/\./, "_", "g", a[1]): replaces . with _ print gensub... "=" a[2]} concatenates the result of gensub above with = and value.

Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.

What is RSS and VSZ in Linux memory management

I think much has already been said, about RSS vs VSZ. From an administrator/programmer/user perspective, when I design/code applications I am more concerned about the RSZ, (Resident memory), as and when you keep pulling more and more variables (heaped) you will see this value shooting up. Try a simple program to build malloc based space allocation in loop, and make sure you fill data in that malloc'd space. RSS keeps moving up. As far as VSZ is concerned, it's more of virtual memory mapping that linux does, and one of its core features derived out of conventional operating system concepts. The VSZ management is done by Virtual memory management of the kernel, for more info on VSZ, see Robert Love's description on mm_struct and vm_struct, which are part of basic task_struct data structure in kernel.

How do I download a binary file over HTTP?

if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile

require 'pull_tempfile'

PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
  CSV.foreach(tmp_file.path) do |row|
    # ....
  end
end

Can't escape the backslash with regex?

The backslash \ is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.

\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.

ref : http://www.regular-expressions.info/reference.html

How can I restore the MySQL root user’s full privileges?

  1. "sudo cat /etc/mysql/debian.cnf" to use debian-sys-maint user
  2. login by this user throgh "mysql -u saved-username -p;", then enter the saved password.
  3. mysql> UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
  4. mysql> FLUSH PRIVILEGES;
  5. mysql> exit
  6. reboot Thanks

How to determine if a string is a number with C++?

I'd suggest a regex approach. A full regex-match (for example, using boost::regex) with

-?[0-9]+([\.][0-9]+)?

would show whether the string is a number or not. This includes positive and negative numbers, integer as well as decimal.

Other variations:

[0-9]+([\.][0-9]+)?

(only positive)

-?[0-9]+

(only integer)

[0-9]+

(only positive integer)

How to set the UITableView Section title programmatically (iPhone/iPad)?

Note that -(NSString *)tableView: titleForHeaderInSection: is not called by UITableView if - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section is implemented in delegate of UITableView;

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

OpenCV - Saving images to a particular folder of choice

You can use this simple code in loop by incrementing count

cv2.imwrite("C:\Sharat\Python\Images\frame%d.jpg" % count, image)

images will be saved in the folder by name line frame0.jpg, frame1.jpg frame2.jpg etc..

for loop in Python

The answer is good, but for the people that want this with range(), the form to do is:

range(end):

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(start,end):

 >>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(start,end, step):

 >>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]

rawQuery(query, selectionArgs)

Maybe this can help you

Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0) 
{               
    c.moveToFirst();
    do {
        id[i] = c.getInt(c.getColumnIndex("field_name"));
        i++;
    } while (c.moveToNext());
    c.close();
}

Easy way to write contents of a Java InputStream to an OutputStream

As WMR mentioned, org.apache.commons.io.IOUtils from Apache has a method called copy(InputStream,OutputStream) which does exactly what you're looking for.

So, you have:

InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();

...in your code.

Is there a reason you're avoiding IOUtils?

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

Component is not part of any NgModule or the module has not been imported into your module

In my case, Angular 6, I renamed folder and file names of my modules from google.map.module.ts to google-map.module.ts. In order to compile without overlay with old module and component names, ng compiler compiled with no error. enter image description here

In app.routes.ts:

     {
        path: 'calendar', 
        loadChildren: './views/app-calendar/app-calendar.module#AppCalendarModule', 
        data: { title: 'Calendar', breadcrumb: 'CALENDAR'}
      },

In google-map.routing.ts

import { GoogleMapComponent } from './google-map.component';
const routes: Routes = [
  {
    path: '', component: GoogleMapComponent, data: { title: 'Coupon Map' }
  }
];
@NgModule({
    exports: [RouterModule],
    imports: [RouterModule.forChild(routes)]
})
export class GoogleMapRoutingModule { }

In google-map.module.ts:

import { GoogleMapRoutingModule } from './google-map.routing';
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    CommonModule,
    GoogleMapRoutingModule,
  ],
  exports: [GoogleMapComponent],
  declarations: [GoogleMapComponent]
})
export class GoogleMapModule { }

How to Auto resize HTML table cell to fit the text size

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

How do I calculate the normal vector of a line segment?

This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y') is perpendicular to the line connecting (x1,y1) and (x2,y2). This line has direction (x2-x1,y2-y1), or (dx,dy).
So,

(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0

The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx) or (-dy,dx)

Determine the type of an object?

type() is a better solution than isinstance(), particularly for booleans:

True and False are just keywords that mean 1 and 0 in python. Thus,

isinstance(True, int)

and

isinstance(False, int)

both return True. Both booleans are an instance of an integer. type(), however, is more clever:

type(True) == int

returns False.

How to execute a file within the python interpreter?

I am not an expert but this is what I noticed:

if your code is mycode.py for instance, and you type just 'import mycode', Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually 'from mycode import *' if you want to make all variables available to the interpreter.

Phonegap Cordova installation Windows

I faced this same error too. And i even tried downloading the PhoneGap master from GitHub,but i found out that what i got was Phonegap 2.9. I eventually had to download the Cordova 3 Source

Follow this steps to get it.

  1. Download and unzip the Cordova 3 Source
  2. Run the template.bat in the cordova-wp8 folder
  3. Copy the generated Zip files to your Visual studio template folder

How do I draw a shadow under a UIView?

Same solution, but just to remind you: You can define the shadow directly in the storyboard.

Ex:

enter image description here

Object not found! The requested URL was not found on this server. localhost

If the page you are visiting is index.php, then your url should look like

http://localhost/test/content/home/ OR http://localhost/test/content/home/index.php

not the way you specified - http://localhost/test/content/home

Insert a background image in CSS (Twitter Bootstrap)

Adding background image on html, body or a wrapper element to achieve background image will cause problems with padding. Check this ticket https://github.com/twitter/bootstrap/issues/3169 on github. ShaunR's comment and also one of the creators response to this. The given solution in created ticket doesn't solve the problem, but it at least gets things going if you aren't using responsive features.

Assuming that you are using container without responsive features, and have a width of 960px, and want to achieve 10px padding, you set:

.container {
   min-width: 940px;
   padding: 10px;
}

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I received the same error (SCRIPT7002: XMLHttpRequest: Network Error 0x80004004, Operation aborted), in our case it was because of JavaScript's same origin policy.

Our web app was making a JQuery AJAX call to our server on Port 8080. The call was getting intercepted and re-routed over SSL (due to server rules mandating that incoming traffic use SSL).

Once we made our web app load through the SSL port the issue was fixed.

How to show validation message below each textbox using jquery?

This is the simple solution may work for you.

Check this solution

$('form').on('submit', function (e) {
e.preventDefault();
var emailBox=$("#email");
var passBox=$("#password");
if (!emailBox.val() || !passBox.val()) {
    $(".validationText").text("Please Enter Value").show();
}
else if(!IsEmail(emailBox.val()))
{
    emailBox.prev().text("Invalid E-mail").show();
}
$("input#email, input#password").focus(function(){
    $(this).prev(".validationText").hide();
});});

using javascript to detect whether the url exists before display in iframe

I created this method, it is ideal because it aborts the connection without downloading it in its entirety, ideal for checking if videos or large images exist, decreasing the response time and the need to download the entire file

// if-url-exist.js v1
function ifUrlExist(url, callback) {
    let request = new XMLHttpRequest;
    request.open('GET', url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.setRequestHeader('Accept', '*/*');
    request.onprogress = function(event) {
        let status = event.target.status;
        let statusFirstNumber = (status).toString()[0];
        switch (statusFirstNumber) {
            case '2':
                request.abort();
                return callback(true);
            default:
                request.abort();
                return callback(false);
        };
    };
    request.send('');
};

Example of use:

ifUrlExist(url, function(exists) {
    console.log(exists);
});

Scala: write string to file in one statement

Through the magic of the semicolon, you can make anything you like a one-liner.

import java.io.PrintWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
val outfile = java.io.File.createTempFile("", "").getPath
val outstream = new PrintWriter(Files.newBufferedWriter(Paths.get(outfile)
  , StandardCharsets.UTF_8
  , StandardOpenOption.WRITE)); outstream.println("content"); outstream.flush(); outstream.close()

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Try this, pick or create one column and make that value required so that it's always populated such as title. A field that doesn't hold the name of the folder. Then in your filter put the filter you wanted that will select only the files you want. Then add an or to your filter, select your "required" field then set it equal to and leave the filter blank. Since all folders will have a blank in this required field your folders will show up with your files.

Check if TextBox is empty and return MessageBox?

For multiple text boxes - add them into a list and show all errors into 1 messagebox.

// Append errors into 1 Message Box      

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

 if (string.IsNullOrEmpty(textBox1.Text))
    {
        errors.Add("User");
    }

    if (string.IsNullOrEmpty(textBox2.Text))
    {
        errors.Add("Document Ref Code");
    }

    if (errors.Count > 0)
    {
        errors.Insert(0, "The following fields are empty:");
        string message = string.Join(Environment.NewLine, errors);
        MessageBox.Show(message, "errors", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    } 

Where to put a textfile I want to use in eclipse?

One path to take is to

  1. Add the file you're working with to the classpath
  2. Use the resource loader to locate the file:

        URL url = Test.class.getClassLoader().getResource("myfile.txt");
        System.out.println(url.getPath());
        ...
    
  3. Open it

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

How to open a web server port on EC2 instance

Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".

Go to the "Network & Security" -> Security Group settings in the left hand navigation

enter image description here Find the Security Group that your instance is apart of Click on Inbound Rules enter image description here Use the drop down and add HTTP (port 80) enter image description here Click Apply and enjoy

How to expand a list to function arguments in Python

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

Why is __dirname not defined in node REPL?

In ES6 use:

import path from 'path';
const __dirname = path.resolve();

also available when node is called with --experimental-modules

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

What is an attribute in Java?

A class is an element in object oriented programming that aggregates attributes(fields) - which can be public accessible or not - and methods(functions) - which also can be public or private and usually writes/reads those attributes.

so you can have a class like Array with a public attribute lengthand a public method sort().

What are the true benefits of ExpandoObject?

The real benefit for me is the totally effortless data binding from XAML:

public dynamic SomeData { get; set; }

...

SomeData.WhatEver = "Yo Man!";

...

 <TextBlock Text="{Binding SomeData.WhatEver}" />

Internal Error 500 Apache, but nothing in the logs?

Why are the 500 Internal Server Errors not being logged into your apache error logs?

The errors that cause your 500 Internal Server Error are coming from a PHP module. By default, PHP does NOT log these errors. Reason being you want web requests go as fast as physically possible and it's a security hazard to log errors to screen where attackers can observe them.

These instructions to enable Internal Server Error Logging are for Ubuntu 12.10 with PHP 5.3.10 and Apache/2.2.22.

Make sure PHP logging is turned on:

  1. Locate your php.ini file:

    el@apollo:~$ locate php.ini
    /etc/php5/apache2/php.ini
    
  2. Edit that file as root:

    sudo vi /etc/php5/apache2/php.ini
    
  3. Find this line in php.ini:

    display_errors = Off
    
  4. Change the above line to this:

    display_errors = On
    
  5. Lower down in the file you'll see this:

    ;display_startup_errors
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    ;error_reporting
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    
  6. The semicolons are comments, that means the lines don't take effect. Change those lines so they look like this:

    display_startup_errors = On
    ;   Default Value: Off
    ;   Development Value: On
    ;   Production Value: Off
    
    error_reporting = E_ALL
    ;   Default Value: E_ALL & ~E_NOTICE
    ;   Development Value: E_ALL | E_STRICT
    ;   Production Value: E_ALL & ~E_DEPRECATED
    

    What this communicates to PHP is that we want to log all these errors. Warning, there will be a large performance hit, so you don't want this enabled on production because logging takes work and work takes time, time costs money.

  7. Restarting PHP and Apache should apply the change.

  8. Do what you did to cause the 500 Internal Server error again, and check the log:

    tail -f /var/log/apache2/error.log
    
  9. You should see the 500 error at the end, something like this:

    [Wed Dec 11 01:00:40 2013] [error] [client 192.168.11.11] PHP Fatal error:  
    Call to undefined function Foobar\\byob\\penguin\\alert() in /yourproject/
    your_src/symfony/Controller/MessedUpController.php on line 249, referer: 
    https://nuclearreactor.com/abouttoblowup
    

Required maven dependencies for Apache POI to work

this is the list of maven artifact id for all poi component. in this link http://poi.apache.org/overview.html#components

How can I convert string to double in C++?

If it is a c-string (null-terminated array of type char), you can do something like:

#include <stdlib.h>
char str[] = "3.14159";
double num = atof(str);

If it is a C++ string, just use the c_str() method:

double num = atof( cppstr.c_str() );

atof() will convert the string to a double, returning 0 on failure. The function is documented here: http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html

How to pass parameters in $ajax POST?

$.ajax(
   {
      type: 'post',
      url: 'superman',
      data: { 
        "field1": "hello",
        "field2": "hello1"
      },
      success: function (response) {
        alert("Success !!");
      },
      error: function () {
        alert("Error !!");
      }
   }
);

type: 'POST', will append **parameters to the body of the request** which is not seen in the URL while type: 'GET', appends parameters to the URL which is visible.

Most of the popular web browsers contain network panels which displays the complete request.

In network panel select XHR to see requests.

This can also be done via this.

$.post('superman',
      { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      function (response) {
        alert("Success !");
      }
    );

Inner join with count() on three tables

i tried putting distinct on both, count(distinct ord.ord_id) as num_order, count(distinct items.item_id) as num items

its working :)

    SELECT
         people.pe_name,
         COUNT(distinct orders.ord_id) AS num_orders,
         COUNT(distinct items.item_id) AS num_items
    FROM
         people
         INNER JOIN orders ON (orders.pe_id = people.pe_id)
         INNER JOIN items ON items.pe_id = people.pe_id
    GROUP BY
         people.pe_id;

Thanks for the Thread it helps :)

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

Javascript Array.sort implementation?

try this with quick sort:

function sort(arr, compareFn = (a, b) => a <= b) {

    if (!arr instanceof Array || arr.length === 0) {
        return arr;
    }

    if (typeof compareFn !== 'function') {
        throw new Error('compareFn is not a function!');
    }

    const partition = (arr, low, high) => {
        const pivot = arr[low];
        while (low < high) {
            while (low < high && compareFn(pivot, arr[high])) {
                --high;
            }
            arr[low] = arr[high];
            while (low < high && compareFn(arr[low], pivot)) {
                ++low;
            }
            arr[high] = arr[low];
        }
        arr[low] = pivot;
        return low;
    };

    const quickSort = (arr, low, high) => {
        if (low < high) {
            let pivot = partition(arr, low, high);
            quickSort(arr, low, pivot - 1);
            quickSort(arr, pivot + 1, high);
        }
        return arr;
    };

    return quickSort(arr, 0, arr.length - 1);
}

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Inspired by @aaronpenne and @Soumyaansh

f = open("file.txt", "rb")
text = f.read().decode(errors='replace')

insert a NOT NULL column to an existing table

Alter TABLE 'TARGET' add 'ShouldAddColumn' Integer Not Null default "0"

Launch Bootstrap Modal on page load

I recently needed to launch a Bootstrap 5 modal without jQuery and not with a button click (eg, on page load) using Django messages. This is how I did it:

Template/HTML

<div class="modal" id="notification">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Notification!</h5>
        <button type="button" class="btn-close"
                data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        {% for m in messages %}
          {{ m }}
        {% endfor %}
      </div>
      <div class="modal-footer justify-content-between">
        <a class="float-none btn btn-secondary" href="{% url 'some_view' %}"
           type="button">
          Link/Button A
        </a>
        <button type="button" class="btn btn-primary"
                data-bs-dismiss="modal">
          Link/Button B
        </button>
      </div>
    </div>
  </div>
</div>

JS in a file or in the template

{% block javascript %}
  {{ block.super }}
  <script>
    var test_modal = new bootstrap.Modal(
      document.getElementById('notification')
    )
    test_modal.show()
  </script>
{% endblock javascript %}

This method will work without the Django template; just use the HTML and put the JS in a file or script elements that loads after the Bootstrap JS before the end of the body element.

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I got this error when I install some VS components. Unfortunately none of these answers didn't help me. I use TFS for command development and I have no permissions to edit build definition. I solved this problem by deleting environment variables which called VS110COMNTOOLS and VS120COMNTOOLS. I think it was installed with my VS components.

Setting a log file name to include current date in Log4j

DailyRollingFileAppender is what you exactly searching for.

<appender name="roll" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="File" value="application.log" />
    <param name="DatePattern" value=".yyyy-MM-dd" />
    <layout class="org.apache.log4j.PatternLayout"> 
      <param name="ConversionPattern" 
          value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n  %-5p %m%n"/>
    </layout>
  </appender>

Git vs Team Foundation Server

For me the major difference is all the ancilliary files that TFS will add to your solution (.vssscc) to 'support' TFS - we've had recent issues with these files ending up mapped to the wrong branch, which lead to some interesting debugging...

How to find the remainder of a division in C?

You can use the % operator to find the remainder of a division, and compare the result with 0.

Example:

if (number % divisor == 0)
{
    //code for perfect divisor
}
else
{
    //the number doesn't divide perfectly by divisor
}

Match whitespace but not newlines

m/ /g just give space in / /, and it will work. Or use \S — it will replace all the special characters like tab, newlines, spaces, and so on.

How to tar certain file types in all subdirectories?

find ./someDir -name "*.php" -o -name "*.html" | tar -cf my_archive -T -

Vue.JS: How to call function after page loaded?

// vue js provides us `mounted()`. this means `onload` in javascript.

mounted () {
  // we can implement any method here like
   sampleFun () {
      // this is the sample method you can implement whatever you want
   }
}

How do I correctly clean up a Python object?

I don't think that it's possible for instance members to be removed before __del__ is called. My guess would be that the reason for your particular AttributeError is somewhere else (maybe you mistakenly remove self.file elsewhere).

However, as the others pointed out, you should avoid using __del__. The main reason for this is that instances with __del__ will not be garbage collected (they will only be freed when their refcount reaches 0). Therefore, if your instances are involved in circular references, they will live in memory for as long as the application run. (I may be mistaken about all this though, I'd have to read the gc docs again, but I'm rather sure it works like this).

"detached entity passed to persist error" with JPA/EJB code

if you use to generate the id = GenerationType.AUTO strategy in your entity.

Replaces user.setId (1) by user.setId (null), and the problem is solved.

Vue 2 - Mutating props vue-warn

You need to add computed method like this

component.vue

props: ['list'],
computed: {
    listJson: function(){
        return JSON.parse(this.list);
    }
}

Why I get 'list' object has no attribute 'items'?

You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.

If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:

result_list = [[int(v) for k,v in d.items()] for d in qs]

Which is the same as:

result_list = []
for d in qs:
    result_list.append([int(v) for k,v in d.items()])

The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:

result_list = [int(v) for d in qs for k,v in d.items()]

"Items collection must be empty before using ItemsSource."

I just ran into a VERY insidious example of this problem. My original fragment was much more complex, which made it difficult to see the error.

   <ItemsControl           
      Foreground="Black"  Background="White" Grid.IsSharedSizingScope="True"
      x:Name="MyGrid" ItemsSource="{Binding}">
      >
      <ItemsControl.ItemsPanel>
           <!-- All is fine here -->
      </ItemsControl.ItemsPanel>
      <ItemsControl.ItemTemplate>
           <!-- All is fine here -->
      </ItemsControl.ItemTemplate>
      <!-- Have you caught the error yet? -->
    </ItemsControl>

The bug? The extra > after the initial opening <ItemsControl> tag! The < got applied to the built-in Items collection. When the DataContext was later set, instant crashola. So look out for more than just errors surround your ItemsControl specific data children when debugging this problem.

ERROR 1049 (42000): Unknown database 'mydatabasename'

If dump file contains:

CREATE DATABASE mydatabasename;
USE mydatabasename; 

You may just use in CLI:

mysql -uroot –pmypassword < mydatabase.sql

It works.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Most efficient way to concatenate strings in JavaScript?

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.

(Thanks @zAlbee for correction)

Printing leading 0's in C

printf("%05d", zipCode);

The 0 indicates what you are padding with and the 5 shows the width of the integer number.

Example 1: If you use "%02d" (useful for dates) this would only pad zeros for numbers in the ones column. E.g., 06 instead of 6.

Example 2: "%03d" would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to 007 and number 17 padded to 017.

Dynamically add item to jQuery Select2 control that uses AJAX

In case of Select2 Version 4+

it has changed syntax and you need to write like this:

// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});

// clear and add new option
$("#select_with_data").html('').select2({data: [
 {id: '', text: ''},
 {id: '1', text: 'Facebook'},
 {id: '2', text: 'Youtube'},
 {id: '3', text: 'Instagram'},
 {id: '4', text: 'Pinterest'}]});



//  append option
$("#select_with_data").append('<option value="5">Twitter</option>');
$("#select_with_data").val('5');
$("#select_with_data").trigger('change');

Ping all addresses in network, windows

@ECHO OFF

IF "%SUBNET%"=="" SET SUBNET=10

:ARGUMENTS
ECHO SUBNET=%SUBNET%
ECHO ARGUMENT %1 
IF "%1"=="SUM" GOTO SUM
IF "%1"=="SLOW" GOTO SLOW
IF "%1"=="ARP" GOTO ARP
IF "%1"=="FAST" GOTO FAST

REM PRINT ARP TABLE BY DEFAULT
:DEFAULT
ARP -a
GOTO END

REM METHOD 1 ADDRESS AT A TIME
:SLOW
ECHO START SCAN
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO ping -a -n 2 192.168.%SUBNET%.%%i | FIND /i "TTL="  >> ipaddresses.txt
GOTO END

REM METHOD 2 MULTITASKING ALL ADDRESS AT SAME TIME
:FAST
ECHO START FAST SCANNING 192.168.%SUBNET%.X
set /a n=0
:FASTLOOP
set /a n+=1
ECHO 192.168.%SUBNET%.%n%
START CMD.exe /c call ipaddress.bat 192.168.%SUBNET%.%n% 
IF %n% lss 254 GOTO FASTLOOP
GOTO END

:SUM
ECHO START SUM
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO TYPE ip192.168.%SUBNET%.%%i.txt | FIND /i "TTL=" >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO DEL ip192.168.%SUBNET%.%%i.txt
type ipaddresses.txt
GOTO END

:ARP
ARP -a >> ipaddresses.txt
type ipaddresses.txt
GOTO END


:END
ECHO DONE WITH IP SCANNING
ECHO OPTION "%0 SLOW" FOR SCANNING 1 AT A TIME
ECHO OPTION "%0 SUM" FOR COMBINE ALL TO FILE
ECHO OPTION "%0 ARP" FOR ADD ARP - IP LIST
ECHO PARAMETER "SET SUBNET=X" FOR SUBNET
ECHO.

Locking pattern for proper use of .NET MemoryCache

To avoid the global lock, you can use SingletonCache to implement one lock per key, without exploding memory usage (the lock objects are removed when no longer referenced, and acquire/release is thread safe guaranteeing that only 1 instance is ever in use via compare and swap).

Using it looks like this:

SingletonCache<string, object> keyLocks = new SingletonCache<string, object>();

const string CacheKey = "CacheKey";
static string GetCachedData()
{
    string expensiveString =null;
    if (MemoryCache.Default.Contains(CacheKey))
    {
        return MemoryCache.Default[CacheKey] as string;
    }

    // double checked lock
    using (var lifetime = keyLocks.Acquire(url))
    {
        lock (lifetime.Value)
        {
           if (MemoryCache.Default.Contains(CacheKey))
           {
              return MemoryCache.Default[CacheKey] as string;
           }

           cacheItemPolicy cip = new CacheItemPolicy()
           {
              AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
           };
           expensiveString = SomeHeavyAndExpensiveCalculation();
           MemoryCache.Default.Set(CacheKey, expensiveString, cip);
           return expensiveString;
        }
    }      
}

Code is here on GitHub: https://github.com/bitfaster/BitFaster.Caching

Install-Package BitFaster.Caching

There is also an LRU implementation that is lighter weight than MemoryCache, and has several advantages - faster concurrent reads and writes, bounded size, no background thread, internal perf counters etc. (disclaimer, I wrote it).

Clean out Eclipse workspace metadata

In my case eclipse is not showing parent class function on $this, so I perform below mention points and it starts works:-

I go to my /var/www/ folder and check for .metadata folder (Here check the .log file and it shows) Resource is out of sync with the file system: 1. Go to Eclipse --> Project --> Clean 2. Windows -- preferences --> General --> Workspace --> And set it to "Refresh Automatically"

After that boom - things gets start working :)

If you want to load variables from other files too then ado this :- Eclipse-->Windows-->Preferences-->Php-->Editor-->Content Assist --> and check "show variable from other files"

Then it will show element , variables and other functions also.

How to force NSLocalizedString to use a specific language

I usually do this in this way, but you MUST have all localization files in your project.

@implementation Language

static NSBundle *bundle = nil;

+(void)initialize 
{
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString *current = [[languages objectAtIndex:0] retain];
    [self setLanguage:current];
}

/*
  example calls:
    [Language setLanguage:@"it"];
    [Language setLanguage:@"de"];
*/
+(void)setLanguage:(NSString *)l
{
    NSLog(@"preferredLang: %@", l);
    NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
    bundle = [[NSBundle bundleWithPath:path] retain];
}

+(NSString *)get:(NSString *)key alter:(NSString *)alternate 
{
    return [bundle localizedStringForKey:key value:alternate table:nil];
}

@end

Hidden TextArea

An <input type=hidden> element is not a hidden input box. It is simply a form field that has a value set via markup or via scripting, not via user input. You can use it for multi-line data too, e.g.

<input type=hidden name=stuff value=
"Hello
world, how
are you?">

If the value contains the Ascii quotation mark ("), then, as for any HTML attribute, you need to use Ascii apostrophes (') as attribute value delimites or escape the quote as &quot;, e.g.

<input type=hidden name=stuff value="A &quot;funny&quot; example">

How to obtain the last index of a list?

all above answers is correct but however

a = [];
len(list1) - 1 # where 0 - 1 = -1

to be more precisely

a = [];
index = len(a) - 1 if a else None;

if index == None : raise Exception("Empty Array")

since arrays is starting with 0

how to use json file in html code

use jQuery's $.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

Difference between static class and singleton pattern?

From a client perspective, static behavior is known to the client but Singleton behavior can be completed hidden from a client. Client may never know that there only one single instance he's playing around with again and again.

What is the opposite of :hover (on mouse leave)?

Just add a transition and the name of the animation on the class inicial, in your case, ul li a, just add a "transition" property and that is all you need

_x000D_
_x000D_
ul li {_x000D_
    display: inline;_x000D_
    margin-left: 20px;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
    color: #999;_x000D_
    transition: 1s;_x000D_
    -webkit-animation: item-hover-off 1s;_x000D_
    -moz-animation: item-hover-off 1s;_x000D_
    animation: item-hover-off 1s;_x000D_
}_x000D_
_x000D_
ul li a:hover {_x000D_
    color: black;_x000D_
    cursor: pointer;_x000D_
    -webkit-animation: item-hover 1s;_x000D_
    -moz-animation: item-hover 1s;_x000D_
    animation: item-hover 1s;_x000D_
}_x000D_
_x000D_
@keyframes item-hover {_x000D_
    from {_x000D_
      color: #999;_x000D_
      }_x000D_
    to {_x000D_
      color: black;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-moz-keyframes item-hover {_x000D_
    from {_x000D_
        color: #999;_x000D_
      }_x000D_
    to {_x000D_
        color: black;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-webkit-keyframes item-hover {_x000D_
    from {_x000D_
        color: #999;_x000D_
      }_x000D_
    to {_x000D_
        color: black;_x000D_
      }_x000D_
}_x000D_
_x000D_
@keyframes item-hover-off {_x000D_
    from {_x000D_
      color: black;_x000D_
      }_x000D_
    to {_x000D_
      color: #999;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-moz-keyframes item-hover-off {_x000D_
    from {_x000D_
        color: black;_x000D_
      }_x000D_
    to {_x000D_
        color: #999;_x000D_
      }_x000D_
}_x000D_
    _x000D_
@-webkit-keyframes item-hover-off {_x000D_
    from {_x000D_
        color: black;_x000D_
      }_x000D_
    to {_x000D_
        color: #999;_x000D_
      }_x000D_
}
_x000D_
<ul>_x000D_
    <li><a>Home</a></li>_x000D_
    <li><a>About</a></li>_x000D_
    <li><a>Contacts</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

What are the main differences between JWT and OAuth authentication?

find the main differences between JWT & OAuth

  1. OAuth 2.0 defines a protocol & JWT defines a token format.

  2. OAuth can use either JWT as a token format or access token which is a bearer token.

  3. OpenID connect mostly use JWT as a token format.

How do I apply a perspective transform to a UIView?

As Ben said, you'll need to work with the UIView's layer, using a CATransform3D to perform the layer's rotation. The trick to get perspective working, as described here, is to directly access one of the matrix cells of the CATransform3D (m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:

Objective-C

UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;

Swift 5.0

if let myView = self.subviews.first {
    let layer = myView.layer
    var rotationAndPerspectiveTransform = CATransform3DIdentity
    rotationAndPerspectiveTransform.m34 = 1.0 / -500
    rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
    layer.transform = rotationAndPerspectiveTransform
}

which rebuilds the layer transform from scratch for each rotation.

A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.

The sublayerTransform you refer to in your response is a transform that is applied to the sublayers of your UIView's CALayer. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers contained within the one layer that I'm rotating.

print variable and a string in python

If you are using python 3.6 and newer then you can use f-strings to do the task like this.

print(f"I have {card.price}")

just include f in front of your string and add the variable inside curly braces { }.

Refer to a blog The new f-strings in Python 3.6: written by Christoph Zwerschke which includes execution times of the various method.

.htaccess redirect www to non-www with SSL/HTTPS

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

This worked for me after much trial and error. Part one is from the user above and will capture www.xxx.yyy and send to https://xxx.yyy

Part 2 looks at entered URL and checks if HTTPS, if not, it sends to HTTPS

Done in this order, it follows logic and no error occurs.

HERE is my FULL version in side htaccess with WordPress:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]


# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Angular ForEach in Angular4/Typescript?

arrayData.forEach((key : any, val: any) => {
                        key['index'] = val + 1;

                        arrayData2.forEach((keys : any, vals :any) => {
                            if (key.group_id == keys.id) {
                                key.group_name = keys.group_name;
                            }
                        })
                    })

How can I start PostgreSQL server on Mac OS X?

There is some edge case that maybe will be helpful for someone:

There is an option that you will have postgres.pid filled with some PID. If you restart your machine, and before PostgreSQL will be back again, some other process will take that PID.

If that will happen, both the pg_ctl status and brew service are asked about the PostgreSQL status, will tell you that it is up.

Just do ps aux | grep <yourPID> and check if it is really PostgreSQL.

How to redirect stdout to both file and console with scripting?

Use logging module to debug and follow your app

Here is how I managed to log to file and to console / stdout

import logging
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    filename='logs_file',
                    filemode='w')
# Until here logs only to file: 'logs_file'

# define a new Handler to log to console as well
console = logging.StreamHandler()
# optional, set the logging level
console.setLevel(logging.INFO)
# set a format which is the same for console use
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to both ti file and console
logging.info('Jackdaws love my big sphinx of quartz.')
logging.info('Hello world')

read it from source: https://docs.python.org/2/howto/logging-cookbook.html

Tricks to manage the available memory in an R session

I make aggressive use of the subset parameter with selection of only the required variables when passing dataframes to the data= argument of regression functions. It does result in some errors if I forget to add variables to both the formula and the select= vector, but it still saves a lot of time due to decreased copying of objects and reduces the memory footprint significantly. Say I have 4 million records with 110 variables (and I do.) Example:

# library(rms); library(Hmisc) for the cph,and rcs functions
Mayo.PrCr.rbc.mdl <- 
cph(formula = Surv(surv.yr, death) ~ age + Sex + nsmkr + rcs(Mayo, 4) + 
                                     rcs(PrCr.rat, 3) +  rbc.cat * Sex, 
     data = subset(set1HLI,  gdlab2 & HIVfinal == "Negative", 
                           select = c("surv.yr", "death", "PrCr.rat", "Mayo", 
                                      "age", "Sex", "nsmkr", "rbc.cat")
   )            )

By way of setting context and the strategy: the gdlab2 variable is a logical vector that was constructed for subjects in a dataset that had all normal or almost normal values for a bunch of laboratory tests and HIVfinal was a character vector that summarized preliminary and confirmatory testing for HIV.

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

Problem 1 : Different applications use different scales for HSV. For example gimp uses H = 0-360, S = 0-100 and V = 0-100. But OpenCV uses H: 0-179, S: 0-255, V: 0-255. Here i got a hue value of 22 in gimp. So I took half of it, 11, and defined range for that. ie (5,50,50) - (15,255,255).

Problem 2: And also, OpenCV uses BGR format, not RGB. So change your code which converts RGB to HSV as follows:

cv.CvtColor(frame, frameHSV, cv.CV_BGR2HSV)

Now run it. I got an output as follows:

enter image description here

Hope that is what you wanted. There are some false detections, but they are small, so you can choose biggest contour which is your lid.

EDIT:

As Karl Philip told in his comment, it would be good to add new code. But there is change of only a single line. So, I would like to add the same code implemented in new cv2 module, so users can compare the easiness and flexibility of new cv2 module.

import cv2
import numpy as np

img = cv2.imread('sof.jpg')

ORANGE_MIN = np.array([5, 50, 50],np.uint8)
ORANGE_MAX = np.array([15, 255, 255],np.uint8)

hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

frame_threshed = cv2.inRange(hsv_img, ORANGE_MIN, ORANGE_MAX)
cv2.imwrite('output2.jpg', frame_threshed)

It gives the same result as above. But code is much more simpler.

How to linebreak an svg text within javascript?

use HTML instead of javascript

_x000D_
_x000D_
<html>_x000D_
  <head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
  <body>_x000D_
    <h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
    <svg_x000D_
      xmlns="http://www.w3.org/2000/svg"_x000D_
      viewBox="0 0 300 300"_x000D_
      x="0" y="0" height="300" width="300"_x000D_
    >_x000D_
_x000D_
      <circle_x000D_
        r="142" cx="150" cy="150"_x000D_
        fill="none" stroke="#000000" stroke-width="2"_x000D_
      />_x000D_
_x000D_
      <foreignObject_x000D_
        x="50" y="50" width="200" height="200"_x000D_
      >_x000D_
        <div_x000D_
          xmlns="http://www.w3.org/1999/xhtml"_x000D_
          style="_x000D_
            width: 196px; height: 196px;_x000D_
            border: solid 2px #000000;_x000D_
            font-size: 32px;_x000D_
            overflow: auto; /* scroll */_x000D_
          "_x000D_
        >_x000D_
          <p>this is html in svg 1</p>_x000D_
          <p>this is html in svg 2</p>_x000D_
          <p>this is html in svg 3</p>_x000D_
          <p>this is html in svg 4</p>_x000D_
        </div>_x000D_
      </foreignObject>_x000D_
_x000D_
    </svg>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

What is difference between Errors and Exceptions?

Error is something that most of the time you cannot handle it.

Exception was meant to give you an opportunity to do something with it. like try something else or write to the log.

try{
  //connect to database 1
}
catch(DatabaseConnctionException err){
  //connect to database 2
  //write the err to log
}

How to test if a double is zero?

Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.

If this has anything to do with money, do not use float or double, instead use BigDecimal.

Best C/C++ Network Library

Aggregated List of Libraries

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

How to resolve conflicts in EGit

This guide was helpful for me http://wiki.eclipse.org/EGit/User_Guide#Resolving_a_merge_conflict.

UPDATED Just a note on that about my procedure, this is how I proceed:

  1. Commit My change
  2. Fetch (Syncrhonize workspace)
  3. Pull
  4. Manage Conflicts with Merge Tool (Team->Merge Tool) and Save
  5. Add each file to stage (Team -> Add to index)
  6. Now the Commit Message in the Stage window is prefilled with "Merged XXX". You can leave as it is or change the commit message
  7. Commit and Push

It is dangerous in some cases but it is very usefull to avoid to use external tool like Git Extension or Source Tree

Ansible - Save registered variable to file

More readable way of achieving this (not a fan of single line ansible tasks)

- local_action: 
    module: copy 
    content: "{{ foo_result }}"
    dest: /path/to/destination/file

Can a main() method of class be invoked from another class in java

Sure. Here's a completely silly program that demonstrates calling main recursively.

public class main
{
    public static void main(String[] args)
    {
        for (int i = 0; i < args.length; ++i)
        {
            if (args[i] != "")
            {
                args[i] = "";
                System.out.println((args.length - i) + " left");
                main(args);
            }
        }

    }
}

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

Retrieve specific commit from a remote Git repository

I think 'git ls-remote' ( http://git-scm.com/docs/git-ls-remote ) should do what you want. Without force fetch or pull.

How do I redirect in expressjs while passing some context?

Here s what I suggest without using any other dependency , just node and express, use app.locals, here s an example :

    app.get("/", function(req, res) {
        var context = req.app.locals.specialContext;
        req.app.locals.specialContext = null;
        res.render("home.jade", context); 
        // or if you are using ejs
        res.render("home", {context: context}); 
    });

    function middleware(req, res, next) {
        req.app.locals.specialContext = * your context goes here *
        res.redirect("/");
    }

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

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

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

Get 2 Digit Number For The Month

Simply can be used:

SELECT RIGHT('0' + CAST(MONTH(@Date) AS NVARCHAR(2)), 2)

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

Setup Bitbucket Repository (Command Line with Mac)

Create New APPLICATION from starting with local reposity :

  1. Terminal -> cd ~/Documents (Paste your APPLICATION base directory path)
  2. Terminal -> mkdir (create directory with )
  3. Terminal -> cd (change directory with directory)
  4. BitBucket A/C -> create repository on bitBucket account
  5. Xcode -> create new xcode project with same name
  6. Terminal -> git init (initilize empty repo)
  7. Terminal -> git remote add origin (Ex. https://[email protected]/app/app.git)
  8. Terminal -> git add .
  9. Terminal -> git status
    1. Terminal -> git commit -m "IntialCommet"
    2. Terminal -> git push origin master

Create APPLICATION clone repository :

  1. Terminal -> mkdir (create directory with )
  2. Terminal -> cd (change directory with directory)
  3. Terminal -> git clone (Ex. https://[email protected]/app/app.git)
  4. Terminal -> cd
  5. Terminal -> git status (Show edit/updated file status)
  6. Terminal -> git pull origin master
  7. Terminal -> git add .
  8. Terminal -> git push origin master

How to specify function types for void (not Void) methods in Java8?

I feel you should be using the Consumer interface instead of Function<T, R>.

A Consumer is basically a functional interface designed to accept a value and return nothing (i.e void)

In your case, you can create a consumer elsewhere in your code like this:

Consumer<Integer> myFunction = x -> {
    System.out.println("processing value: " + x);    
    .... do some more things with "x" which returns nothing...
}

Then you can replace your myForEach code with below snippet:

public static void myForEach(List<Integer> list, Consumer<Integer> myFunction) 
{
  list.forEach(x->myFunction.accept(x));
}

You treat myFunction as a first-class object.

Yarn install command error No such file or directory: 'install'

Tried above steps, didn't work on Ubuntu 20. For Ubuntu 20, remove the cmdtest and yarn like suggested above. Install yarn with below commands:

curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt install yarn

Heap space out of memory

There is no way to dynamically increase the heap programatically since the heap is allocated when the Java Virtual Machine is started.

However, you can use this command

java -Xmx1024M YourClass

to set the memory to 1024

or, you can set a min max

java -Xms256m -Xmx1024m YourClassNameHere

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

Swift 5 : For evenly distributed spaces between cells with dynamic cell width to make the best of container space you may use the code snippet below by providing a minimumCellWidth value.

private func collectionViewLayout() -> UICollectionViewLayout {
    
    let layout = UICollectionViewFlowLayout()
    layout.sectionHeadersPinToVisibleBounds = true
    // Important: if direction is horizontal use minimumItemSpacing instead. 
    layout.scrollDirection = .vertical
    
    let itemHeight: CGFloat = 240
    let minCellWidth :CGFloat = 130.0
    let minItemSpacing: CGFloat = 10
    let containerWidth: CGFloat = self.view.bounds.width
    let maxCellCountPerRow: CGFloat =  floor((containerWidth - minItemSpacing) / (minCellWidth+minItemSpacing ))
    
    let itemWidth: CGFloat = floor( ((containerWidth - (2 * minItemSpacing) - (maxCellCountPerRow-1) * minItemSpacing) / maxCellCountPerRow  ) )
    // Calculate the remaining space after substracting calculating cellWidth (Divide by 2 because of left and right insets)
    let inset = max(minItemSpacing, floor( (containerWidth - (maxCellCountPerRow*itemWidth) - (maxCellCountPerRow-1)*minItemSpacing) / 2 ) )

    
    layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
    layout.minimumInteritemSpacing = min(minItemSpacing,inset)
    layout.minimumLineSpacing = minItemSpacing
    layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom: minItemSpacing, right: inset)

    
    return layout
}

How to check if ZooKeeper is running or up from command prompt?

I did some test:

When it's running:

$ /usr/lib/zookeeper/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/lib/zookeeper/bin/../conf/zoo.cfg
Mode: follower

When it's stopped:

$ zkServer status                                                                                                                                
JMX enabled by default
Using config: /usr/local/etc/zookeeper/zoo.cfg
Error contacting service. It is probably not running.

I'm not running on the same machine, but you get the idea.

Interface or an Abstract Class: which one to use?

To add to some of the already excellent answers:

  • Abstract classes let you provide some degree of implementation, interfaces are pure templates. An interface can only define functionality, it can never implement it.

  • Any class that implements the interface commits to implementing all the methods it defines or it must be declared abstract.

  • Interfaces can help to manage the fact that, like Java, PHP does not support multiple inheritance. A PHP class can only extend a single parent. However, you can make a class promise to implement as many interfaces as you want.

  • type: for each interface it implements, the class takes on the corresponding type. Because any class can implement an interface (or more interfaces), interfaces effectively join types that are otherwise unrelated.

  • a class can both extend a superclass and implement any number of interfaces:

    class SubClass extends ParentClass implements Interface1, Interface2 {
        // ...
    }
    

Please explain when I should use an interface and when I should use abstract class?

Use an interface when you need to provide only a template with no implementation what so ever, and you want to make sure any class that implements that interface will have the same methods as any other class that implements it (at least).

Use an abstract class when you want to create a foundation for other objects (a partially built class). The class that extends your abstract class will use some properties or methods defined/implemented:

<?php
// interface
class X implements Y { } // this is saying that "X" agrees to speak language "Y" with your code.

// abstract class
class X extends Y { } // this is saying that "X" is going to complete the partial class "Y".
?>

How I can change my abstract class in to an interface?

Here is a simplified case/example. Take out any implementation details out. For example, change your abstract class from:

abstract class ClassToBuildUpon {
    public function doSomething() {
          echo 'Did something.';
    }
}

to:

interface ClassToBuildUpon {
    public function doSomething();
}

Convert 4 bytes to int

The following code reads 4 bytes from array (a byte[]) at position index and returns a int. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.

This code used the least amount of CPU time but allocates a ByteBuffer until Java 10's JIT gets rid of the allocation.

int result;

result = ByteBuffer.
   wrap(array).
   getInt(index);

This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.

int result;
short data0, data1, data2, data3;

data0  = (short) (array[index++] & 0x00FF);
data1  = (short) (array[index++] & 0x00FF);
data2  = (short) (array[index++] & 0x00FF);
data3  = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;

Getting reference to child component in parent component

You may actually go with ViewChild API...

parent.ts

<button (click)="clicked()">click</button>

export class App {
  @ViewChild(Child) vc:Child;
  constructor() {
    this.name = 'Angular2'
  }

  func(e) {
    console.log(e)

  }
  clicked(){
   this.vc.getName();
  }
}

child.ts

export class Child implements OnInit{

  onInitialized = new EventEmitter<Child>();
  ...  
  ...
  getName()
  {
     console.log('called by vc')
     console.log(this.name);
  }
}

Automatically scroll down chat div

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bootstrap 3: Using img-circle, how to get circle from non-square image?

You Need to take same height and width

and simply use the border-radius:360px;

How to use "like" and "not like" in SQL MSAccess for the same field?

If you're doing it in VBA (and not in a query) then: where field like "AA" and field not like "BB" then would not work.

You'd have to use: where field like "AA" and field like "BB" = false then

What is python's site-packages directory?

site-packages is just the location where Python installs its modules.

No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).

Programmatically you can find it this way:

import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages

'/Users/foo/.envs/env1/lib/python2.7/site-packages'

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I've seen it suggested docker may be at its maximum of created networks. The command docker network prune can be used to remove all networks not used by at least one container.

My issue ended up being, as Robert commented about: an issue with openvpn service openvpn stop 'solved' the problem.

Getting realtime output using subprocess

Real Time Output Issue resolved: I encountered a similar issue in Python, while capturing the real time output from C program. I added fflush(stdout); in my C code. It worked for me. Here is the code.

C program:

#include <stdio.h>
void main()
{
    int count = 1;
    while (1)
    {
        printf(" Count  %d\n", count++);
        fflush(stdout);
        sleep(1);
    }
}

Python program:

#!/usr/bin/python

import os, sys
import subprocess


procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

while procExe.poll() is None:
    line = procExe.stdout.readline()
    print("Print:" + line)

Output:

Print: Count  1
Print: Count  2
Print: Count  3

Calling Non-Static Method In Static Method In Java

The easiest way to use a non-static method/field within a a static method or vice versa is...

(To work this there must be at least one instance of this class)

This type of situation is very common in android app development eg:- An Activity has at-least one instance.

public class ParentClass{

private static ParentClass mParentInstance = null;

ParentClass(){
  mParentInstance = ParentClass.this;           
}


void instanceMethod1(){
}


static void staticMethod1(){        
    mParentInstance.instanceMethod1();
}


public static class InnerClass{
      void  innerClassMethod1(){
          mParentInstance.staticMethod1();
          mParentInstance.instanceMethod1();
      }
   }
}

Note:- This cannot be used as a builder method like this one.....

String.valueOf(100);

Stopping a windows service when the stop option is grayed out

sc queryex <service name>
taskkill /F /PID <Service PID>

eg

enter image description here

eg

Using Java with Nvidia GPUs (CUDA)

I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

With my Android 5 tablet, every time I attempt to use adb, to install a signed release apk, I get the [INSTALL_FAILED_ALREADY_EXISTS] error.

I have to uninstall the debug package first. But, I cannot uninstall using the device's Application Manager!

If do uninstall the debug version with the Application Manager, then I have to re-run the debug build variant from Android Studio, then uninstall it using adb uninstall com.example.mypackagename

Finally, I can use adb install myApp.apk to install the signed release apk.

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */

Using C# regular expressions to remove HTML tags

@JasonTrue is correct, that stripping HTML tags should not be done via regular expressions.

It's quite simple to strip HTML tags using HtmlAgilityPack:

public string StripTags(string input) {
    var doc = new HtmlDocument();
    doc.LoadHtml(input ?? "");
    return doc.DocumentNode.InnerText;
}

How to show alert message in mvc 4 controller?

<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">

ERROR Android emulator gets killed

This issue happens when you have two Android SDK installations on your machine and the environment variable "ANDROID_HOME" points to the wrong location.

To fix it go to Android Studio settings, find the proper Android SDK location, update the environment variable and restart Android Studio / your PC.

enter image description here

text-align: right; not working for <label>

Label is an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your div element is a block element so its width is by default 100%.

You will have to place the text-align: right; on the div element in your case, or applying display: block; to your label

Another option is to set a width for each label and then use text-align. The display: block method will not be necessary using this.

How to check for an empty struct?

Using reflect.deepEqual also works, especially when you have map inside the struct

package main

import "fmt"
import "time"
import "reflect"

type Session struct {
    playerId string
    beehive string
    timestamp time.Time
}

func (s Session) IsEmpty() bool {
  return reflect.DeepEqual(s,Session{})
}

func main() {
  x := Session{}
  if x.IsEmpty() {
    fmt.Print("is empty")
  } 
}

How do I search an SQL Server database for a string?

I was given access to a database, but not the table where my query was being stored in.

Inspired by @marc_s answer, I had a look at HeidiSQL which is a Windows program that can deal with MySQL, SQL Server, and PostgreSQL.

I found that it can also search a database for a string.

Click Search, then Find text on Server

Search tool open. Make sure the DB is selected

It will search each table and give you how many times it found the string per table!

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

Random row selection in Pandas dataframe

Something like this?

import random

def some(x, n):
    return x.ix[random.sample(x.index, n)]

Note: As of Pandas v0.20.0, ix has been deprecated in favour of loc for label based indexing.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

Using $ docker inspect Incase the Image has no /bin/bash in the output, you can use command below: it worked for me perfectly

$ docker exec -it <container id> sh

How to read attribute value from XmlNode in C#?

Try this:

string employeeName = chldNode.Attributes["Name"].Value;

Edit: As pointed out in the comments, this will throw an exception if the attribute doesn't exist. The safe way is:

var attribute = node.Attributes["Name"];
if (attribute != null){
    string employeeName = attribute.Value;
    // Process the value here
}

Font awesome is not showing icon

Be aware that the new version (5) of font awesome uses "fas" or "fab" instead of "fa" prefix.

Quoted from their website:

The fa prefix has been deprecated in version 5. The new default is the fas solid style and the fab style for brands.

This is why my fonts were showing blank squares. Now fixed.

Example code:

<a class="nav-link" href="//www.facebook.com/xxx" target="_blank"><i class="fab fa-facebook-f"></i></a>

See: https://fontawesome.com/icons/facebook-f?style=brands

Resizing SVG in html?

Use the following code:

<g transform="scale(0.1)">
...
</g>

How do you wait for input on the same Console.WriteLine() line?

As Matt has said, use Console.Write. I would also recommend explicitly flushing the output, however - I believe WriteLine does this automatically, but I'd seen oddities when just using Console.Write and then waiting. So Matt's code becomes:

Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();

Setting the focus to a text field

I have toyed with this for forever, and finally found something that seems to always work!

textField = new JTextField() {

    public void addNotify() {
        super.addNotify();
        requestFocus();
    }
};

ResultSet exception - before start of result set

You need to move the pointer to the first row, before asking for data:

result.beforeFirst();
result.next();
String foundType = result.getString(1);

Why do I always get the same sequence of random numbers with rand()?

rand() returns pseudo-random numbers. It generates numbers based on a given algorithm. The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation. This is handy when you need to verify the behavior and consistency of your program.

You can set the "seed" of the random generator with the srand function(only call srand once in a program) One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:

srand(time(NULL)); or srand(getpid()); at the start of the program.

Generating real randomness is very very hard for a computer, but for practical non-crypto related work, an algorithm that tries to evenly distribute the generated sequences works fine.

How to use count and group by at the same select statement

With Oracle you could use analytic functions:

select town, count(town), sum(count(town)) over () total_count from user
group by town

Your other options is to use a subquery:

select town, count(town), (select count(town) from user) as total_count from user
group by town

How to make Twitter Bootstrap tooltips have multiple lines?

If you are using Angular UI Bootstrap, you can use tooltip with html syntax: tooltip-html-unsafe

e.g. update to angular 1.2.10 & angular-ui-bootstrap 0.11: http://jsfiddle.net/aX2vR/1/

old one: http://jsfiddle.net/8LMwz/1/

graphing an equation with matplotlib

To plot an equation that is not solved for a specific variable (like circle or hyperbola):

import numpy as np  
import matplotlib.pyplot as plt  
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100) 
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1  #  'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()

More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf

C non-blocking keyboard input

The curses library can be used for this purpose. Of course, select() and signal handlers can be used too to a certain extent.

How to make an inline-block element fill the remainder of the line?

See: http://jsfiddle.net/qx32C/36/

_x000D_
_x000D_
.lineContainer {_x000D_
    overflow: hidden; /* clear the float */_x000D_
    border: 1px solid #000_x000D_
}_x000D_
.lineContainer div {_x000D_
    height: 20px_x000D_
} _x000D_
.left {_x000D_
    width: 100px;_x000D_
    float: left;_x000D_
    border-right: 1px solid #000_x000D_
}_x000D_
.right {_x000D_
    overflow: hidden;_x000D_
    background: #ccc_x000D_
}
_x000D_
<div class="lineContainer">_x000D_
    <div class="left">left</div>_x000D_
    <div class="right">right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Why did I replace margin-left: 100px with overflow: hidden on .right?

EDIT: Here are two mirrors for the above (dead) link:

How to concatenate strings in django templates?

You can't do variable manipulation in django templates. You have two options, either write your own template tag or do this in view,

Ruby value of a hash key?

This question seems to be ambiguous.

I'll try with my interpretation of the request.

def do_something(data)
   puts "Found! #{data}"
end

a = { 'x' => 'test', 'y' => 'foo', 'z' => 'bar' }
a.each { |key,value| do_something(value) if key == 'x' }

This will loop over all the key,value pairs and do something only if the key is 'x'.

Custom Authentication in ASP.Net-Core

@Manish Jain, I suggest to implement the method with boolean return:

public class UserManager
{

    // Additional code here...            

    public async Task<bool> SignIn(HttpContext httpContext, UserDbModel user)
    {
        // Additional code here...            

        // Here the real authentication against a DB or Web Services or whatever 
        if (user.Email != null)
            return false;                    

        ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

        // This is for give the authentication cookie to the user when authentication condition was met
        await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        return true;
    }
}

How do I make text bold in HTML?

You're nearly there!

For a bold text, you should have this: <b> bold text</b> or <strong>bold text</strong> They have the same result.

Working example - JSfiddle

presenting ViewController with NavigationViewController swift

The accepted answer is great. This is not answer, but just an illustration of the issue.

I present a viewController like this:

inside vc1:

func showVC2() {
    if let navController = self.navigationController{
        navController.present(vc2, animated: true)
    }
}

inside vc2:

func returnFromVC2() {
    if let navController = self.navigationController {
        navController.popViewController(animated: true)
    }else{
        print("navigationController is nil") <-- I was reaching here!
    }
}

As 'stefandouganhyde' has said: "it is not contained by your UINavigationController or any other"

new solution:

func returnFromVC2() {
    dismiss(animated: true, completion: nil)
}

How do I copy a version of a single file from one git branch to another?

I would use git restore (available since git 2.23)

git restore --source otherbranch path/to/myfile.txt


Why it is better than other options?

git checkout otherbranch -- path/to/myfile.txt - It copy file to working directory but also to staging area (similar effect as if you would copy this file manually and executed git add on it). git restore doesn't touch staging area (unless told it to by --staged option).

git show otherbranch:path/to/myfile.txt > path/to/myfile.txt uses standard shell redirection. If you use Powershell then there might be problem with text enconding or you could get broken file if it's binary. With git restore changing files is done all by git executable.

Another advantage is that you can restore whole folder with:

git restore --source otherbranch path/to

or with git restore --overlay --source otherbranch path/to if you want to avoid deleting files. For example if there is less files on otherbranch than in current working directory (and these files are tracked) without --overlay option git restore will delete them. But this is good default bahaviour, you most likely want the state of directory to be "the same like in otherbranch", not "the same like in otherbranch but with additional files from my current branch"

How to pip install a package with min and max version range?

You can do:

$ pip install "package>=0.2,<0.3"

And pip will look for the best match, assuming the version is at least 0.2, and less than 0.3.

This also applies to pip requirements files. See the full details on version specifiers in PEP 440.

Undefined reference to static class member

Regarding the second question: push_ref takes reference as a parameter, and you cannot have a reference to static const memeber of a class/struct. Once you call static_cast, a temporary variable is created. And a reference to this object can be passed, everything works just fine.

Or at least my colleague who resolved this said so.

Radio Buttons "Checked" Attribute Not Working

Just copied your code into: http://jsfiddle.net/fY4F9/

No is checked by default. Do you have any javascript running that would effect the radio box?

What are the correct version numbers for C#?

I've summarised most of the versions in this table. The only ones missing should be ASP.NET Core versions. I've also added different versions of ASP.NET MVC.

Note that ASP.NET 5 has been rebranded as ASP.NET Core 1.0 and ASP.NET MVC 6 has been rebranded as ASP.NET Core MVC 1.0.0. I believe this change occurred sometime around Jan 2016.

I have included the release date of ASP.NET 5 RC1 in the table, but I've yet to include ASP.NET core 1.0 and other core versions, because I couldn't find the exact release dates. You can read more about the release dates regarding ASP.NET Core here: When is ASP.NET Core 1.0 (ASP.NET 5 / vNext) scheduled for release?

Version

how to select first N rows from a table in T-SQL?

SELECT TOP 10 *
FROM Users

Note that if you don't specify an ORDER BY clause then any 10 rows could be returned, because "first 10 rows" doesn't really mean anything until you tell the database what ordering to use.

Is there an easy way to add a border to the top and bottom of an Android View?

Just to add my solution to the list..

I wanted a semi transparent bottom border that extends past the original shape (So the semi-transparent border was outside the parent rectangle).

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
  <item>
    <shape android:shape="rectangle" >      
      <solid android:color="#33000000" /> <!-- Border colour -->
    </shape>
  </item>
  <item  android:bottom="2dp" >
    <shape android:shape="rectangle" >     
      <solid android:color="#164586" />
    </shape>
  </item>
</layer-list>

Which gives me;

enter image description here

jQuery: Uncheck other checkbox on one checked

I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View, like a foreach loop):

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

<li id="checkboxlist" class="list-group-item card">
  <div class="checkbox checkbox-inline">
    <label><input type="checkbox" id="checkbox1">Checkbox 1</label>
    <label><input type="checkbox" id="checkbox2">Checkbox 2</label>
  </div>
</li>

Corresponding Jquery:

$(".list-group-item").each(function (i, li) {
  var currentli = $(li);
  $(currentli).find("#checkbox1").on('change', function () {
       $(currentli).find("#checkbox2").not(this).prop('checked',false);
  });

  $(currentli).find("#checkbox2").on('change', function () {
       $(currentli).find("#checkbox1").not(this).prop('checked', false);
  });
});

Working DEMO: https://jsfiddle.net/gr67qk20/

Convert Java Date to UTC String

The following simplified code, based on the accepted answer above, worked for me:

public class GetSync {
    public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
    private static final TimeZone utc = TimeZone.getTimeZone("UTC");
    private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
    static {
        isoFormatter.setTimeZone(utc);
    }

    public static String now() {
        return isoFormatter.format(new Date()).toString();
    }
}

I hope this helps somebody.

How to change color in markdown cells ipython/jupyter notebook?

If none of the above suggestions works for you, try using the style attribute.

**Notes**
<p style="color:red;">ERROR: Setting focus didn't work for me when I tried from jupyter. However it worked well when I ran it from the terminal</p>

This gives me the following result

enter image description here

NGinx Default public www location?

In Ubuntu, Nginx default root Directory location is /usr/share/nginx/html

How to reference a .css file on a razor view?

Using

@Scripts.Render("~/scripts/myScript.js")

or

@Styles.Render("~/styles/myStylesheet.css")

could work for you.

https://stackoverflow.com/a/36157950/2924015

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

Remove the title bar in Windows Forms

Also add this bit of code to your form to allow it to be draggable still.

Just add it right before the constructor (the method that calls InitializeComponent()


private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;

///
/// Handling the window messages
///
protected override void WndProc(ref Message message)
{
    base.WndProc(ref message);

    if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
        message.Result = (IntPtr)HTCAPTION;
}

That code is from: https://jachman.wordpress.com/2006/06/08/enhanced-drag-and-move-winforms-without-having-a-titlebar/

Now to get rid of the title bar but still have a border combine the code from the other response:

this.ControlBox = false;

this.Text = String.Empty;

with this line:

this.FormBorderStyle = FormBorderStyle.FixedSingle;


Put those 3 lines of code into the form's OnLoad event and you should have a nice 'floating' form that is draggable with a thin border (use FormBorderStyle.None if you want no border).

bash: npm: command not found?

in redhat base OS (tested in centos 7)

yum install nodejs npm -y

in debian base OS

apt-get install -y npm    

How to count the frequency of the elements in an unordered list?

You can do this:

import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)

Output:

(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))

The first array is values, and the second array is the number of elements with these values.

So If you want to get just array with the numbers you should use this:

np.unique(a, return_counts=True)[1]