Programs & Examples On #Boot

The boot phase broadly refers to the set of operations that a computer system performs between power-on and access to a graphical/textual shell. Do NOT use this tag for Spring Boot or Twitter Bootstrap. Use [spring-boot] and [twitter-bootstrap] instead.

Run script with rc.local: script works, but not at boot

rc.local only runs on startup. If you reboot and want the script to execute, it needs to go into the rc.0 file starting with the K99 prefix.

How to get to a particular element in a List in java?

CSVReader reader = new CSVReader(new FileReader(
                "myfile.csv"));
        try {
            List<String[]> myEntries = reader.readAll();
            for (String[] s : myEntries) {
               for(String ss : s) {
                   System.out.print(", " + ss);
               }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

Read and write to binary files in C?

Reading and writing binary files is pretty much the same as any other file, the only difference is how you open it:

unsigned char buffer[10];
FILE *ptr;

ptr = fopen("test.bin","rb");  // r for read, b for binary

fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer

You said you can read it, but it's not outputting correctly... keep in mind that when you "output" this data, you're not reading ASCII, so it's not like printing a string to the screen:

for(int i = 0; i<10; i++)
    printf("%u ", buffer[i]); // prints a series of bytes

Writing to a file is pretty much the same, with the exception that you're using fwrite() instead of fread():

FILE *write_ptr;

write_ptr = fopen("test.bin","wb");  // w for write, b for binary

fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer

Since we're talking Linux.. there's an easy way to do a sanity check. Install hexdump on your system (if it's not already on there) and dump your file:

mike@mike-VirtualBox:~/C$ hexdump test.bin
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000010 0001 003e 0001 0000 0000 0000 0000 0000
...

Now compare that to your output:

mike@mike-VirtualBox:~/C$ ./a.out 
127 69 76 70 2 1 1 0 0 0

hmm, maybe change the printf to a %x to make this a little clearer:

mike@mike-VirtualBox:~/C$ ./a.out 
7F 45 4C 46 2 1 1 0 0 0

Hey, look! The data matches up now*. Awesome, we must be reading the binary file correctly!

*Note the bytes are just swapped on the output but that data is correct, you can adjust for this sort of thing

Connect to Oracle DB using sqlplus

sqlplus username/password@database

Eg:

sqlplus hr/hr@orcl

How do I center content in a div using CSS?

with all the adjusting css. if possible, wrap it with a table with height and width as 100% and td set it to vertical align to middle, text-align to center

Attaching click to anchor tag in angular

<a href="javascript:void(0);" (click)="onGoToPage2()">Go to Page 2</a>

How do I convert a number to a numeric, comma-separated formatted string?

I looked at several of the options. Here are my two favorites, because I needed to round the value.

,DataSizeKB = replace(convert(varchar,Cast(Round(SUM(BigNbr / 0.128),0)as money),1), '.00','')
,DataSizeKB2   = format(Round(SUM(BigNbr / 0.128),0),'##,##0')
-----------------
--- below if the full script where I left DataSizeKB in both methods -----------
--- enjoy --------- 
--- Hank Freeman : [email protected] 
-----------------------------------
--- Scritp to get rowcounts and Memory size of index and Primary Keys
   SELECT
   FileGroupName = DS.name
   ,FileGroupType =
      CASE DS.[type]
        WHEN 'FG' THEN 'Filegroup'
        WHEN 'FD' THEN 'Filestream'
        WHEN 'FX' THEN 'Memory-optimized'
        WHEN 'PS' THEN 'Partition Scheme'
        ELSE 'Unknown'
      END
   ,SchemaName = SCH.name
   ,TableName = OBJ.name
   ,IndexType =
      CASE IDX.[type]
        WHEN 0 THEN 'Heap'
        WHEN 1 THEN 'Clustered'
        WHEN 2 THEN 'Nonclustered'
        WHEN 3 THEN 'XML'
        WHEN 4 THEN 'Spatial'
        WHEN 5 THEN 'Clustered columnstore'
        WHEN 6 THEN 'Nonclustered columnstore'
        WHEN 7 THEN 'Nonclustered hash'
      END
   ,IndexName = IDX.name
   ,RowCounts = replace(convert(varchar,Cast(p.rows as money),1), '.00','')  --- MUST show for all types when no Primary key
   --,( Case WHEN IDX.[type] IN (2,6,7) then 0  else  p.rows  end )as Rowcounts_T
   ,AllocationDesc = AU.type_desc
/*
   ,RowCounts = p.rows  --- MUST show for all types when no Primary key
   ,TotalSizeKB2  = Cast(Round(SUM(AU.total_pages / 0.128),0)as int) -- 128 pages per megabyte
   ,UsedSizeKB    = Cast(Round(SUM(AU.used_pages / 0.128),0)as int) 
   ,DataSizeKB    = Cast(Round(SUM(AU.data_pages / 0.128),0)as int)
    --replace(convert(varchar,cast(1234567 as money),1), '.00','')
*/
   ,TotalSizeKB   = replace(convert(varchar,Cast(Round(SUM(AU.total_pages / 0.128),0)as money),1), '.00','') -- 128 pages per megabyte
   ,UsedSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.used_pages / 0.128),0)as money),1), '.00','') 
   ,DataSizeKB    = replace(convert(varchar,Cast(Round(SUM(AU.data_pages / 0.128),0)as money),1), '.00','')
   ,DataSizeKB2   = format(Round(SUM(AU.data_pages / 0.128),0),'##,##0')
   ,DataSizeKB3   = format(SUM(AU.data_pages / 0.128),'##,##0')
   --SELECT Format(1234567.8, '##,##0.00')
   ---
   ,is_default    = CONVERT(INT,DS.is_default)
   ,is_read_only = CONVERT(INT,DS.is_read_only)
  FROM
   sys.filegroups DS -- you could also use sys.data_spaces
    LEFT JOIN sys.allocation_units AU ON DS.data_space_id = AU.data_space_id
    LEFT JOIN sys.partitions PA
      ON (AU.[type] IN (1,3) AND
          AU.container_id = PA.hobt_id) OR
         (AU.[type] = 2 AND
          AU.container_id = PA.[partition_id])
    LEFT JOIN sys.objects OBJ ON PA.[object_id] = OBJ.[object_id]
    LEFT JOIN sys.schemas SCH ON OBJ.[schema_id] = SCH.[schema_id]
    LEFT JOIN sys.indexes IDX
      ON PA.[object_id] = IDX.[object_id] AND
         PA.index_id = IDX.index_id
    -----
    INNER JOIN 
      sys.partitions p ON obj.object_id = p.OBJECT_ID AND IDX.index_id = p.index_id
  WHERE
    OBJ.type_desc = 'USER_TABLE' -- only include user tables
    OR
    DS.[type] = 'FD' -- or the filestream filegroup
  GROUP BY
    DS.name ,SCH.name ,OBJ.name ,IDX.[type] ,IDX.name ,DS.[type]  ,DS.is_default   ,DS.is_read_only -- discard different allocation units
   ,p.rows  ,AU.type_desc  --- 
  ORDER BY
    DS.name ,SCH.name ,OBJ.name ,IDX.name
   ---
   ;

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How do I count the number of rows and columns in a file using bash?

Columns: awk '{print NF}' file | sort -nu | tail -n 1

Use head -n 1 for lowest column count, tail -n 1 for highest column count.

Rows: cat file | wc -l or wc -l < file for the UUOC crowd.

Uncaught TypeError: .indexOf is not a function

I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.

You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.

if( param.indexOf != undefined ) {
   // we have a string or other object that 
   // happens to have a function named indexOf
}

You can test this in your browser console:

> (3).indexOf == undefined;
true

> "".indexOf == undefined;
false

Converting an integer to a hexadecimal string in Ruby

To summarize:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

How to change plot background color?

Use the set_facecolor(color) method of the axes object, which you've created one of the following ways:

  • You created a figure and axis/es together

    fig, ax = plt.subplots(nrows=1, ncols=1)
    
  • You created a figure, then axis/es later

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
    
  • You used the stateful API (if you're doing anything more than a few lines, and especially if you have multiple plots, the object-oriented methods above make life easier because you can refer to specific figures, plot on certain axes, and customize either)

    plt.plot(...)
    ax = plt.gca()
    

Then you can use set_facecolor:

ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))

example plot with pink background on the axes

As a refresher for what colors can be:

matplotlib.colors

Matplotlib recognizes the following formats to specify a color:

  • an RGB or RGBA tuple of float values in [0, 1] (e.g., (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3));
  • a hex RGB or RGBA string (e.g., '#0F0F0F' or '#0F0F0F0F');
  • a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5');
  • one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'};
  • a X11/CSS4 color name;
  • a name from the xkcd color survey; prefixed with 'xkcd:' (e.g., 'xkcd:sky blue');
  • one of {'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'} which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle);
  • a “CN” color spec, i.e. 'C' followed by a single digit, which is an index into the default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.

All string specifications of color, other than “CN”, are case-insensitive.

Return HTTP status code 201 in flask

As lacks suggested send status code in return statement and if you are storing it in some variable like

notfound = 404
invalid = 403
ok = 200

and using

return xyz, notfound

than time make sure its type is int not str. as I faced this small issue also here is list of status code followed globally http://www.w3.org/Protocols/HTTP/HTRESP.html

Hope it helps.

How do I write a for loop in bash

Try the bash built-in help:


$ help for

for: for NAME [in WORDS ... ;] do COMMANDS; done
    The `for' loop executes a sequence of commands for each member in a
    list of items.  If `in WORDS ...;' is not present, then `in "$@"' is
    assumed.  For each element in WORDS, NAME is set to that element, and
    the COMMANDS are executed.
for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
    Equivalent to
        (( EXP1 ))
        while (( EXP2 )); do
            COMMANDS
            (( EXP3 ))
        done
    EXP1, EXP2, and EXP3 are arithmetic expressions.  If any expression is
    omitted, it behaves as if it evaluates to 1.


Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

Slidedown and slideup layout with animation

I use these easy functions, it work like jquery slideUp slideDown, use it in an helper class, just pass your view :

public static void expand(final View v) {
    v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    final int targetHeight = v.getMeasuredHeight();

    // Older versions of android (pre API 21) cancel animations for views with a height of 0.
    v.getLayoutParams().height = 1;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? WindowManager.LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

public static void collapse(final View v) {
    final int initialHeight = v.getMeasuredHeight();

    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if(interpolatedTime == 1){
                v.setVisibility(View.GONE);
            }else{
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

Unsuccessful append to an empty NumPy array

numpy.append always copies the array before appending the new values. Your code is equivalent to the following:

import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)

Perhaps you mean to do this?

import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])

How do I merge my local uncommitted changes into another Git branch?

Stashing, temporary commits and rebasing may all be overkill. If you haven't added the changed files to the index, yet, then you may be able to just checkout the other branch.

git checkout branch2

This will work so long as no files that you are editing are different between branch1 and branch2. It will leave you on branch2 with you working changes preserved. If they are different then you can specify that you want to merge your local changes with the changes introduced by switching branches with the -m option to checkout.

git checkout -m branch2

If you've added changes to the index then you'll want to undo these changes with a reset first. (This will preserve your working copy, it will just remove the staged changes.)

git reset

How to develop Android app completely using python?

Android, Python !

When I saw these two keywords together in your question, Kivy is the one which came to my mind first.

Kivy logo

Before coming to native Android development in Java using Android Studio, I had tried Kivy. It just awesome. Here are a few advantage I could find out.


Simple to use

With a python basics, you won't have trouble learning it.


Good community

It's well documented and has a great, active community.


Cross platform.

You can develop thing for Android, iOS, Windows, Linux and even Raspberry Pi with this single framework. Open source.


It is a free software

At least few of it's (Cross platform) competitors want you to pay a fee if you want a commercial license.


Accelerated graphics support

Kivy's graphics engine build over OpenGL ES 2 makes it suitable for softwares which require fast graphics rendering such as games.



Now coming into the next part of question, you can't use Android Studio IDE for Kivy. Here is a detailed guide for setting up the development environment.

How to install python developer package?

yum install python-devel will work.

If yum doesn't work then use

apt-get install python-dev

How to define relative paths in Visual Studio Project?

I have used a syntax like this before:

$(ProjectDir)..\headers

or

..\headers

As other have pointed out, the starting directory is the one your project file is in(vcproj or vcxproj), not where your main code is located.

C# - How to convert string to char?

Your question is a bit unclear, but I think you want (requires using System.Linq;):

var result = yourArrayOfStrings.SelectMany(s => s).ToArray();

Another solution is:

var result = string.Concat(yourArrayOfStrings).ToCharArray();

How to check not in array element

$array1 = "Orange";
$array2 = array("Apple","Grapes","Orange","Pineapple");
if(in_array($array1,$array2)){
    echo $array1.' exists in array2';
}else{
    echo $array1.'does not exists in array2';
}

How to get a MemoryStream from a Stream in .NET?

If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:

public class MyClass
{ 
    Stream _s;

    public MyClass(Stream s) { _s = s; }
}

But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:

public MyClass(Stream stream)
{
    _ms = new MemoryStream();
    CopyStream(stream, _ms);
}

// Merged From linked CopyStream below and Jon Skeet's ReadFully example
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[16*1024];
    int read;
    while((read = input.Read (buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

HTML5 best practices; section/header/aside/article elements

The div elements can be replaced with the new elements: header, nav, section, article, aside, and footer.

The markup for that document could look like the following:

<body>
     <header>...</header>
     <nav>...</nav>
     <article>
          <section>
               ...
          </section>
     </article>
     <aside>...</aside>
     <footer>...</footer>
</body>

You may find more information in this article on A List Apart.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

Making view resize to its parent when added with addSubview

Swift 4 extension using explicit constraints:

import UIKit.UIView

extension UIView {
    public func addSubview(_ subview: UIView, stretchToFit: Bool = false) {
        addSubview(subview)
        if stretchToFit {
            subview.translatesAutoresizingMaskIntoConstraints = false
            leftAnchor.constraint(equalTo: subview.leftAnchor).isActive = true
            rightAnchor.constraint(equalTo: subview.rightAnchor).isActive = true
            topAnchor.constraint(equalTo: subview.topAnchor).isActive = true
            bottomAnchor.constraint(equalTo: subview.bottomAnchor).isActive = true
        }
    }
}

Usage:

parentView.addSubview(childView) // won't resize (default behavior unchanged)
parentView.addSubview(childView, stretchToFit: false) // won't resize
parentView.addSubview(childView, stretchToFit: true) // will resize

Seeing the underlying SQL in the Spring JdbcTemplate?

Try adding in log4j.xml

<!--  enable query logging -->
<category name="org.springframework.jdbc.core.JdbcTemplate">
    <priority value="DEBUG" />
</category>

<!-- enable query logging for SQL statement parameter value -->
<category name="org.springframework.jdbc.core.StatementCreatorUtils">
    <priority value="TRACE" />
</category>

your logs looks like:

DEBUG JdbcTemplate:682 - Executing prepared SQL query
DEBUG JdbcTemplate:616 - Executing prepared SQL statement [your sql query]
TRACE StatementCreatorUtils:228 - Setting SQL statement parameter value: column index 1, parameter value [param], value class [java.lang.String], SQL type unknown

What is the most compatible way to install python modules on a Mac?

The most popular way to manage python packages (if you're not using your system package manager) is to use setuptools and easy_install. It is probably already installed on your system. Use it like this:

easy_install django

easy_install uses the Python Package Index which is an amazing resource for python developers. Have a look around to see what packages are available.

A better option is pip, which is gaining traction, as it attempts to fix a lot of the problems associated with easy_install. Pip uses the same package repository as easy_install, it just works better. Really the only time use need to use easy_install is for this command:

easy_install pip

After that, use:

pip install django

At some point you will probably want to learn a bit about virtualenv. If you do a lot of python development on projects with conflicting package requirements, virtualenv is a godsend. It will allow you to have completely different versions of various packages, and switch between them easily depending your needs.

Regarding which python to use, sticking with Apple's python will give you the least headaches, but If you need a newer version (Leopard is 2.5.1 I believe), I would go with the macports python 2.6.

Searching for UUIDs in text with regex

Wanted to give my contribution, as my regex cover all cases from OP and correctly group all relevant data on the group method (you don't need to post process the string to get each part of the uuid, this regex already get it for you)

([\d\w]{8})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{12})|[{0x]*([\d\w]{8})[0x, ]{4}([\d\w]{4})[0x, ]{4}([\d\w]{4})[0x, {]{5}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})

Login credentials not working with Gmail SMTP

if you are getting error this(535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials o60sm2132303pje.21 - gsmtp')

then simply go in you google accountsettings of security section and make a less secure account and turn on the less secure button

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

SET JAVA_HOME=C:\Program Files\Java\jdk1.8.0

worked fine for me.

Note - Don't put double quotes over the path as mentioned above. Otherwise when you run

mvn -version

it will give following error

Files\java\jdk1.8.0_201\jre""=="" was unexpected at this time.

Remove everything after a certain character

Worked for me:

      var first = regexLabelOut.replace(/,.*/g, "");

PowerShell script to check the status of a URL

I recently set up a script that does this.

As David Brabant pointed out, you can use the System.Net.WebRequest class to do an HTTP request.

To check whether it is operational, you should use the following example code:

# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')

# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()

# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode

If ($HTTP_Status -eq 200) {
    Write-Host "Site is OK!"
}
Else {
    Write-Host "The Site may be down, please check!"
}

# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { } 
Else { $HTTP_Response.Close() }

How can I make Java print quotes, like "Hello"?

System.out.println("\"Hello\"")

Spark : how to run spark file from spark shell

You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven

<repository>
      <id>Spark repository</id>
      <url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>

And then the dependency:

<dependency>
      <groupId>spark</groupId>
      <artifactId>spark</artifactId>
      <version>1.2.0</version>
</dependency>

In terms of running a file with spark commands: you can simply do this:

echo"
   import org.apache.spark.sql.*
   ssc = new SQLContext(sc)
   ssc.sql("select * from mytable").collect
" > spark.input

Now run the commands script:

cat spark.input | spark-shell

Android LinearLayout Gradient Background

I would check your alpha channel on your gradient colors. For me, when I was testing my code out I had the alpha channel set wrong on the colors and it did not work for me. Once I got the alpha channel set it all worked!

Sum one number to every element in a list (or array) in Python

You can also use map:

a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))

It gives:

[2, 2, 2, 2, 2]

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

How to deal with the URISyntaxException

Coudn't imagine nothing better for
http://server.ru:8080/template/get?type=mail&format=html&key=ecm_task_assignment&label=??????????? ? ????????????&descr=????????&objectid=2231
that:

public static boolean checkForExternal(String str) {
    int length = str.length();
    for (int i = 0; i < length; i++) {
        if (str.charAt(i) > 0x7F) {
            return true;
        }
    }
    return false;
}

private static final Pattern COLON = Pattern.compile("%3A", Pattern.LITERAL);
private static final Pattern SLASH = Pattern.compile("%2F", Pattern.LITERAL);
private static final Pattern QUEST_MARK = Pattern.compile("%3F", Pattern.LITERAL);
private static final Pattern EQUAL = Pattern.compile("%3D", Pattern.LITERAL);
private static final Pattern AMP = Pattern.compile("%26", Pattern.LITERAL);

public static String encodeUrl(String url) {
    if (checkForExternal(url)) {
        try {
            String value = URLEncoder.encode(url, "UTF-8");
            value = COLON.matcher(value).replaceAll(":");
            value = SLASH.matcher(value).replaceAll("/");
            value = QUEST_MARK.matcher(value).replaceAll("?");
            value = EQUAL.matcher(value).replaceAll("=");
            return AMP.matcher(value).replaceAll("&");
        } catch (UnsupportedEncodingException e) {
            throw LOGGER.getIllegalStateException(e);
        }
    } else {
        return url;
    }
}

How to install pandas from pip on windows cmd?

Assuming you are using Windows OS.

All you need to add the pip.exe path to the Environment Variables (Path).

Generally, you can find it under ..Python\Scripts folder.

For me it is, C:\Program Files\Python36\Scripts\

C# - Print dictionary

More cleaner way using LINQ

var lines = dictionary.Select(kvp => kvp.Key + ": " + kvp.Value.ToString());
textBox3.Text = string.Join(Environment.NewLine, lines);

Search for "does-not-contain" on a DataFrame in pandas

You can use Apply and Lambda to select rows where a column contains any thing in a list. For your scenario :

df[df["col"].apply(lambda x:x not in [word1,word2,word3])]

-XX:MaxPermSize with or without -XX:PermSize

If you're doing some performance tuning it's often recommended to set both -XX:PermSize and -XX:MaxPermSize to the same value to increase JVM efficiency.

Here is some information:

  1. Support for large page heap on x86 and amd64 platforms
  2. Java Support for Large Memory Pages
  3. Setting the Permanent Generation Size

You can also specify -XX:+CMSClassUnloadingEnabled to enable class unloading option if you are using CMS GC. It may help to decrease the probability of Java.lang.OutOfMemoryError: PermGen space

NLTK and Stopwords Fail #lookuperror

import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
STOPWORDS = set(stopwords.words('english'))

How to get first 5 characters from string

Use substr():

$result = substr($myStr, 0, 5);

How to use multiprocessing queue in Python?

A multi-producers and multi-consumers example, verified. It should be easy to modify it to cover other cases, single/multi producers, single/multi consumers.

from multiprocessing import Process, JoinableQueue
import time
import os

q = JoinableQueue()

def producer():
    for item in range(30):
        time.sleep(2)
        q.put(item)
    pid = os.getpid()
    print(f'producer {pid} done')


def worker():
    while True:
        item = q.get()
        pid = os.getpid()
        print(f'pid {pid} Working on {item}')
        print(f'pid {pid} Finished {item}')
        q.task_done()

for i in range(5):
    p = Process(target=worker, daemon=True).start()

# send thirty task requests to the worker
producers = []
for i in range(2):
    p = Process(target=producer)
    producers.append(p)
    p.start()

# make sure producers done
for p in producers:
    p.join()

# block until all workers are done
q.join()
print('All work completed')

Explanation:

  1. Two producers and five consumers in this example.
  2. JoinableQueue is used to make sure all elements stored in queue will be processed. 'task_done' is for worker to notify an element is done. 'q.join()' will wait for all elements marked as done.
  3. With #2, there is no need to join wait for every worker.
  4. But it is important to join wait for every producer to store element into queue. Otherwise, program exit immediately.

Upload Image using POST form data in Python-requests

From wechat api doc:

curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)

Spring Boot, Spring Data JPA with multiple DataSources

thanks to the answers of Steve Park and Rafal Borowiec I got my code working, however, I had one issue: the DriverManagerDataSource is a "simple" implementation and does NOT give you a ConnectionPool (check http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html).

Hence, I replaced the functions which returns the DataSource for the secondDB to.

public DataSource <secondaryDB>DataSource() {
    // use DataSourceBuilder and NOT DriverManagerDataSource 
    // as this would NOT give you ConnectionPool
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.url(databaseUrl);
    dataSourceBuilder.username(username);
    dataSourceBuilder.password(password);
    dataSourceBuilder.driverClassName(driverClassName);
    return dataSourceBuilder.build();
}

Also, if do you not need the EntityManager as such, you can remove both the entityManager() and the @Bean annotation.

Plus, you may want to remove the basePackages annotation of your configuration class: maintaining it with the factoryBean.setPackagesToScan() call is sufficient.

How to properly override clone method?

Just because java's implementation of Cloneable is broken it doesn't mean you can't create one of your own.

If OP real purpose was to create a deep clone, i think that it is possible to create an interface like this:

public interface Cloneable<T> {
    public T getClone();
}

then use the prototype constructor mentioned before to implement it:

public class AClass implements Cloneable<AClass> {
    private int value;
    public AClass(int value) {
        this.vaue = value;
    }

    protected AClass(AClass p) {
        this(p.getValue());
    }

    public int getValue() {
        return value;
    }

    public AClass getClone() {
         return new AClass(this);
    }
}

and another class with an AClass object field:

public class BClass implements Cloneable<BClass> {
    private int value;
    private AClass a;

    public BClass(int value, AClass a) {
         this.value = value;
         this.a = a;
    }

    protected BClass(BClass p) {
        this(p.getValue(), p.getA().getClone());
    }

    public int getValue() {
        return value;
    }

    public AClass getA() {
        return a;
    }

    public BClass getClone() {
         return new BClass(this);
    }
}

In this way you can easely deep clone an object of class BClass without need for @SuppressWarnings or other gimmicky code.

jQuery DIV click, with anchors

If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
    return false;
});

See event.preventDefault() vs. return false for details on return false vs. preventDefault.

Eclipse, regular expression search and replace

Yes, ( ) captures a group. You can use it again with $i where i is the i'th capture group.

So:

search: (\w+\.someMethod\(\))

replace: ((TypeName)$1)

Hint: Ctrl + Space in the textboxes gives you all kinds of suggestions for regular expression writing.

! [rejected] master -> master (fetch first)

Sometimes it happens when you duplicate files typically README sort of.

Package opencv was not found in the pkg-config search path

with opencv 4.0;

  • add -DOPENCV_GENERATE_PKGCONFIG=ON to build arguments
  • pkg-config --cflags --libs opencv4 instead of opencv

How to assign multiple classes to an HTML container?

you need to put a dot between the class like

class="column.wrapper">

How do I put double quotes in a string in vba?

I prefer the answer of tabSF . implementing the same to your answer. here below is my approach

Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"

Inline <style> tags vs. inline css properties

There can be different reasons for choosing one way over the other.

  • If you need to specify css to elements that are generated programmatically (for example modifying css for images of different sizes), it can be more maintainable to use inline css.
  • If some css is valid only for the current page, you should rather use the script tag than a separate .css file. It is good if the browser doesn't have to do too many http requests.

Otherwise, as stated, it is better to use a separate css file.

PHP PDO returning single row

Did you try:

$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;

How to convert a time string to seconds?

A little more pythonic way I think would be:

timestr = '00:04:23'

ftr = [3600,60,1]

sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])

Output is 263Sec.

I would be interested to see if anyone could simplify it further.

Responsive iframe using Bootstrap

Option 1

With Bootstrap 3.2 you can wrap each iframe in the responsive-embed wrapper of your choice:

http://getbootstrap.com/components/#responsive-embed

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="…"></iframe>
</div>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="…"></iframe>
</div>

Option 2

If you don't want to wrap your iframes, you can use FluidVids https://github.com/toddmotto/fluidvids. See demo here: http://toddmotto.com/labs/fluidvids/

   <!-- fluidvids.js -->
    <script src="js/fluidvids.js"></script>
    <script>
    fluidvids.init({
      selector: ['iframe'],
      players: ['www.youtube.com', 'player.vimeo.com']
    });
    </script>

rejected master -> master (non-fast-forward)

The only i was able to resolve this issue was to delete the local and git repo and create the same again at both ends. Works fine for now.

WPF ListView turn off selection

One of the properties of the listview is IsHitTestVisible. Uncheck it.

counting number of directories in a specific directory

Run stat -c %h folder and subtract 2 from the result. This employs only a single subprocess as opposed to the 2 (or even 3) required by most of the other solutions here (typically find plus wc).

Using sh/bash:

cnt=$((`stat -c %h folder` - 2))
echo $cnt   # 'echo' is a sh/bash builtin, not an additional process

Using csh/tcsh:

@ cnt = `stat -c %h folder` - 2
echo $cnt   # 'echo' is a csh/tcsh builtin, not an additional process


Explanation: stat -c %h folder prints the number of hardlinks to folder, and each subfolder under folder contains a ../ entry which is a hardlink back to folder. You must subtract 2 because there are two additional hardlinks in the count:

  1. folder's own self-referential ./ entry, and
  2. folder's parent's link to folder

Setting a property by reflection with a string value

If you are writing Metro app, you should use other code:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType));

Note:

ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude");

instead of

ship.GetType().GetProperty("Latitude");

In Jenkins, how to checkout a project into a specific directory (using GIT)

The default git plugin for Jenkins does the job quite nicely.

After adding a new git repository (project configuration > Source Code Management > check the GIT option) to the project navigate to the bottom of the plugin settings, just above Repository browser region. There should be an Advanced button. After clicking it a new form should appear, with a value described as Local subdirectory for repo (optional). Setting this to folder will make the plugin to check out the repository into the folder relative to your workspace. This way you can have as many repositories in your project as you need, all in separate locations.

Alternatively, if the project you're using will allow that, you can use GIT sub modules, which are similar to external paths in SVN. In the GIT Book there is a section on that very topic. If that will not be against some policy, submodules are fairly simple to use, giving you powerful way to control the locations, versions/tags/branches that will be imported AND it will be available on your local repository as well giving you better portability.

Obviously the GIT plugin supports checking out submodules, so Jenkins can work with them quite effectively.

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

If Android Studio directly opening your project instead of setup window, then just close the windows of all projects. Now you will able to see the startup window. If SDK is missing then it will provide option to download SDK and other required tools.

It works for me.

Can pm2 run an 'npm start' script

you need to provide app name here like myapp

pm2 start npm --name {appName} -- run {script name}

you can check it by

pm2 list

you can also add time

pm2 restart "id" --log-date-format 'DD-MM HH:mm:ss.SSS' or pm2 restart "id" --time

you can check logs by

pm2 log "id" or pm2 log "appName"

to get logs for all app

pm2 logs

Initial bytes incorrect after Java AES/CBC decryption

Here a solution without Apache Commons Codec's Base64:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AdvancedEncryptionStandard
{
    private byte[] key;

    private static final String ALGORITHM = "AES";

    public AdvancedEncryptionStandard(byte[] key)
    {
        this.key = key;
    }

    /**
     * Encrypts the given plain text
     *
     * @param plainText The plain text to encrypt
     */
    public byte[] encrypt(byte[] plainText) throws Exception
    {
        SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        return cipher.doFinal(plainText);
    }

    /**
     * Decrypts the given byte array
     *
     * @param cipherText The data to decrypt
     */
    public byte[] decrypt(byte[] cipherText) throws Exception
    {
        SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        return cipher.doFinal(cipherText);
    }
}

Usage example:

byte[] encryptionKey = "MZygpewJsCpRrfOr".getBytes(StandardCharsets.UTF_8);
byte[] plainText = "Hello world!".getBytes(StandardCharsets.UTF_8);
AdvancedEncryptionStandard advancedEncryptionStandard = new AdvancedEncryptionStandard(
        encryptionKey);
byte[] cipherText = advancedEncryptionStandard.encrypt(plainText);
byte[] decryptedCipherText = advancedEncryptionStandard.decrypt(cipherText);

System.out.println(new String(plainText));
System.out.println(new String(cipherText));
System.out.println(new String(decryptedCipherText));

Prints:

Hello world!
?;??LA+??b*
Hello world!

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

Diff files present in two different directories

Here is a script to show differences between files in two folders. It works recursively. Change dir1 and dir2.

(search() { for i in $1/*; do [ -f "$i" ] && (diff "$1/${i##*/}" "$2/${i##*/}" || echo "files: $1/${i##*/}   $2/${i##*/}"); [ -d "$i" ] && search "$1/${i##*/}" "$2/${i##*/}"; done }; search "dir1" "dir2" )

How to compare only date in moment.js

You could use startOf('day') method to compare just the date

Example :

var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());

dateToCompare.startOf('day').isSame(today.startOf('day'));

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

Activity has leaked window that was originally added

In my case, the reason was that I forgot to include a permission in the Android manifest file.

How did I find out? Well, just like @Bobby says in a comment beneath the accepted answer, just scroll further up to your logs and you'll see the first reason or event that really threw the Exception. Apparently, the message "Activity has leaked window that was originally added" is only an Exception that resulted from whatever the first Exception is.

Removing the remembered login and password list in SQL Server Management Studio

In my scenario I only wanted to remove a specific username/password from the list which had many other saved connections I didn't want to forget. It turns out the SqlStudio.bin file others are discussing here is a .NET binary serialization of the Microsoft.SqlServer.Management.UserSettings.SqlStudio class, which can be deserialized, modified and reserialized to modify specific settings.

To accomplish removal of the specific login, I created a new C# .Net 4.6.1 console application and added a reference to the namespace which is located in the following dll: C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\Microsoft.SqlServer.Management.UserSettings.dll (your path may differ slightly depending on SSMS version)

From there I could easily create and modify the settings as desired:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Management.UserSettings;

class Program
{
    static void Main(string[] args)
    {
        var settingsFile = new FileInfo(@"C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin");

        // Backup our original file just in case...
        File.Copy(settingsFile.FullName, settingsFile.FullName + ".backup");

        BinaryFormatter fmt = new BinaryFormatter();

        SqlStudio settings = null;

        using(var fs = settingsFile.Open(FileMode.Open))
        {
            settings = (SqlStudio)fmt.Deserialize(fs);
        }

        // The structure of server types / servers / connections requires us to loop
        // through multiple nested collections to find the connection to be removed.
        // We start here with the server types

        var serverTypes = settings.SSMS.ConnectionOptions.ServerTypes;

        foreach (var serverType in serverTypes)
        {
            foreach (var server in serverType.Value.Servers)
            {
                // Will store the connection for the provided server which should be removed
                ServerConnectionSettings removeConn = null;

                foreach (var conn in server.Connections)
                {
                    if (conn.UserName == "adminUserThatShouldBeRemoved")
                    {
                        removeConn = conn;
                        break;
                    }
                }

                if (removeConn != null)
                {
                    server.Connections.RemoveItem(removeConn);
                }
            }
        }

        using (var fs = settingsFile.Open(FileMode.Create))
        {
            fmt.Serialize(fs, settings);
        }
    }
}

How to split a string in shell and get the last field

for x in `echo $str | tr ";" "\n"`; do echo $x; done

Check if a String contains numbers Java

The solution I went with looks like this:

Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);

Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);

if (matcher1.find() && matcher2.find())
{
    int number = Integer.parseInt(matcher1.group());                    
    pw.println(number + " squared = " + (number * number));
}

I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

  1. Make a jar file from your applet class and META-INF/MANIFEST.MF file.
  2. Sign your jar file with your certificate.
  3. Configure your local site permissions as > file:///C:/ or http: //localhost:8080
  4. Then run your html document on Intenet Explorer on Windows.(Not Google Chrome !)

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

Equivalent to 'app.config' for a library (DLL)

In response to the original question, I typically add the config file in my test project as a link; you can then use the DeploymentItem attribute to addit to the Out folder of the test run.

[TestClass]
[DeploymentItem("MyProject.Cache.dll.config")]
public class CacheTest
{
    .
    .
    .
    .
}

In response to the comments that Assemblies can't be project specific, they can and it provides great flexibility esp. when working with IOC frameworks.

How to configure encoding in Maven?

In my case I was using the maven-dependency-plugin so in order to resolve the issue I had to add the following property:

  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

See Apache Maven Resources Plugin / Specifying a character encoding scheme

how to dynamically add options to an existing select in vanilla javascript

.add() also works.

var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(option);

W3 School - try

Node.js throws "btoa is not defined" error

The 'btoa-atob' module does not export a programmatic interface, it only provides command line utilities.

If you need to convert to Base64 you could do so using Buffer:

console.log(Buffer.from('Hello World!').toString('base64'));

Reverse (assuming the content you're decoding is a utf8 string):

console.log(Buffer.from(b64Encoded, 'base64').toString());

Note: prior to Node v4, use new Buffer rather than Buffer.from.

Path.Combine absolute with relative path strings

Path.GetFullPath() does not work with relative paths.

Here's the solution that works with both relative + absolute paths. It works on both Linux + Windows and it keeps the .. as expected in the beginning of the text (at rest they will be normalized). The solution still relies on Path.GetFullPath to do the fix with a small workaround.

It's an extension method so use it like text.Canonicalize()

/// <summary>
///     Fixes "../.." etc
/// </summary>
public static string Canonicalize(this string path)
{
    if (path.IsAbsolutePath())
        return Path.GetFullPath(path);
    var fakeRoot = Environment.CurrentDirectory; // Gives us a cross platform full path
    var combined = Path.Combine(fakeRoot, path);
    combined = Path.GetFullPath(combined);
    return combined.RelativeTo(fakeRoot);
}
private static bool IsAbsolutePath(this string path)
{
    if (path == null) throw new ArgumentNullException(nameof(path));
    return
        Path.IsPathRooted(path)
        && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
        && !Path.GetPathRoot(path).Equals(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal);
}
private static string RelativeTo(this string filespec, string folder)
{
    var pathUri = new Uri(filespec);
    // Folders must end in a slash
    if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) folder += Path.DirectorySeparatorChar;
    var folderUri = new Uri(folder);
    return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString()
        .Replace('/', Path.DirectorySeparatorChar));
}

How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

Setting up Gradle for api 26 (Android)

You could add google() to repositories block

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'

        }
        maven {
            url "https://jitpack.io"
        }
        google()
    }
}

Import Libraries in Eclipse?

No, don't do it that way.

From your Eclipse workspace, right click your project on the left pane -> Properties -> Java Build Path -> Add Jars -> add your jars here.

Tadaa!! :)

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

Another addition: be careful when replacing multiples and converting the type of the column back from object to float. If you want to be certain that your None's won't flip back to np.NaN's apply @andy-hayden's suggestion with using pd.where. Illustration of how replace can still go 'wrong':

In [1]: import pandas as pd

In [2]: import numpy as np

In [3]: df = pd.DataFrame({"a": [1, np.NAN, np.inf]})

In [4]: df
Out[4]:
     a
0  1.0
1  NaN
2  inf

In [5]: df.replace({np.NAN: None})
Out[5]:
      a
0     1
1  None
2   inf

In [6]: df.replace({np.NAN: None, np.inf: None})
Out[6]:
     a
0  1.0
1  NaN
2  NaN

In [7]: df.where((pd.notnull(df)), None).replace({np.inf: None})
Out[7]:
     a
0  1.0
1  NaN
2  NaN

Object reference not set to an instance of an object.

strSearch in this case is probably null (not simply empty).

Try using

String.IsNullOrEmpty(strSearch)

if you are just trying to determine if the string doesn't have any contents.

How to clear form after submit in Angular 2?

See also https://angular.io/docs/ts/latest/guide/reactive-forms.html (section "reset the form flags")

>=RC.6

In RC.6 it should be supported to update the form model. Creating a new form group and assigning to myForm

[formGroup]="myForm"

will also be supported (https://github.com/angular/angular/pull/11051#issuecomment-243483654)

>=RC.5

form.reset();

In the new forms module (>= RC.5) NgForm has a reset() method and also supports a forms reset event. https://github.com/angular/angular/blob/6fd5bc075d70879c487c0188f6cd5b148e72a4dd/modules/%40angular/forms/src/directives/ng_form.ts#L179

<=RC.3

This will work:

onSubmit(value:any):void {
  //send some data to backend
  for(var name in form.controls) {
    (<Control>form.controls[name]).updateValue('');
    /*(<FormControl>form.controls[name]).updateValue('');*/ this should work in RC4 if `Control` is not working, working same in my case
    form.controls[name].setErrors(null);
  }
}

See also

How to install python modules without root access?

Install virtualenv locally (source of instructions):

Important: Insert the current release (like 16.1.0) for X.X.X.
Check the name of the extracted file and insert it for YYYYY.

$ curl -L -o virtualenv.tar.gz https://github.com/pypa/virtualenv/tarball/X.X.X
$ tar xfz virtualenv.tar.gz
$ python pypa-virtualenv-YYYYY/src/virtualenv.py env

Before you can use or install any package you need to source your virtual Python environment env:

$ source env/bin/activate

To install new python packages (like numpy), use:

(env)$ pip install <package>

How do I get the latest version of my code?

By Running this command you'll get the most recent tag that usually is the version of your project:

git describe --abbrev=0 --tags

How do I make a file:// hyperlink that works in both IE and Firefox?

Paste following link to directly under link button click event, otherwise use javascript to call code behind function

Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs) 
    System.Diagnostics.Process.Start(FilePath)
End Sub

How do I specify new lines on Python, when writing on files?

Simplest solution

If you only call print without any arguments, it will output a blank line.

print

You can pipe the output to a file like this (considering your example):

f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()

Not only is it OS-agnostic (without even having to use the os package), it's also more readable than putting \n within strings.

Explanation

The print() function has an optional keyword argument for the end of the string, called end, which defaults to the OS's newline character, for eg. \n. So, when you're calling print('hello'), Python is actually printing 'hello' + '\n'. Which means that when you're calling just print without any arguments, it's actually printing '' + '\n', which results in a newline.

Alternative

Use multi-line strings.

s = """First line
    Second line
    Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

You can do (if you want to test NULL)

$this->db->where_exec('archived IS NULL) 

If you want to test NOT NULL

$this->db->where_exec('archived IS NOT NULL) 

JSON order mixed up

Just add the order with this tag

@JsonPropertyOrder({ "property1", "property2"})

React.js: Identifying different inputs with one onChange handler

You can use a special React attribute called ref and then match the real DOM nodes in the onChange event using React's getDOMNode() function:

handleClick: function(event) {
  if (event.target === this.refs.prev.getDOMNode()) {
    ...
  }
}

render: function() {
  ...
  <button ref="prev" onClick={this.handleClick}>Previous question</button>
  <button ref="next" onClick={this.handleClick}>Next question</button>
  ...
}

HTML/JavaScript: Simple form validation on submit

Disclosure: I wrote FieldVal.

Here is a solution using FieldVal. By using FieldVal UI to build a form and then FieldVal to validate the input, you can pass the error straight back into the form.

You can even run the validation code on the backend (if you're using Node.js) and show the error in the form without wiring all of the fields up manually.

Live demo: http://codepen.io/MarcusLongmuir/pen/WbOydx

function validate_form(data) {
    // This would work on the back end too (if you're using Node)

    // Validate the provided data
    var validator = new FieldVal(data);
    validator.get("email", BasicVal.email(true));
    validator.get("title", BasicVal.string(true));
    validator.get("url", BasicVal.url(true));
    return validator.end();
}


$(document).ready(function(){

    // Create a form and add some fields
    var form = new FVForm()
    .add_field("email", new FVTextField("Email"))
    .add_field("title", new FVTextField("Title"))
    .add_field("url", new FVTextField("URL"))
    .on_submit(function(value){

        // Clear the existing errors
        form.clear_errors();

        // Use the function above to validate the input
        var error = validate_form(value);

        if (error) {
            // Pass the error into the form
            form.error(error);
        } else {
            // Use the data here
            alert(JSON.stringify(value));
        }
    })

    form.element.append(
        $("<button/>").text("Submit")
    ).appendTo("body");

    //Pre-populate the form
    form.val({
        "email": "[email protected]",
        "title": "Your Title",
        "url": "http://www.example.com"
    })
});

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Get file version in PowerShell

Nowadays you can get the FileVersionInfo from Get-Item or Get-ChildItem, but it will show the original FileVersion from the shipped product, and not the updated version. For instance:

(Get-Item C:\Windows\System32\Lsasrv.dll).VersionInfo.FileVersion

Interestingly, you can get the updated (patched) ProductVersion by using this:

(Get-Command C:\Windows\System32\Lsasrv.dll).Version

The distinction I'm making between "original" and "patched" is basically due to the way the FileVersion is calculated (see the docs here). Basically ever since Vista, the Windows API GetFileVersionInfo is querying part of the version information from the language neutral file (exe/dll) and the non-fixed part from a language-specific mui file (which isn't updated every time the files change).

So with a file like lsasrv (which got replaced due to security problems in SSL/TLS/RDS in November 2014) the versions reported by these two commands (at least for a while after that date) were different, and the second one is the more "correct" version.

However, although it's correct in LSASrv, it's possible for the ProductVersion and FileVersion to be different (it's common, in fact). So the only way to get the updated Fileversion straight from the assembly file is to build it up yourself from the parts, something like this:

Get-Item C:\Windows\System32\Lsasrv.dll | ft FileName, File*Part

Or by pulling the data from this:

[System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)

You can easily add this to all FileInfo objects by updating the TypeData in PowerShell:

Update-TypeData -TypeName System.IO.FileInfo -MemberName FileVersion -MemberType ScriptProperty -Value {
   [System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName) | % {
      [Version](($_.FileMajorPart, $_.FileMinorPart, $_.FileBuildPart, $_.FilePrivatePart)-join".") 
   }
}

Now every time you do Get-ChildItem or Get-Item you'll have a FileVersion property that shows the updated FileVersion ...

How can I Remove .DS_Store files from a Git repository?

Remove ignored files:

(.DS_Store)

$ find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How to define custom configuration variables in rails

In Rails 3.0.5, the following approach worked for me:

In config/environments/development.rb, write

config.custom_config_key = :config_value

The value custom_config_key can then be referenced from other files using

Rails.application.config.custom_config_key

How do I add an integer value with javascript (jquery) to a value that's returning a string?

Your code should like this:

<span id="replies">8</span>

var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);

Hacks N Tricks

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

It's an encoding problem. You have to set the correct encoding in the HTML head via meta tag:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Replace "ISO-8859-1" with whatever your encoding is (e.g. 'UTF-8'). You must find out what encoding your HTML files are. If you're on an Unix system, just type file file.html and it should show you the encoding. If this is not possible, you should be able to find out somewhere what encoding your editor produces.

PHP Fatal error: Call to undefined function json_decode()

Using Ubuntu?

Short answer:

sudo apt-get install php7.2-json

(or php7.1-json or php5-json depending on the PHP version you're running)

Then of course make sure you restart Apache:

sudo service apache2 restart

Or if you are using PHP-FPM:

sudo service php7.2-fpm restart

(Or php7.1-fpm or php5-fpm)

Explanation

Debian has removed the previous JSON extension as of PHP 5.5rc2 due to a license conflict.

The JSON license has a clause which states:

The Software shall be used for Good, not Evil.

This causes a problem with Free Software Foundation's definition of free software which states:

The freedom to run the program, for any purpose (freedom 0).

FSF goes on to specifically list the JSON license as nonfree.

Yes it seems a bit silly. Nevertheless Debian has removed the non-compliant JSON extension, and instead offered a replacement extension that is functionally equivalent.

To be clear: PHP itself has NOT removed JSON, it's still in master. This is a distro / package manager issue.

Rasmus makes it pretty clear:

We have not removed json and we will never release a version of php without json support built in. Any changes in 5.5 is due to whatever distro packaging you are using which we have no control over.

More details

http://iteration99.com/2013/php-json-licensing-and-php-5-5/

http://liorkaplan.wordpress.com/2013/06/01/bye-bye-non-free-php-json-extension/

https://bugs.php.net/bug.php?id=63520

http://philsturgeon.co.uk/blog/2013/08/fud-cracker-php-55-never-lost-json-support

Entity Framework is Too Slow. What are my options?

I have found the answer by @Slauma here very useful for speeding things up. I used the same sort of pattern for both inserts and updates - and performance rocketed.

Setting and getting localStorage with jQuery

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.

Sample using .text()

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// alert the value to check if we got it
alert(localStorage.getItem('test'));

JSFiddle: https://jsfiddle.net/f3zLa3zc/


Storing the HTML itself

// get html
var html = $('#test')[0].outerHTML;

// set localstorage
localStorage.setItem('htmltest', html);

// test if it works
alert(localStorage.getItem('htmltest'));

JSFiddle:
https://jsfiddle.net/psfL82q3/1/


Update on user comment

A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.

// get the text
var text = $('#test').text();

// set the item in localStorage
localStorage.setItem('test', text);

// bind text to 'blur' event for div
$('#test').on('blur', function() {

    // check the new text
    var newText = $(this).text();

    // overwrite the old text
    localStorage.setItem('test', newText);

    // test if it works
    alert(localStorage.getItem('test'));

});

If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.

JSFiddle:
https://jsfiddle.net/g1b8m1fc/

Visual Studio 2010 - recommended extensions

Quick Open File for Visual Studio 2010 - free. Simulates the feature known to Eclipse users as Open Resource. This plugin gives Visual Studio equivalently quick method for opening any solution file.

VS10x Editor View Enhancer - free beta. Type and member definitions emphasizing, end-of-block details, clickable hotspots (C# and VB documents)

How to randomize (shuffle) a JavaScript array?

Randomly either push or unshift(add in the beginning).

['a', 'b', 'c', 'd'].reduce((acc, el) => {
  Math.random() > 0.5 ? acc.push(el) : acc.unshift(el);
  return acc;
}, []);

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Disable back button in android

You can do this simple way Don't call super.onBackPressed()

Note:- Don't do this unless and until you have strong reason to do it.

@Override
public void onBackPressed() {
// super.onBackPressed();
// Not calling **super**, disables back button in current screen.
}

Get url parameters from a string in .NET

Use .NET Reflector to view the FillFromString method of System.Web.HttpValueCollection. That gives you the code that ASP.NET is using to fill the Request.QueryString collection.

Division of integers in Java

As your output results a double you should cast either completed variable or total variable or both to double while dividing.

So, the correct implmentation will be:

System.out.println((double)completed/total);

How to stop a looping thread in Python?

I had a different approach. I've sub-classed a Thread class and in the constructor I've created an Event object. Then I've written custom join() method, which first sets this event and then calls a parent's version of itself.

Here is my class, I'm using for serial port communication in wxPython app:

import wx, threading, serial, Events, Queue

class PumpThread(threading.Thread):

    def __init__ (self, port, queue, parent):
        super(PumpThread, self).__init__()
        self.port = port
        self.queue = queue
        self.parent = parent

        self.serial = serial.Serial()
        self.serial.port = self.port
        self.serial.timeout = 0.5
        self.serial.baudrate = 9600
        self.serial.parity = 'N'

        self.stopRequest = threading.Event()

    def run (self):
        try:
            self.serial.open()
        except Exception, ex:
            print ("[ERROR]\tUnable to open port {}".format(self.port))
            print ("[ERROR]\t{}\n\n{}".format(ex.message, ex.traceback))
            self.stopRequest.set()
        else:
            print ("[INFO]\tListening port {}".format(self.port))
            self.serial.write("FLOW?\r")

        while not self.stopRequest.isSet():
            msg = ''
            if not self.queue.empty():
                try:
                    command = self.queue.get()
                    self.serial.write(command)
                except Queue.Empty:
                    continue

            while self.serial.inWaiting():
                char = self.serial.read(1)
                if '\r' in char and len(msg) > 1:
                    char = ''
                    #~ print('[DATA]\t{}'.format(msg))
                    event = Events.PumpDataEvent(Events.SERIALRX, wx.ID_ANY, msg)
                    wx.PostEvent(self.parent, event)
                    msg = ''
                    break
                msg += char
        self.serial.close()

    def join (self, timeout=None):
        self.stopRequest.set()
        super(PumpThread, self).join(timeout)

    def SetPort (self, serial):
        self.serial = serial

    def Write (self, msg):
        if self.serial.is_open:
            self.queue.put(msg)
        else:
            print("[ERROR]\tPort {} is not open!".format(self.port))

    def Stop(self):
        if self.isAlive():
            self.join()

The Queue is used for sending messages to the port and main loop takes responses back. I've used no serial.readline() method, because of different end-line char, and I have found the usage of io classes to be too much fuss.

Make an Installation program for C# applications and include .NET Framework installer into the setup

Use Visual Studio Setup project. Setup project can automatically include .NET framework setup in your installation package:

Here is my step-by-step for windows forms application:

  1. Create setup project. You can use Setup Wizard.

    enter image description here

  2. Select project type.

    enter image description here

  3. Select output.

    enter image description here

  4. Hit Finish.

  5. Open setup project properties.

    enter image description here

  6. Chose to include .NET framework.

    enter image description here

  7. Build setup project

  8. Check output

    enter image description here


Note: The Visual Studio Installer projects are no longer pre-packed with Visual Studio. However, in Visual Studio 2013 you can download them by using:

Tools > Extensions and Updates > Online (search) > Visual Studio Installer Projects

Is it possible to CONTINUE a loop from an exception?

For this example you really should just use an outer join.

declare
begin
  FOR attr_rec IN ( 
    select attr 
    from USER_TABLE u 
    left outer join attribute_table a 
    on ( u.USERTYPE = 'X' and a.user_id = u.id ) 
  ) LOOP
    <process records> 
    <if primary key of attribute_table is null 
     then the attribute does not exist for this user.>
  END LOOP;
END;

Why must wait() always be in synchronized block

What is the potential damage if it was possible to invoke wait() outside a synchronized block, retaining it's semantics - suspending the caller thread?

Let's illustrate what issues we would run into if wait() could be called outside of a synchronized block with a concrete example.

Suppose we were to implement a blocking queue (I know, there is already one in the API :)

A first attempt (without synchronization) could look something along the lines below

class BlockingQueue {
    Queue<String> buffer = new LinkedList<String>();

    public void give(String data) {
        buffer.add(data);
        notify();                   // Since someone may be waiting in take!
    }

    public String take() throws InterruptedException {
        while (buffer.isEmpty())    // don't use "if" due to spurious wakeups.
            wait();
        return buffer.remove();
    }
}

This is what could potentially happen:

  1. A consumer thread calls take() and sees that the buffer.isEmpty().

  2. Before the consumer thread goes on to call wait(), a producer thread comes along and invokes a full give(), that is, buffer.add(data); notify();

  3. The consumer thread will now call wait() (and miss the notify() that was just called).

  4. If unlucky, the producer thread won't produce more give() as a result of the fact that the consumer thread never wakes up, and we have a dead-lock.

Once you understand the issue, the solution is obvious: Use synchronized to make sure notify is never called between isEmpty and wait.

Without going into details: This synchronization issue is universal. As Michael Borgwardt points out, wait/notify is all about communication between threads, so you'll always end up with a race condition similar to the one described above. This is why the "only wait inside synchronized" rule is enforced.


A paragraph from the link posted by @Willie summarizes it quite well:

You need an absolute guarantee that the waiter and the notifier agree about the state of the predicate. The waiter checks the state of the predicate at some point slightly BEFORE it goes to sleep, but it depends for correctness on the predicate being true WHEN it goes to sleep. There's a period of vulnerability between those two events, which can break the program.

The predicate that the producer and consumer need to agree upon is in the above example buffer.isEmpty(). And the agreement is resolved by ensuring that the wait and notify are performed in synchronized blocks.


This post has been rewritten as an article here: Java: Why wait must be called in a synchronized block

How to set a header for a HTTP GET request, and trigger file download?

Pure jQuery.

$.ajax({
  type: "GET",
  url: "https://example.com/file",
  headers: {
    'Authorization': 'Bearer eyJraWQiFUDA.......TZxX1MGDGyg'
  },
  xhrFields: {
    responseType: 'blob'
  },
  success: function (blob) {
    var windowUrl = window.URL || window.webkitURL;
    var url = windowUrl.createObjectURL(blob);
    var anchor = document.createElement('a');
    anchor.href = url;
    anchor.download = 'filename.zip';
    anchor.click();
    anchor.parentNode.removeChild(anchor);
    windowUrl.revokeObjectURL(url);
  },
  error: function (error) {
    console.log(error);
  }
});

How to change the order of DataFrame columns?

You could also do something like this:

df = df[['mean', '0', '1', '2', '3']]

You can get the list of columns with:

cols = list(df.columns.values)

The output will produce:

['0', '1', '2', '3', 'mean']

...which is then easy to rearrange manually before dropping it into the first function

Difference between == and === in JavaScript

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false

regular expression to match exactly 5 digits

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.

Try this...

var str = 'f 34 545 323 12345 54321 123456',
    matches = str.match(/\b\d{5}\b/g);

console.log(matches); // ["12345", "54321"]

jsFiddle.

The word boundary \b is your friend here.

Update

My regex will get a number like this 12345, but not like a12345. The other answers provide great regexes if you require the latter.

Animate visibility modes, GONE and VISIBLE

Well there is a very easy way, but just setting android:animateLayoutChanges="true" will not work. You need to enableTransitionType in you activity. Check this link for more info: http://www.thecodecity.com/2018/03/android-animation-on-view-visibility.html

.NET Core vs Mono

In a nutshell:

Mono = Compiler for C#

Mono Develop = Compiler+IDE

.Net Core = ASP Compiler

Current case for .Net Core is web only as soon as it adopts some open winform standard and wider language adoption, it could finally be the Microsoft killer dev powerhouse. Considering Oracle's recent Java licensing move, Microsoft have a huge time to shine.

How to convert IPython notebooks to PDF and HTML?

I find that the easiest method to convert a notebook which is on the web to pdf is to first view it on the web service nbviewer. You can then print it to a pdf file. If the notebook is on your local drive, then upload it to a github repository first and use its url for nbviewer.

Getting coordinates of marker in Google Maps API

Also, you can display current position by "drag" listener and write it to visible or hidden field. You may also need to store zoom. Here's copy&paste from working tool:

            function map_init() {
            var lt=48.451778;
            var lg=31.646305;

            var myLatlng = new google.maps.LatLng(lt,lg);
            var mapOptions = {
                center: new google.maps.LatLng(lt,lg),
                zoom: 6,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('map'),mapOptions);   
            var marker = new google.maps.Marker({
                position:myLatlng,
                map:map,
                draggable:true
            });

            google.maps.event.addListener(
                marker,
                'drag',
                function() {
                    document.getElementById('lat1').innerHTML = marker.position.lat().toFixed(6);
                    document.getElementById('lng1').innerHTML = marker.position.lng().toFixed(6);
                    document.getElementById('zoom').innerHTML = mapObject.getZoom();

                    // Dynamically show it somewhere if needed
                    $(".x").text(marker.position.lat().toFixed(6));
                    $(".y").text(marker.position.lng().toFixed(6));
                    $(".z").text(map.getZoom());

                }
            );                  
            }

Relative Paths in Javascript in an external file

I found this to work for me.

    <script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +     
    window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>

between script tags of course... (I'm not sure why the script tags didn't show up in this post)...

disable horizontal scroll on mobile web

Try this code,overflow will help to remove scrollbar.You can use it also for any div which is scrolling.

html, body {
   overflow-x: hidden;
 }
body {
   width:100%;
 }

java.util.Date and getYear()

        try{ 
int year = Integer.parseInt(new Date().toString().split("-")[0]); 
} 
catch(NumberFormatException e){
}

Much of Date is deprecated.

Initializing a two dimensional std::vector

The general syntax, as depicted already is:

std::vector<std::vector<int> > v (A_NUMBER, std::vector <int> (OTHER_NUMBER, DEFAULT_VALUE))  

Here, the vector 'v' can be visualised as a two dimensional array, with 'A_NUMBER' of rows, with 'OTHER_NUMBER' of columns with their initial value set to 'DEFAULT_VALUE'.

Also it can be written like this:

std::vector <int> line(OTHER_NUMBER, DEFAULT_VALUE)
std::vector<std::vector<int> > v(A_NUMBER, line)

Inputting values in a 2-D vector is similar to inputting values in a 2-D array:

for(int i = 0; i < A_NUMBER; i++) {
     for(int j = 0; j < OTHER_NUMBER; j++) {
         std::cin >> v[i][j]
     }
}

Examples have already been stated in other answers....!

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

i've mandained some similar page (classic asp...)

my approach was to use Q promise directly on the popup.

For example my problem was that the popup i wanted to print close itself too fast ... and the print previw was empty, i solved this way :

Caller :

var popup = window.open("index.asp","popupwindow","width=800,height=500,left=200,top=5,scrollbars,toolbar=0,resizable");

Popup (at the end of the page):

<script src="/Scripts/jquery-1.9.1.min.js"></script>
<script src="/Scripts/q.min.js"></script>
<script type="text/javascript">
    Q(window.print()).then(function () {window.close();});
</script>

I think that your "parent lock" could be solved in a similar way

i would try :

var w = whatever;
Q(
  // fill your popup
).then(function () {
 w.print();
}).then(function () {
 w.close();
}); 

that makes "the print" and "the close" async... so the parent will be immediately "unlocked"

How to delete rows in tables that contain foreign keys to other tables

From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is

DELETE FROM MainTable
WHERE PrimaryKey = ???

You database engine will take care of deleting the corresponding referencing records.

How to Get XML Node from XDocument

The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
                    where xml2.Element("ID").Value == variable
                    select xml2).FirstOrDefault();

This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.

Marc

How to shrink/purge ibdata1 file in MySQL

In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:

  • dump all you databases
  • uninstall mysql-server,
  • add in remained my.cnf:
    [mysqld]
    innodb_file_per_table=1
  • erase all in /var/lib/mysql
  • install mysql-server
  • restore users and databases

Installing Bower on Ubuntu

Ubuntu 16.04 and later

Bower is a package manager primarily for (but not limited to) front-end web development. In Ubuntu 16.04 and later Bower package manager can be quickly and easily installed from the Ubuntu Software app. Open Ubuntu Software, search for "bower" and click the Install button to install it. In all currently supported versions of Ubuntu open the terminal and type:

sudo snap install bower --classic

enter image description here

Javascript array sort and unique

O[N^2] solutions are bad, especially when the data is already sorted, there is no need to do two nested loops for removing duplicates. One loop and comparing to the previous element will work great.

A simple solution with O[] of sort() would suffice. My solution is:

function sortUnique(arr, compareFunction) {
  let sorted = arr.sort(compareFunction);
  let result = sorted.filter(compareFunction
    ? function(val, i, a) { return (i == 0 || compareFunction(a[i-1], val) != 0); }
    : function(val, i, a) { return (i == 0 || a[i-1] !== val); }
  );
  return result;
}

BTW, can do something like this to have Array.sortUnique() method:

Array.prototype.sortUnique = function(compareFunction) {return sortUnique(this, compareFunction); }

Furthermore, sort() could be modified to remove second element if compare() function returns 0 (equal elements), though that code can become messy (need to revise loop boundaries in the flight). Besides, I stay away from making my own sort() functions in interpreted languages, since it will most certainly degrade the performance. So this addition is for the ECMA 2019+ consideration.

Calculate AUC in R?

I usually use the function ROC from the DiagnosisMed package. I like the graph it produces. AUC is returned along with it's confidence interval and it is also mentioned on the graph.

ROC(classLabels,scores,Full=TRUE)

How to read a CSV file into a .NET Datatable

I use a library called ExcelDataReader, you can find it on NuGet. Be sure to install both ExcelDataReader and the ExcelDataReader.DataSet extension (the latter provides the required AsDataSet method referenced below).

I encapsulated everything in one function, you can copy it in your code directly. Give it a path to CSV file, it gets you a dataset with one table.

public static DataSet GetDataSet(string filepath)
{
   var stream = File.OpenRead(filepath);

   try
   {
       var reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration()
       {
           LeaveOpen = false
       });

       var result = reader.AsDataSet(new ExcelDataSetConfiguration()
       {
           // Gets or sets a value indicating whether to set the DataColumn.DataType 
           // property in a second pass.
           UseColumnDataType = true,

           // Gets or sets a callback to determine whether to include the current sheet
           // in the DataSet. Called once per sheet before ConfigureDataTable.
           FilterSheet = (tableReader, sheetIndex) => true,

           // Gets or sets a callback to obtain configuration options for a DataTable. 
           ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
           {
               // Gets or sets a value indicating the prefix of generated column names.
               EmptyColumnNamePrefix = "Column",

               // Gets or sets a value indicating whether to use a row from the 
               // data as column names.
               UseHeaderRow = true,

               // Gets or sets a callback to determine which row is the header row. 
               // Only called when UseHeaderRow = true.
               ReadHeaderRow = (rowReader) =>
               {
                   // F.ex skip the first row and use the 2nd row as column headers:
                   //rowReader.Read();
               },

               // Gets or sets a callback to determine whether to include the 
               // current row in the DataTable.
               FilterRow = (rowReader) =>
               {
                   return true;
               },

               // Gets or sets a callback to determine whether to include the specific
               // column in the DataTable. Called once per column after reading the 
               // headers.
               FilterColumn = (rowReader, columnIndex) =>
               {
                   return true;
               }
           }
       });

       return result;
   }
   catch (Exception ex)
   {
       return null;
   }
   finally
   {
       stream.Close();
       stream.Dispose();
   }
}

Specify multiple attribute selectors in CSS

For concatenating it's:

input[name="Sex"][value="M"] {}

And for taking union it's:

input[name="Sex"], input[value="M"] {}

Parsing JSON using C

Jsmn is quite minimalistic and has only two functions to work with.

https://github.com/zserge/jsmn

Print JSON parsed object?

The following code will display complete json data in alert box

var data= '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

json = JSON.parse(data);
window.alert(JSON.stringify(json));

Regular expression to match characters at beginning of line only

(?i)^[ \r\n]*CTR

(?i) -- case insensitive -- Remove if case sensitive.
[ \r\n]  -- ignore space and new lines
* -- 0 or more times the same
CTR - your starts with string.

Cannot use string offset as an array in php

The error occurs when:

$a = array(); 
$a['text1'] = array();
$a['text1']['text2'] = 'sometext';

Then

echo $a['text1']['text2'];     //Error!!

Solution

$b = $a['text1'];
echo $b['text2'];    // prints: sometext

..

Best way to check if object exists in Entity Framework?

I know this is a very old thread but just incase someone like myself needs this solution but in VB.NET here's what I used base on the answers above.

Private Function ValidateUniquePayroll(PropertyToCheck As String) As Boolean
    // Return true if Username is Unique
    Dim rtnValue = False
    Dim context = New CPMModel.CPMEntities
    If (context.Employees.Any()) Then ' Check if there are "any" records in the Employee table
        Dim employee = From c In context.Employees Select c.PayrollNumber ' Select just the PayrollNumber column to work with
        For Each item As Object In employee ' Loop through each employee in the Employees entity
            If (item = PropertyToCheck) Then ' Check if PayrollNumber in current row matches PropertyToCheck
                // Found a match, throw exception and return False
                rtnValue = False
                Exit For
            Else
                // No matches, return True (Unique)
                rtnValue = True
            End If
        Next
    Else
        // The is currently no employees in the person entity so return True (Unqiue)
        rtnValue = True
    End If
    Return rtnValue
End Function

How do I read / convert an InputStream into a String in Java?

Taking into account file one should first get a java.io.Reader instance. This can then be read and added to a StringBuilder (we don't need StringBuffer if we are not accessing it in multiple threads, and StringBuilder is faster). The trick here is that we work in blocks, and as such don't need other buffering streams. The block size is parameterized for run-time performance optimization.

public static String slurp(final InputStream is, final int bufferSize) {
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    try (Reader in = new InputStreamReader(is, "UTF-8")) {
        for (;;) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
    }
    catch (UnsupportedEncodingException ex) {
        /* ... */
    }
    catch (IOException ex) {
        /* ... */
    }
    return out.toString();
}

What is the best way to implement nested dictionaries?

I used to use this function. its safe, quick, easily maintainable.

def deep_get(dictionary, keys, default=None):
    return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)

Example :

>>> from functools import reduce
>>> def deep_get(dictionary, keys, default=None):
...     return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
...
>>> person = {'person':{'name':{'first':'John'}}}
>>> print (deep_get(person, "person.name.first"))
John
>>> print (deep_get(person, "person.name.lastname"))
None
>>> print (deep_get(person, "person.name.lastname", default="No lastname"))
No lastname
>>>

Run PowerShell scripts on remote PC

Can you try the following?

psexec \\server cmd /c "echo . | powershell script.ps1"

Given a starting and ending indices, how can I copy part of a string in C?

Just use memcpy.

If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.

strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

Adding to a vector of pair

Read the following documentation:

http://cplusplus.com/reference/std/utility/make_pair/

or

http://en.cppreference.com/w/cpp/utility/pair/make_pair

I think that will help. Those sites are good resources for C++, though the latter seems to be the preferred reference these days.

Web-scraping JavaScript page with Python

You'll want to use urllib, requests, beautifulSoup and selenium web driver in your script for different parts of the page, (to name a few).
Sometimes you'll get what you need with just one of these modules.
Sometimes you'll need two, three, or all of these modules.
Sometimes you'll need to switch off the js on your browser.
Sometimes you'll need header info in your script.
No websites can be scraped the same way and no website can be scraped in the same way forever without having to modify your crawler, usually after a few months. But they can all be scraped! Where there's a will there's a way for sure.
If you need scraped data continuously into the future just scrape everything you need and store it in .dat files with pickle.
Just keep searching how to try what with these modules and copying and pasting your errors into the Google.

How to write data to a text file without overwriting the current data

Best thing is

File.AppendAllText("c:\\file.txt","Your Text");

Python regular expressions return true/false

Ignacio Vazquez-Abrams is correct. But to elaborate, re.match() will return either None, which evaluates to False, or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.

How to implement swipe gestures for mobile devices?

There is also an AngularJS module called angular-gestures which is based on hammer.js: https://github.com/wzr1337/angular-gestures

Using C# to check if string contains a string in string array

Try:

String[] val = { "helloword1", "orange", "grape", "pear" };
String sep = "";
string stringToCheck = "word1";

bool match = String.Join(sep,val).Contains(stringToCheck);
bool anothermatch = val.Any(s => s.Contains(stringToCheck));

PHP: Possible to automatically get all POSTed data?

Sure. Just walk through the $_POST array:

foreach ($_POST as $key => $value) {
    echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
}

How big can a MySQL database get before performance starts to degrade

I'm currently managing a MySQL database on Amazon's cloud infrastructure that has grown to 160 GB. Query performance is fine. What has become a nightmare is backups, restores, adding slaves, or anything else that deals with the whole dataset, or even DDL on large tables. Getting a clean import of a dump file has become problematic. In order to make the process stable enough to automate, various choices needed to be made to prioritize stability over performance. If we ever had to recover from a disaster using a SQL backup, we'd be down for days.

Horizontally scaling SQL is also pretty painful, and in most cases leads to using it in ways you probably did not intend when you chose to put your data in SQL in the first place. Shards, read slaves, multi-master, et al, they are all really shitty solutions that add complexity to everything you ever do with the DB, and not one of them solves the problem; only mitigates it in some ways. I would strongly suggest looking at moving some of your data out of MySQL (or really any SQL) when you start approaching a dataset of a size where these types of things become an issue.

Update: a few years later, and our dataset has grown to about 800 GiB. In addition, we have a single table which is 200+ GiB and a few others in the 50-100 GiB range. Everything I said before holds. It still performs just fine, but the problems of running full dataset operations have become worse.

Volatile Vs Atomic

The volatile keyword is used:

  • to make non atomic 64-bit operations atomic: long and double. (all other, primitive accesses are already guaranteed to be atomic!)
  • to make variable updates guaranteed to be seen by other threads + visibility effects: after writing to a volatile variable, all the variables that where visible before writing that variable become visible to another thread after reading the same volatile variable (happen-before ordering).

The java.util.concurrent.atomic.* classes are, according to the java docs:

A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:

boolean compareAndSet(expectedValue, updateValue);

The atomic classes are built around the atomic compareAndSet(...) function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile variables do. (with one exception: weakCompareAndSet(...)).

From the java docs:

When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.

To your question:

Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).

What is the difference between AtomicInteger and volatile int?

AtomicInteger provides atomic operations on an int with proper synchronization (eg. incrementAndGet(), getAndAdd(...), ...), volatile int will just ensure the visibility of the int to other threads.

Alternating Row Colors in Bootstrap 3 - No Table

You can use this code :

.row :nth-child(odd){
  background-color:red;
}
.row :nth-child(even){
  background-color:green;
}

Demo : http://codepen.io/mouhammed/pen/rblsC

Calculate difference between two dates (number of days)?

In case someone wants numer of whole days as a double (a, b of type DateTime):

 (a.Date - b.Date).TotalDays

Distinct by property of class with LINQ

You can't effectively use Distinct on a collection of objects (without additional work). I will explain why.

The documentation says:

It uses the default equality comparer, Default, to compare values.

For objects that means it uses the default equation method to compare objects (source). That is on their hash code. And since your objects don't implement the GetHashCode() and Equals methods, it will check on the reference of the object, which are not distinct.

MySQL Trigger - Storing a SELECT in a variable

You can declare local variables in MySQL triggers, with the DECLARE syntax.

Here's an example:

DROP TABLE IF EXISTS foo;
CREATE TABLE FOO (
  i SERIAL PRIMARY KEY
);

DELIMITER //
DROP TRIGGER IF EXISTS bar //

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = NEW.i;
  SET @a = x; -- set user variable outside trigger
END//

DELIMITER ;

SET @a = 0;

SELECT @a; -- returns 0

INSERT INTO foo () VALUES ();

SELECT @a; -- returns 1, the value it got during the trigger

When you assign a value to a variable, you must ensure that the query returns only a single value, not a set of rows or a set of columns. For instance, if your query returns a single value in practice, it's okay but as soon as it returns more than one row, you get "ERROR 1242: Subquery returns more than 1 row".

You can use LIMIT or MAX() to make sure that the local variable is set to a single value.

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT age FROM users WHERE name = 'Bill'); 
  -- ERROR 1242 if more than one row with 'Bill'
END//

CREATE TRIGGER bar AFTER INSERT ON foo
FOR EACH ROW BEGIN
  DECLARE x INT;
  SET x = (SELECT MAX(age) FROM users WHERE name = 'Bill');
  -- OK even when more than one row with 'Bill'
END//

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

Docker command can't connect to Docker daemon

After install everything and start the service, try close your terminal and open it again, then try pull your image

Edit

I also had this issue again, if the solution above won't worked, try this solution that is the command bellow

sudo mv /var/lib/docker/network/files/ /tmp/dn-bak

Considerations

If command above works you probably are with network docker problems, anyway this resolves it, to confirm that, see the log with the command bellow

tail -5f /var/log/upstart/docker.log

If the output have something like that

FATA[0000] Error starting daemon: Error initializing network controller: could not delete the default bridge network: network bridge has active endpoints 
/var/run/docker.sock is up

You really are with network problems, however I do not know yet if the next time you restart(update, 2 months no issue again) your OS will get this problem again and if it is a bug or installation problem

My docker version

Client:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   a34a1d5
 Built:        Fri Nov 20 13:12:04 UTC 2015
 OS/Arch:      linux/amd64

Server:
 Version:      1.9.1
 API version:  1.21
 Go version:   go1.4.2
 Git commit:   a34a1d5
 Built:        Fri Nov 20 13:12:04 UTC 2015
 OS/Arch:      linux/amd64

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Not OP's answer but as this was the first question that popped up for me in google, Id also like to add that users searching for this might need to reseed their table, which was the case for me

DBCC CHECKIDENT(tablename)

Crop image in android

I found a really cool library, try this out. this is really smooth and easy to use.

https://github.com/TakuSemba/CropMe

Execute a file with arguments in Python shell

runfile('abc.py', ['arg1', 'arg2'])

/etc/apt/sources.list" E212: Can't open file for writing

change the permission for the other user for that type setfacl -m u:username:rw filename

How to set standard encoding in Visual Studio

I don't know of a global setting nither but you can try this:

  1. Save all Visual Studio templates in UTF-8
  2. Write a Visual Studio Macro/Addin that will listen to the DocumentSaved event and will save the file in UTF-8 format (if not already).
  3. Put a proxy on your source control that will make sure that new files are always UTF-8.

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

To add to what others posted:

ExecuteScalar conceptually returns the leftmost column from the first row of the resultset from the query; you could ExecuteScalar a SELECT * FROM staff, but you'd only get the first cell of the resulting rows Typically used for queries that return a single value. I'm not 100% sure about SQLServer but in Oracle, you wouldnt use it to run a FUNCTION (a database code that returns a single value) and expect it to give you the return value of the function even though functions return single values.. However, if youre running the function as part of a query, e.g. SELECT SUBSTR('abc', 1, 1) FROM DUAL then it would give the return value by virtue of the fact that the return value is stored in the top leftmost cell of the resulting rowset

ExecuteNonQuery would be used to run database stored procedures, functions and queries that modify data (INSERT/UPDATE/DELETE) or modify database structure (CREATE TABLE...). Typically the return value of the call is an indication of how many rows were affected by the operation but check the DB documentation to guarantee this

Only get hash value using md5sum (without filename)

Well, I had the same problem today, but trying to get file md5 hash when running the find command. I got the most voted question and wrapped it in a function called md5 to run in find command. The mission for me was calculate hash for all files in an folder and output it as hash:filename.

md5() { md5sum $1 | awk '{ printf "%s",$1 }'; }
export -f md5
find -type f -exec bash -c 'md5 "$0"' {} \; -exec echo -n ':' \; -print

So, I'd got some pieces from here and also from find -exec a shell function?

How to create PDFs in an Android app?

A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.

Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.

Swift - Split string over multiple lines

Swift:

@connor is the right answer, but if you want to add lines in a print statement what you are looking for is \n and/or \r, these are called Escape Sequences or Escaped Characters, this is a link to Apple documentation on the topic..

Example:

print("First line\nSecond Line\rThirdLine...")

How do I make CMake output into a 'bin' dir?

Regardless of whether I define this in the main CMakeLists.txt or in the individual ones, it still assumes I want all the libs and bins off the main path, which is the least useful assumption of all.

WPF Data Binding and Validation Rules Best Practices

I think the new preferred way might be to use IDataErrorInfo

Read more here

Fixed header, footer with scrollable content

It works fine for me using a CSS grid. Initially fix the container and then give overflow-y: auto; for the centre content which has to get scrolled i.e other than header and footer.

_x000D_
_x000D_
.container{
  height: 100%;
  left: 0;
  position: fixed;
  top: 0;
  width: 100%;
  display: grid;
  grid-template-rows: 5em auto 3em;
}

header{
   grid-row: 1;  
    background-color: rgb(148, 142, 142);
    justify-self: center;
    align-self: center;
    width: 100%;
}

.body{
  grid-row: 2;
  overflow-y: auto;
}

footer{
   grid-row: 3;
   
    background: rgb(110, 112, 112);
}
_x000D_
<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
    <footer><h3>Footer</h3></footer>
</div>
_x000D_
_x000D_
_x000D_

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

1:Go to: Tools > Options > Projects and Solutions > Web Projects > Use the 64 bit version of IIS Express 2: change below setting for web service project. enter image description here

Defining a variable with or without export

Although not explicitly mentioned in the discussion, it is NOT necessary to use export when spawning a subshell from inside bash since all the variables are copied into the child process.

Android Studio doesn't see device

Env - AS 3.3.2 Linux 4 (ubuntu)

in AS used menu Tools > Create desktop entry 

Desktop file content - ( note the path does NOT include Platform-tools )

[Desktop Entry]
Encoding=UTF-8
Version=1.0
Type=Application
Name=Android Studio
Icon=jetbrains-studio.png
Path=/home/rob/android-studio
Exec=sh -c ' /home/rob/android-studio/bin/studio.sh' 
StartupNotify=false
StartupWMClass=jetbrains-studio
OnlyShowIn=Unity;
X-UnityGenerated=true

Note that the location of SDK.platform-tools 'adb' below will not be found by desktop.PATH above:

 $ which adb
/usr/local/src/android-sdk-linux/platform-tools/adb

On my setup, my symptom was that any terminal would list the device OK but the toolbar button in AS would never show a connected device... "no devices" is all i would ever see when my phone was connected via USB cable.

SOLUTION for me was adding the correct PATH near the top of the file:

 ${AS_HOME}/bin/studio.sh ...

PATH=$PATH:/usr/local/src/android-sdk-linux/platform-tools:/usr/local/src/android-sdk-linux/tools

What is the difference between char * const and const char *?

I would like to point out that using int const * (or const int *) isn't about a pointer pointing to a const int variable, but that this variable is const for this specific pointer.

For example:

int var = 10;
int const * _p = &var;

The code above compiles perfectly fine. _p points to a const variable, although var itself isn't constant.

unable to start mongodb local server

You already have a process running. You can kill it with the command :

killall mongod

Spaces cause split in path with PowerShell

Using Powershell on Windows10 in 2018, what worked for me was simply to replace double quotes " by simple quotes '. Adding the backtick before the space, as suggested in an answer, broke the path.

jQuery click event not working after adding class

.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax

$(document).on('click', "a.tabclick", function() {

This syntax will work for delegated events

.on()

JTable - Selected Row click event

Here's how I did it:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

This code reacts on mouse click and item selection from keyboard.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

Custom seekbar (thumb size, color and background)

At first courtesy goes to @Charuka .

DO

You can use android:progressDrawable="@drawable/seekbar" instead of android:background="@drawable/seekbar" .

progressDrawable used for the progress mode.

You should try with

android:minHeight

Defines the minimum height of the view. It is not guaranteed the view will be able to achieve this minimum height (for example, if its parent layout constrains it with less available height).

android:minWidth

Defines the minimum width of the view. It is not guaranteed the view will be able to achieve this minimum width (for example, if its parent layout constrains it with less available width)

    android:minHeight="25p"
    android:maxHeight="25dp" 

FYI:

Using android:minHeight and android:maxHeight is not good solutions .Need to rectify your Custom Seekbar (From Class Level) .

How do I get the result of a command in a variable in windows?

If you're looking for the solution provided in Using the result of a command as an argument in bash?

then here is the code:

@echo off
if not "%1"=="" goto get_basename_pwd
for /f "delims=X" %%i in ('cd') do call %0 %%i
for /f "delims=X" %%i in ('dir /o:d /b') do echo %%i>>%filename%.txt
goto end

:get_basename_pwd
set filename=%~n1

:end
  • This will call itself with the result of the CD command, same as pwd.
  • String extraction on parameters will return the filename/folder.
  • Get the contents of this folder and append to the filename.txt

[Credits]: Thanks to all the other answers and some digging on the Windows XP commands page.

Cell Style Alignment on a range

Based on this comment from the OP, "I found the problem. apparentlyworksheet.Cells[y + 1, x + 1].HorizontalAlignment", I believe the real explanation is that all the cells start off sharing the same Style object. So if you change that style object, it changes all the cells that use it. But if you just change the cell's alignment property directly, only that cell is affected.

Get just the filename from a path in a Bash script

Most UNIX-like operating systems have a basename executable for a very similar purpose (and dirname for the path):

pax> a=/tmp/file.txt
pax> b=$(basename $a)
pax> echo $b
file.txt

That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.

So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.

One way to do that (and this is a bash-only solution, needing no other executables):

pax> a=/tmp/xx/file.tar.gz
pax> xpath=${a%/*} 
pax> xbase=${a##*/}
pax> xfext=${xbase##*.}
pax> xpref=${xbase%.*}
pax> echo;echo path=${xpath};echo pref=${xpref};echo ext=${xfext}

path=/tmp/xx
pref=file.tar
ext=gz

That little snippet sets xpath (the file path), xpref (the file prefix, what you were specifically asking for) and xfext (the file extension).

SQL query to find Nth highest salary from a salary table

Try this solution.

select SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(DISTINCT salary ORDER BY salary DESC),',',3),',',-1) from employees

How to capture a JFrame's close button click event?

Override windowClosing Method.

public void windowClosing(WindowEvent e)

It is invoked when a window is in the process of being closed. The close operation can be overridden at this point.

How to remove \n from a list element?

This works to take out the \n (new line) off a item in a list it just takes the first item in string off

def remove_end(s):
    templist=[]
    for i in s:
        templist.append(i)
    return(templist[0])

How to append text to a text file in C++?

You need to specify the append open mode like

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
  outfile << "Data"; 
  return 0;
}

How can I add to a List's first position?

Of course, Insert or AddFirst will do the trick, but you could always do:

myList.Reverse();
myList.Add(item);
myList.Reverse();

Bootstrap: adding gaps between divs

I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>

How do I truly reset every setting in Visual Studio 2012?

Executing the command: Devenv.exe /ResetSettings like :

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>devenv.exe /ResetSettings , resolved my issue :D

For more: https://msdn.microsoft.com/en-us/library/ms241273.aspx