Programs & Examples On #Offline browsing

0

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

How do I use spaces in the Command Prompt?

set "CMD=C:\Program Files (x86)\PDFtk\bin\pdftk"
echo cmd /K ""%CMD%" %D% output trimmed.pdf"
start cmd /K ""%CMD%" %D% output trimmed.pdf"

this worked for me in a batch file

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

Create table variable in MySQL

TO answer your question: no, MySQL does not support Table-typed variables in the same manner that SQL Server (http://msdn.microsoft.com/en-us/library/ms188927.aspx) provides. Oracle provides similar functionality but calls them Cursor types instead of table types (http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems012.htm).

Depending your needs you can simulate table/cursor-typed variables in MySQL using temporary tables in a manner similar to what is provided by both Oracle and SQL Server.

However, there is an important difference between the temporary table approach and the table/cursor-typed variable approach and it has a lot of performance implications (this is the reason why Oracle and SQL Server provide this functionality over and above what is provided with temporary tables).

Specifically: table/cursor-typed variables allow the client to collate multiple rows of data on the client side and send them up to the server as input to a stored procedure or prepared statement. What this eliminates is the overhead of sending up each individual row and instead pay that overhead once for a batch of rows. This can have a significant impact on overall performance when you are trying to import larger quantities of data.

A possible work-around:

What you may want to try is creating a temporary table and then using a LOAD DATA (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) command to stream the data into the temporary table. You could then pass them name of the temporary table into your stored procedure. This will still result in two calls to the database server, but if you are moving enough rows there may be a savings there. Of course, this is really only beneficial if you are doing some kind of logic inside the stored procedure as you update the target table. If not, you may just want to LOAD DATA directly into the target table.

How to Retrieve value from JTextField in Java Swing?

Just use event.getSource() frim within actionPerformed

Cast it to the component

for Ex, if you need combobox

JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();

use appropriate api to get the value,

for Ex.

Object selected = comboBox.getSelectedItem();  etc.

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

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

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

For example, turning

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

into (C)

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

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.

When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.

Is " " a replacement of " "?

Those do both mean non-breaking space, yes.   is another synonym, in hex.

How to create an Excel File with Nodejs?

You should check ExcelJS

Works with CSV and XLSX formats.

Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:

app.get('/some/route', function(req, res) {
  res.writeHead(200, {
    'Content-Disposition': 'attachment; filename="file.xlsx"',
    'Transfer-Encoding': 'chunked',
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
  var worksheet = workbook.addWorksheet('some-worksheet')
  worksheet.addRow(['foo', 'bar']).commit()
  worksheet.commit()
  workbook.commit()
}

Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)

See also this SO answer.

What is managed or unmanaged code in programming?

Managed Code:
Code that runs under a "contract of cooperation" with the common language runtime. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.

Un-Managed Code:
Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).

Reference: http://www.dotnetspider.com/forum/11612-difference-between-managed-and-unmanaged-code.aspx

Concatenate two slices in Go

append( ) function and spread operator

Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation. So we need to use ...

package main

import (
    "fmt"
)

func main() {
    x := []int{1, 2, 3}
    y := []int{4, 5, 6}
    z := append([]int{}, append(x, y...)...)
    fmt.Println(z)
}

output of the above code is: [1 2 3 4 5 6]

Getting list of parameter names inside python function

import inspect

def func(a,b,c=5):
    pass

inspect.getargspec(func)  # inspect.signature(func) in Python 3

(['a', 'b', 'c'], None, None, (5,))

Executing periodic actions in Python

If you meant to run foo() inside a python script every 10 seconds, you can do something on these lines.

import time

def foo():
    print "Howdy"

while True:
    foo()
    time.sleep(10)

How to detect the end of loading of UITableView

Using private API:

@objc func tableViewDidFinishReload(_ tableView: UITableView) {
    print(#function)
    cellsAreLoaded = true
}

Using public API:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // cancel the perform request if there is another section
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tableViewDidLoadRows:) object:tableView];

    // create a perform request to call the didLoadRows method on the next event loop.
    [self performSelector:@selector(tableViewDidLoadRows:) withObject:tableView afterDelay:0];

    return [self.myDataSource numberOfRowsInSection:section];
}

// called after the rows in the last section is loaded
-(void)tableViewDidLoadRows:(UITableView*)tableView{
    self.cellsAreLoaded = YES;
}

A possible better design is to add the visible cells to a set, then when you need to check if the table is loaded you can instead do a for loop around this set, e.g.

var visibleCells = Set<UITableViewCell>()

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.insert(cell)
}

override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.remove(cell)
}

// example property you want to show on a cell that you only want to update the cell after the table is loaded. cellForRow also calls configure too for the initial state.
var count = 5 {
    didSet {
        for cell in visibleCells {
            configureCell(cell)
        }
    }
}

How to parse freeform street/postal address out of text, and into components

UPDATE: Geocode.xyz now works worldwide. For examples see https://geocode.xyz

For USA, Mexico and Canada, see geocoder.ca.

For example:

Input: something going on near the intersection of main and arthur kill rd new york

Output:

<geodata>
  <latt>40.5123510000</latt>
  <longt>-74.2500500000</longt>
  <AreaCode>347,718</AreaCode>
  <TimeZone>America/New_York</TimeZone>
  <standard>
    <street1>main</street1>
    <street2>arthur kill</street2>
    <stnumber/>
    <staddress/>
    <city>STATEN ISLAND</city>
    <prov>NY</prov>
    <postal>11385</postal>
    <confidence>0.9</confidence>
  </standard>
</geodata>

You may also check the results in the web interface or get output as Json or Jsonp. eg. I'm looking for restaurants around 123 Main Street, New York

How to print a debug log?

You can use:

<?php
echo '<script>console.log("debug log")</script>';
?>

header('HTTP/1.0 404 Not Found'); not doing anything

No, it probably is actually working. It's just not readily visible. Instead of just using the header call, try doing that, then including 404.php, and then calling die.

You can test the fact that the HTTP/1.0 404 Not Found works by creating a PHP file named, say, test.php with this content:

<?php

header("HTTP/1.0 404 Not Found");
echo "PHP continues.\n";
die();
echo "Not after a die, however.\n";

Then viewing the result with curl -D /dev/stdout reveals:

HTTP/1.0 404 Not Found
Date: Mon, 04 Apr 2011 03:39:06 GMT
Server: Apache
X-Powered-By: PHP/5.3.2
Content-Length: 14
Connection: close
Content-Type: text/html

PHP continues.

How to fix date format in ASP .NET BoundField (DataFormatString)?

Formatting depends on the server's culture setting. If you use en-US culture, you can use Short Date Pattern like {0:d}

For example, it formats 6/15/2009 1:45:30 to 6/15/2009

You can check more formats from BoundField.DataFormatString

How do I check if a number is positive or negative in C#?

The Math.Sign method is one way to go. It will return -1 for negative numbers, 1 for positive numbers, and 0 for values equal to zero (i.e. zero has no sign). Double and single precision variables will cause an exception (ArithmeticException) to be thrown if they equal NaN.

creating a random number using MYSQL

This should give what you want:

FLOOR(RAND() * 401) + 100

Generically, FLOOR(RAND() * (<max> - <min> + 1)) + <min> generates a number between <min> and <max> inclusive.

Update

This full statement should work:

SELECT name, address, FLOOR(RAND() * 401) + 100 AS `random_number` 
FROM users

How can I remove non-ASCII characters but leave periods and spaces using Python?

Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.

Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?

Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:

this is line 1
this is line 2

the result would be 'this is line 1this is line 2' ... is that what you really want?

A greater solution would include:

  1. a better name for the filter function than onlyascii
  2. recognition that a filter function merely needs to return a truthy value if the argument is to be retained:

    def filter_func(char):
        return char == '\n' or 32 <= ord(char) <= 126
    # and later:
    filtered_data = filter(filter_func, data).lower()
    

What does 'corrupted double-linked list' mean

For anyone who is looking for solutions here, I had a similar issue with C++: malloc(): smallbin double linked list corrupted:

This was due to a function not returning a value it was supposed to.

std::vector<Object> generateStuff(std::vector<Object>& target> {
  std::vector<Object> returnValue;
  editStuff(target);
  // RETURN MISSING
}

Don't know why this was able to compile after all. Probably there was a warning about it.

How to add border around linear layout except at the bottom?

Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.

Here is a quick sample code for you to see how easy it is, but you will find more information on the link.

<com.khandelwal.library.view.BorderFrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:leftBorderColor="#00F0F0"
            app:leftBorderWidth="10dp"
            app:topBorderColor="#F0F000"
            app:topBorderWidth="15dp"
            app:rightBorderColor="#F000F0"
            app:rightBorderWidth="20dp"
            app:bottomBorderColor="#000000"
            app:bottomBorderWidth="25dp" >
    </com.khandelwal.library.view.BorderFrameLayout>

So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.

And no, I'm neither the author of this library nor one of his friend ;-)

How to create a DB link between two oracle instances

as a simple example:

CREATE DATABASE LINK _dblink_name_
  CONNECT TO _username_
    IDENTIFIED BY _passwd_
      USING '$_ORACLE_SID_'

for more info: http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm

Open Redis port for remote connections

For me, I needed to do the following:

1- Comment out bind 127.0.0.1

2- Change protected-mode to no

3- Protect my server with iptables (https://www.digitalocean.com/community/tutorials/how-to-implement-a-basic-firewall-template-with-iptables-on-ubuntu-14-04)

How can I get the baseurl of site?

The popular GetLeftPart solution is not supported in the PCL version of Uri, unfortunately. GetComponents is, however, so if you need portability, this should do the trick:

uri.GetComponents(
    UriComponents.SchemeAndServer | UriComponents.UserInfo, UriFormat.Unescaped);

Annotations from javax.validation.constraints not working

in my case i had a custom class-level constraint that was not being called.

@CustomValidation // not called
public class MyClass {
    @Lob
    @Column(nullable = false)
    private String name;
}

as soon as i added a field-level constraint to my class, either custom or standard, the class-level constraint started working.

@CustomValidation // now it works. super.
public class MyClass {
    @Lob
    @Column(nullable = false)
    @NotBlank // adding this made @CustomValidation start working
    private String name;
}

seems like buggy behavior to me but easy enough to work around i guess

jQuery SVG vs. Raphael

If you don't need VML and IE8 support then use Canvas (PaperJS for example). Look at latest IE10 demos for Windows 7. They have amazing animations in Canvas. SVG is not capable to do anything close to them. Overall Canvas is available at all mobile browsers. SVG is not working at early versions of Android 2.0- 2.3 (as I know)

Yes, Canvas is not scalable, but it so fast that you can redraw the whole canvas faster then browser capable to scroll view port.

From my perspective Microsoft's optimizations provides means to use Canvas as regular GDI engine and implement graphics applications like we do them for Windows now.

Pretty-Printing JSON with PHP

For those running PHP version 5.3 or before, you may try below:

$pretty_json = "<pre>".print_r(json_decode($json), true)."</pre>";

echo $pretty_json;

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

CKEditor instance already exists

I've had similar issue where we were making several instances of CKeditor for the content loaded via ajax.

CKEDITOR.remove()

Kept the DOM in the memory and didn't remove all the bindings.

CKEDITOR.instance[instance_id].destroy()

Gave the error i.contentWindow error whenever I create new instance with new data from ajax. But this was only until I figured out that I was destroying the instance after clearing the DOM.

Use destroy() while the instance & it's DOM is present on the page, then it works perfectly fine.

In Python, how do I loop through the dictionary and change the value if it equals something?

Comprehensions are usually faster, and this has the advantage of not editing mydict during the iteration:

mydict = dict((k, v if v else '') for k, v in mydict.items())

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

The count(*) will never raise exception because it always returns actual count or 0 - zero, no matter what. I'd use count.

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

How to vertically align <li> elements in <ul>?

I had the same problem. Try this.

<nav>
    <ul>
        <li><a href="#">AnaSayfa</a></li>
        <li><a href="#">Hakkimizda</a></li>
        <li><a href="#">Iletisim</a></li>
    </ul>
</nav>
@charset "utf-8";

nav {
    background-color: #9900CC;
    height: 80px;
    width: 400px;
}

ul {
    list-style: none;
    float: right;
    margin: 0;
}

li {
    float: left;
    width: 100px;
    line-height: 80px;
    vertical-align: middle;
    text-align: center;
    margin: 0;
}

nav li a {
    width: 100px;
    text-decoration: none;
    color: #FFFFFF;
}

The import com.google.android.gms cannot be resolved

I too had the same issue. Got it resolved by compiling with the latest sdk tool versions.(Play services,build tools etc). Sample build.gradle is shown below for reference.

    apply plugin: 'com.android.application'


android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.abc.bcd"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.android.support:appcompat-v7:23.0.1'
}

What is the meaning of curly braces?

Dictionaries in Python are data structures that store key-value pairs. You can use them like associative arrays. Curly braces are used when declaring dictionaries:

d = {'One': 1, 'Two' : 2, 'Three' : 3 }
print d['Two'] # prints "2"

Curly braces are not used to denote control levels in Python. Instead, Python uses indentation for this purpose.

I think you really need some good resources for learning Python in general. See https://stackoverflow.com/q/175001/10077

How to remove all leading zeroes in a string

I don't think preg_replace is the answer.. old thread but just happen to looking for this today. ltrim and (int) casting is the winner.

<?php
 $numString = "0000001123000";
 $actualInt = "1123000";

 $fixed_str1 = preg_replace('/000+/','',$numString);
 $fixed_str2 = ltrim($numString, '0');
 $fixed_str3 = (int)$numString;

 echo $numString . " Original";
 echo "<br>"; 
 echo $fixed_str1 . " Fix1";
 echo "<br>"; 
 echo $fixed_str2 . " Fix2";
 echo "<br>";
 echo $fixed_str3 . " Fix3";
 echo "<br>";
 echo $actualInt . " Actual integer in string";

 //output

 0000001123000 Origina
 1123 Fix1
 1123000 Fix2
 1123000 Fix3
 1123000 Actual integer in tring

How do I delete everything below row X in VBA/Excel?

Another option is Sheet1.Rows(x & ":" & Sheet1.Rows.Count).ClearContents (or .Clear). The reason you might want to use this method instead of .Delete is because any cells with dependencies in the deleted range (e.g. formulas that refer to those cells, even if empty) will end up showing #REF. This method will preserve formula references to the cleared cells.

Clicking the back button twice to exit an activity

You can also use the visibility of a Toast, so you don't need that Handler/postDelayed ultra solution.

Toast doubleBackButtonToast;

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

    doubleBackButtonToast = Toast.makeText(this, "Double tap back to exit.", Toast.LENGTH_SHORT);
}

@Override
public void onBackPressed() {
    if (doubleBackButtonToast.getView().isShown()) {
        super.onBackPressed();
    }

    doubleBackButtonToast.show();
}

Setting active profile and config location from command line in spring boot

There are two different ways you can add/override spring properties on the command line.

Option 1: Java System Properties (VM Arguments)

It's important that the -D parameters are before your application.jar otherwise they are not recognized.

java -jar -Dspring.profiles.active=prod application.jar

Option 2: Program arguments

java -jar application.jar --spring.profiles.active=prod --spring.config.location=c:\config

convert htaccess to nginx

You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :

$content = $_POST['content'];

    $lines   = explode(PHP_EOL, $content);
    $results = '';

    foreach($lines as $line)
    {
        $items = explode(' ', $line);

        $q = str_replace("^", "^/", $items[1]);

        if (substr($q, strlen($q) - 1) !== '$') $q .= '$';

        $buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';

        $results .= $buffer.PHP_EOL;
    }

    die($results);

Remove json element

You can try to delete the JSON as follows:

var bleh = {first: '1', second: '2', third:'3'}

alert(bleh.first);

delete bleh.first;

alert(bleh.first);

Alternatively, you can also pass in the index to delete an attribute:

delete bleh[1];

However, to understand some of the repercussions of using deletes, have a look here

vector vs. list in STL

One special capability of std::list is splicing (linking or moving part of or a whole list into a different list).

Or perhaps if your contents are very expensive to copy. In such a case it might be cheaper, for example, to sort the collection with a list.

Also note that if the collection is small (and the contents are not particularly expensive to copy), a vector might still outperform a list, even if you insert and erase anywhere. A list allocates each node individually, and that might be much more costly than moving a few simple objects around.

I don't think there are very hard rules. It depends on what you mostly want to do with the container, as well as on how large you expect the container to be and the contained type. A vector generally trumps a list, because it allocates its contents as a single contiguous block (it is basically a dynamically allocated array, and in most circumstances an array is the most efficient way to hold a bunch of things).

How to convert NSData to byte array in iPhone?

The signature of -[NSData bytes] is - (const void *)bytes. You can't assign a pointer to an array on the stack. If you want to copy the buffer managed by the NSData object into the array, use -[NSData getBytes:]. If you want to do it without copying, then don't allocate an array; just declare a pointer variable and let NSData manage the memory for you.

Rails has_many with alias name

If you use has_many through, and want to alias:

has_many :alias_name, through: model_name, source: initial_name

How to cin Space in c++?

I thought I'd share the answer that worked for me. The previous line ended in a newline, so most of these answers by themselves didn't work. This did:

string title;
do {
  getline(cin, title);
} while (title.length() < 2);

That was assuming the input is always at least 2 characters long, which worked for my situation. You could also try simply comparing it to the string "\n".

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

Write variable to a file in Ansible

An important comment from tmoschou:

As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.

For more details see this and an explanation


Original answer:

You could use the copy module, with the content parameter:

- copy: content="{{ your_json_feed }}" dest=/path/to/destination/file

The docs here: copy module

How to use multiprocessing queue in Python?

Here's a dead simple usage of multiprocessing.Queue and multiprocessing.Process that allows callers to send an "event" plus arguments to a separate process that dispatches the event to a "do_" method on the process. (Python 3.4+)

import multiprocessing as mp
import collections

Msg = collections.namedtuple('Msg', ['event', 'args'])

class BaseProcess(mp.Process):
    """A process backed by an internal queue for simple one-way message passing.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = mp.Queue()

    def send(self, event, *args):
        """Puts the event and args as a `Msg` on the queue
        """
       msg = Msg(event, args)
       self.queue.put(msg)

    def dispatch(self, msg):
        event, args = msg

        handler = getattr(self, "do_%s" % event, None)
        if not handler:
            raise NotImplementedError("Process has no handler for [%s]" % event)

        handler(*args)

    def run(self):
        while True:
            msg = self.queue.get()
            self.dispatch(msg)

Usage:

class MyProcess(BaseProcess):
    def do_helloworld(self, arg1, arg2):
        print(arg1, arg2)

if __name__ == "__main__":
    process = MyProcess()
    process.start()
    process.send('helloworld', 'hello', 'world')

The send happens in the parent process, the do_* happens in the child process.

I left out any exception handling that would obviously interrupt the run loop and exit the child process. You can also customize it by overriding run to control blocking or whatever else.

This is really only useful in situations where you have a single worker process, but I think it's a relevant answer to this question to demonstrate a common scenario with a little more object-orientation.

How does the modulus operator work?

Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2

for same thing C++ has modulus operator ('%')

Basic code for explanation

#include <iostream>
using namespace std;


int main()
{
    int num = 11;
    cout << "remainder is " << (num % 3) << endl;

    return 0;
}

Which will display

remainder is 2

Make git automatically remove trailing whitespace before committing

This doesn't remove whitespace automatically before a commit, but it is pretty easy to effect. I put the following perl script in a file named git-wsf (git whitespace fix) in a dir in $PATH so I can:

git wsf | sh

and it removes all whitespace only from lines of files that git reports as a diff.

#! /bin/sh
git diff --check | perl -x $0
exit

#! /usr/bin/perl

use strict;

my %stuff;
while (<>) {
    if (/trailing whitespace./) {
        my ($file,$line) = split(/:/);
        push @{$stuff{$file}},$line;
    }
}

while (my ($file, $line) = each %stuff) {
    printf "ex %s <<EOT\n", $file;
    for (@$line) {
        printf '%ds/ *$//'."\n", $_;
    }
    print "wq\nEOT\n";
}

Clear the entire history stack and start a new activity on Android

Try below code,

Intent intent = new Intent(ManageProfileActivity.this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TASK| 
                Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Unknown version of Tomcat was specified in Eclipse

This happened to me because Tomcat was still in the process of downloading (Download and Install). The message disappeared after a few minutes.

The eclipse window should really have some type of progress indicator showing download status.

Best Java obfuscator?

I think that Proguard is the best. It is also possible to integrate it with your IDE (for example NetBeans). However, consider that if you obfuscate your code it could be difficult to track problems in your logs..

How to call function on child component on parent events

A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from parent.

_x000D_
_x000D_
var Child = {_x000D_
  template: '<div>{{value}}</div>',_x000D_
  data: function () {_x000D_
    return {_x000D_
      value: 0_x000D_
    };_x000D_
  },_x000D_
  methods: {_x000D_
   setValue(value) {_x000D_
     this.value = value;_x000D_
    }_x000D_
  },_x000D_
  created() {_x000D_
    this.$emit('handler', this.setValue);_x000D_
  }_x000D_
}_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  components: {_x000D_
    'my-component': Child_x000D_
  },_x000D_
  methods: {_x000D_
   setValueHandler(fn) {_x000D_
     this.setter = fn_x000D_
    },_x000D_
    click() {_x000D_
     this.setter(70)_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <my-component @handler="setValueHandler"></my-component>_x000D_
  <button @click="click">Click</button>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

The parent keeps track of the child handler functions and calls whenever necessary.

Handling urllib2's timeout? - Python

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

Check if url contains string with JQuery

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf("?added-to-cart=555") > -1) {
    alert("found it");
}

How to test if a DataSet is empty?

If I understand correctly, this should work for you

if (ds.Tables[0].Rows.Count == 0)
{
    //
}

How to trim a file extension from a String in JavaScript?

Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';

    yourStr = yourStr.slice(0, -4); // 'test'

Laravel - Model Class not found

I was having the same "Class [class name] not found" error message, but it wasn't a namespace issue. All my namespaces were set up correctly. I even tried composer dump-autoload and it didn't help me.

Surprisingly (to me) I then did composer dump-autoload -o which according to Composer's help, "optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production." Somehow doing it that way got composer to behave and include the class correctly in the autoload_classmap.php file.

Calling ASP.NET MVC Action Methods from JavaScript

Javascript Function

function AddToCart(id) {
 $.ajax({
   url: '@Url.Action("AddToCart", "ControllerName")',
   type: 'GET',
   dataType: 'json',
   cache: false,
   data: { 'id': id },
   success: function (results) {
        alert(results)
   },
   error: function () {
    alert('Error occured');
   }
   });
   }

Controller Method to call

[HttpGet]
  public JsonResult AddToCart(string id)
  {
    string newId = id;
     return Json(newId, JsonRequestBehavior.AllowGet);
  }

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

LINQ - Left Join, Group By, and Count

Consider using a subquery:

from p in context.ParentTable 
let cCount =
(
  from c in context.ChildTable
  where p.ParentId == c.ChildParentId
  select c
).Count()
select new { ParentId = p.Key, Count = cCount } ;

If the query types are connected by an association, this simplifies to:

from p in context.ParentTable 
let cCount = p.Children.Count()
select new { ParentId = p.Key, Count = cCount } ;

Check time difference in Javascript

I have done some enhancements for timer counter

//example return : 01:23:02:02
//               : 1 Day 01:23:02:02
//               : 2 Days 01:23:02:02 


function get_timeDifference(strtdatetime) {
    var datetime = new Date(strtdatetime).getTime();
    var now = new Date().getTime();

    if (isNaN(datetime)) {
        return "";
    }

    //console.log(datetime + " " + now);

    if (datetime < now) {
        var milisec_diff = now - datetime;
    } else {
        var milisec_diff = datetime - now;
    }

    var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));

    var date_diff = new Date(milisec_diff);





    var msec = milisec_diff;
    var hh = Math.floor(msec / 1000 / 60 / 60);
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);
    msec -= mm * 1000 * 60;
    var ss = Math.floor(msec / 1000);
    msec -= ss * 1000


    var daylabel = "";
    if (days > 0) {
        var grammar = " ";
        if (days > 1) grammar = "s " 
        var hrreset = days * 24;
        hh = hh - hrreset;
        daylabel = days + " Day" + grammar ;
    }


    //  Format Hours
    var hourtext = '00';
    hourtext = String(hh);
    if (hourtext.length == 1) { hourtext = '0' + hourtext };

    //  Format Minutes
    var mintext = '00';
    mintext = String(mm); 
    if (mintext.length == 1) { mintext = '0' + mintext };

    //  Format Seconds
    var sectext = '00';
    sectext = String(ss); 
    if (sectext.length == 1) { sectext = '0' + sectext };

    var msectext = '00';
    msectext = String(msec);
    msectext = msectext.substring(0, 1);
    if (msectext.length == 1) { msectext = '0' + msectext };

    return daylabel + hourtext + ":" + mintext + ":" + sectext + ":" + msectext;
}

jQuery: Load Modal Dialog Contents via Ajax

var dialogName = '#dialog_XYZ';
$.ajax({
        url: "/ajax_pages/my_page.ext",
        data: {....},
        success: function(data) {
          $(dialogName ).remove();

          $('BODY').append(data);

          $(dialogName )
            .dialog(options.dialogOptions);
        }
});

The Ajax-Request load the Dialog, add them to the Body of the current page and open the Dialog.

If you only whant to load the content you can do:

var dialogName = '#dialog_XYZ';
$.ajax({
            url: "/ajax_pages/my_page.ext",
            data: {....},
            success: function(data) {
              $(dialogName).append(data);

              $(dialogName )
                .dialog(options.dialogOptions);
            }
});

Why is an OPTIONS request sent and can I disable it?

Yes it's possible to avoid options request. Options request is a preflight request when you send (post) any data to another domain. It's a browser security issue. But we can use another technology: iframe transport layer. I strongly recommend you forget about any CORS configuration and use readymade solution and it will work anywhere.

Take a look here: https://github.com/jpillora/xdomain

And working example: http://jpillora.com/xdomain/

CSS root directory

/Images/myImage.png

this has to be in root of your domain/subdomain

http://website.to/Images/myImage.png

and it will work

However, I think it would work like this, too

  • images
    • yourimage.png
  • styles
    • style.css

style.css:

body{
    background: url(../images/yourimage.png);
}

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

How to update/upgrade a package using pip?

import subprocess as sbp
import pip
pkgs = eval(str(sbp.run("pip3 list -o --format=json", shell=True,
                         stdout=sbp.PIPE).stdout, encoding='utf-8'))
for pkg in pkgs:
    sbp.run("pip3 install --upgrade " + pkg['name'], shell=True)

Save as xx.py
Then run Python3 xx.py
Environment: python3.5+ pip10.0+

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

How to read the output from git diff?

The default output format (which originally comes from a program known as diff if you want to look for more info) is known as a “unified diff”. It contains essentially 4 different types of lines:

  • context lines, which start with a single space,
  • insertion lines that show a line that has been inserted, which start with a +,
  • deletion lines, which start with a -, and
  • metadata lines which describe higher level things like which file this is talking about, what options were used to generate the diff, whether the file changed its permissions, etc.

I advise that you practice reading diffs between two versions of a file where you know exactly what you changed. Like that you'll recognize just what is going on when you see it.

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

AngularJS not detecting Access-Control-Allow-Origin header?

It can also happen when your parameters are wrong in the request. In my case I was working with a API that sent me the message

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401."

when I send wrong username or password with the POST request to login.

Get checkbox list values with jQuery

var aArray = [];
window.$( "#myDiv" ).find( "input[type=checkbox][checked]" ).each( function()
{
  aArray.push( this.name );

});

You can put it in a function and execute on click of the button.

Array.push() and unique items

Yep, it's a small mistake.

if(this.items.indexOf(item) === -1) {
    this.items.push(item);
    console.log(this.items);
}

Java: How to set Precision for double value?

To set precision for double values DecimalFormat is good technique. To use this class import java.text.DecimalFormat and create object of it for example

double no=12.786;
DecimalFormat dec = new DecimalFormat("#0.00");
System.out.println(dec.format(no));

So it will print two digits after decimal point here it will print 12.79

How to change the color of an svg element?

If you want to do this to an inline svg that is, for example, a background image in your css:

_x000D_
_x000D_
background: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='rgba(31,159,215,1)' viewBox='...'/%3E%3C/svg%3E");
_x000D_
_x000D_
_x000D_

of course, replace the ... with your inline image code

running a command as a super user from a python script

I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for more information.

What we are doing here is echoing the password and then using pipe we pass it on to the sudo through '-S' argument.

#!/usr/bin/env python
import subprocess

sudo_password = 'mysecretpass'
command = 'apach2ctl restart'
command = command.split()

cmd1 = subprocess.Popen(['echo',sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)

output = cmd2.stdout.read().decode() 

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

Looking at the JDK, innermost constructor for Calendar.getInstance() has this:

public GregorianCalendar(TimeZone zone, Locale aLocale) {
    super(zone, aLocale);
    gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
    setTimeInMillis(System.currentTimeMillis());
}

so it already automatically does what you suggest. Date's default constructor holds this:

public Date() {
    this(System.currentTimeMillis());
}

So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend joda-time to use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot.

Split pandas dataframe in two if it has more than 10 rows

I used a List Comprehension to cut a huge DataFrame into blocks of 100'000:

size = 100000
list_of_dfs = [df.loc[i:i+size-1,:] for i in range(0, len(df),size)]

or as generator:

list_of_dfs = (df.loc[i:i+size-1,:] for i in range(0, len(df),size))

How can I append a string to an existing field in MySQL?

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Handling errors in Promise.all

You would need to know how to identify an error in your results. If you do not have a standard expected error, I suggest that you run a transformation on each error in the catch block that makes it identifiable in your results.

try {
  let resArray = await Promise.all(
    state.routes.map(route => route.handler.promiseHandler().catch(e => e))
  );

  // in catch(e => e) you can transform your error to a type or object
  // that makes it easier for you to identify whats an error in resArray
  // e.g. if you expect your err objects to have e.type, you can filter
  // all errors in the array eg
  // let errResponse = resArray.filter(d => d && d.type === '<expected type>')
  // let notNullResponse = resArray.filter(d => d)

  } catch (err) {
    // code related errors
  }

What does "collect2: error: ld returned 1 exit status" mean?

In your situation you got a reference to the missing symbols. But in some situations, ld will not provide error information.

If you want to expand the information provided by ld, just add the following parameters to your $(LDFLAGS)

-Wl,-V

Eclipse java debugging: source not found

When running in debug mode, click Edit Source Lookup after suspended from thread. At this point, we should be able to add the necessary project/jar which contains your source code. After I added my current project in this way, and it solved my problem. Thanks

bundle install returns "Could not locate Gemfile"

You must be in the same directory of Gemfile

How can I escape a double quote inside double quotes?

Use a backslash:

echo "\""     # Prints one " character.

javascript find and remove object in array based on key value

Array.prototype.removeAt = function(id) {
    for (var item in this) {
        if (this[item].id == id) {
            this.splice(item, 1);
            return true;
        }
    }
    return false;
}

This should do the trick, jsfiddle

Hide all warnings in ipython

I hide the warnings in the pink boxes by running the following code in a cell:

from IPython.display import HTML
HTML('''<script>
code_show_err=false; 
function code_toggle_err() {
 if (code_show_err){
 $('div.output_stderr').hide();
 } else {
 $('div.output_stderr').show();
 }
 code_show_err = !code_show_err
} 
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')

How to dynamically create a class?

Runtime Code Generation with JVM and CLR - Peter Sestoft

Work for persons that are really interested in this type of programming.

My tip for You is that if You declare something try to avoid string, so if You have class Field it is better to use class System.Type to store the field type than a string. And for the sake of best solutions instead of creation new classes try to use those that has been created FiledInfo instead of creation new.

How to load URL in UIWebView in Swift?

In Swift 3 you can do it like this:

@IBOutlet weak var webview: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Web view load
    let url = URL (string: "http://www.example.com/")
    let request = URLRequest(url: url!)
    webview.loadRequest(request)
}

Remember to add permission at Info.plist, add the following values:

Info.plist

Intersection and union of ArrayLists in Java

After testing, here is my best intersection approach.

Faster speed compared to pure HashSet Approach. HashSet and HashMap below has similar performance for arrays with more than 1 million records.

As for Java 8 Stream approach, speed is quite slow for array size larger then 10k.

Hope this can help.

public static List<String> hashMapIntersection(List<String> target, List<String> support) {
    List<String> r = new ArrayList<String>();
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String s : support) {
        map.put(s, 0);
    }
    for (String s : target) {
        if (map.containsKey(s)) {
            r.add(s);
        }
    }
    return r;
}
public static List<String> hashSetIntersection(List<String> a, List<String> b) {
    Long start = System.currentTimeMillis();

    List<String> r = new ArrayList<String>();
    Set<String> set = new HashSet<String>(b);

    for (String s : a) {
        if (set.contains(s)) {
            r.add(s);
        }
    }
    print("intersection:" + r.size() + "-" + String.valueOf(System.currentTimeMillis() - start));
    return r;
}

public static void union(List<String> a, List<String> b) {
    Long start = System.currentTimeMillis();
    Set<String> r= new HashSet<String>(a);
    r.addAll(b);
    print("union:" + r.size() + "-" + String.valueOf(System.currentTimeMillis() - start));
}

Case vs If Else If: Which is more efficient?

It seems that the compiler is better in optimizing a switch-statement than an if-statement.

The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.

Here's a small comparison:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

What is apache's maximum url length?

The default limit for the length of the request line is 8190 bytes (see LimitRequestLine directive). And if we subtract three bytes for the request method (i.e. GET), eight bytes for the version information (i.e. HTTP/1.0/HTTP/1.1) and two bytes for the separating space, we end up with 8177 bytes for the URI path plus query.

How to prevent going back to the previous activity?

I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.

Here are a few links that might help:

Disable back button in android

  MyActivity.java =>
    @Override
    public void onBackPressed() {

       return;
    }

How can I disable 'go back' to some activity?

  AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

how to set "camera position" for 3d plots using python/matplotlib?

Minimal example varying azim, dist and elev

To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

Here is my test program:

#!/usr/bin/env python3

import sys

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

if len(sys.argv) > 1:
    azim = int(sys.argv[1])
else:
    azim = None
if len(sys.argv) > 2:
    dist = int(sys.argv[2])
else:
    dist = None
if len(sys.argv) > 3:
    elev = int(sys.argv[3])
else:
    elev = None

# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

if azim is not None:
    ax.azim = azim
if dist is not None:
    ax.dist = dist
if elev is not None:
    ax.elev = elev

print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))

plt.savefig(
    'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
    format='png',
    bbox_inches='tight'
)

Running it without arguments gives the default values:

ax.azim = -60
ax.dist = 10
ax.elev = 30

main_-60_10_30.png

enter image description here

Vary azim

The azimuth is the rotation around the z axis e.g.:

  • 0 means "looking from +x"
  • 90 means "looking from +y"

main_-60_10_30.png

enter image description here

main_0_10_30.png

enter image description here

main_60_10_30.png

enter image description here

Vary dist

dist seems to be the distance from the center visible point in data coordinates.

main_-60_10_30.png

enter image description here

main_-60_5_30.png

enter image description here

main_-60_20_-30.png

enter image description here

Vary elev

From this we understand that elev is the angle between the eye and the xy plane.

main_-60_10_60.png

enter image description here

main_-60_10_30.png

enter image description here

main_-60_10_0.png

enter image description here

main_-60_10_-30.png

enter image description here

Tested on matpotlib==3.2.2.

Check whether a variable is a string in Ruby

foo.instance_of? String

or

foo.kind_of? String 

if you you only care if it is derrived from String somewhere up its inheritance chain

Get a pixel from HTML Canvas?

Yup, check out getImageData(). Here's an example of breaking CAPTCHA with JavaScript using canvas:

OCR and Neural Nets in JavaScript

Accessing a value in a tuple that is in a list

a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

For boot2docker, we can set it on /var/lib/boot2docker/profile, for instance:

ulimit -n 2018

Be warned not to set this limit too high as it will slow down apt-get! See bug #1332440. I had it with debian jessie.

How do I update a Tomcat webapp without restarting the entire service?

Have you tried to use Tomcat's Manager application? It allows you to undeploy / deploy war files with out shutting Tomcat down.

If you don't want to use the Manager application, you can also delete the war file from the webapps directory, Tomcat will undeploy the application after a short period of time. You can then copy a war file back into the directory, and Tomcat will deploy the war file.

If you are running Tomcat on Windows, you may need to configure your Context to not lock various files.

If you absolutely can't have any downtime, you may want to look at Tomcat 7's Parallel deployments You may deploy multiple versions of a web application with the same context path at the same time. The rules used to match requests to a context version are as follows:

  • If no session information is present in the request, use the latest version.
  • If session information is present in the request, check the session manager of each version for a matching session and if one is found, use that version.
  • If session information is present in the request but no matching session can be found, use the latest version.

What is the difference between GitHub and gist?

“Gists are actually Git repositories, which means that you can fork or clone any gist, even if you aren't the original author. You can also view a gist's full commit history, including diffs.”

? check out the official github documentation

So the key difference is, that they are single files.

Oh, and: gists can be “secret” (as in: private url) also without being a paying github customer, if I understand correctly...

How to get form values in Symfony2 controller

None of the above worked for me. This works for me:

$username = $form["username"]->getData();
$password = $form["password"]->getData();

I hope it helps.

Python return statement error " 'return' outside function"

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

Border for an Image view in Android?

Indented border

Add the following code to a shape:

<gradient
    android:angle="135"
    android:endColor="#FF444444"
    android:centerColor="#FFAAAAAA"
    android:startColor="#FFFFFFFF"/>

ét voila, you've got a (more or less) indented border, with the light source set to left-top. Fiddle with the size of the bitmap (in relation to the size of the imageview, I used a 200dp x 200dp imageview and a bitmap of 196dp x 196dp in the example, with a radius of 14dp for the corners) and the padding to get the best result. Switch end and startcolor for a bevelled effect.

Here's the full code of the shape you see in the image (save it in res/drawable, e.g. border_shape.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="135"
        android:endColor="#FF444444"
        android:centerColor="#FFAAAAAA"
        android:startColor="#FFFFFFFF"/>
    <padding
        android:top="2dp"
        android:left="2dp"
        android:right="2dp"
        android:bottom="2dp"/>
    <corners
        android:radius="30dp"/>
</shape>

And call it in your imageview like this:

android:scaleType="center"    
android:background="@drawable/border_shape"
android:cropToPadding="true"
android:adjustViewBounds="true"

And here is the code for the bitmap with rounded corners:

Bitmap getRoundedRectBitmap(Bitmap bitmap, float radius) {
    Paint paint = new Paint();
    PorterDuffXfermode pdmode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    Bitmap bm = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bm);
    Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    RectF rectF = new RectF(rect);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(0xff424242);
    canvas.drawRoundRect(rectF, radius, radius, paint);
    paint.setXfermode(pdmode);
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return bm;
}

How to see if an object is an array without using reflection?

You can use instanceof.

JLS 15.20.2 Type Comparison Operator instanceof

 RelationalExpression:
    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

That means you can do something like this:

Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"        

You'd have to check if the object is an instanceof boolean[], byte[], short[], char[], int[], long[], float[], double[], or Object[], if you want to detect all array types.

Also, an int[][] is an instanceof Object[], so depending on how you want to handle nested arrays, it can get complicated.

For the toString, java.util.Arrays has a toString(int[]) and other overloads you can use. It also has deepToString(Object[]) for nested arrays.

public String toString(Object arr) {
   if (arr instanceof int[]) {
      return Arrays.toString((int[]) arr);
   } else //...
}

It's going to be very repetitive (but even java.util.Arrays is very repetitive), but that's the way it is in Java with arrays.

See also

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

1.3.1 fixed it.

Just update your extension and you should be good to go

Common sources of unterminated string literal

If you've done any cut/paste: some online syntax highlighters will mangle single and double quotes, turning them into formatted quote pairs (matched opening and closing pairs). (tho i can't find any examples right now)... So that entails hitting Command-+ a few times and staring at your quote characters

Try a different font? also, different editors and IDEs use different tokenizers and highlight rules, and JS is one of more dynamic languages to parse, so try opening the file in emacs, vim, gedit (with JS plugins)... If you get lucky, one of them will show a long purple string running through the end of file.

How to add a search box with icon to the navbar in Bootstrap 3?

I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form need to be added an attribute width.

<form role="search" style="width: 15em; margin: 0.3em 2em;">
    <div class="input-group">
        <input type="text" class="form-control" placeholder="Search">
        <div class="input-group-btn">
            <button type="submit" class="btn btn-default">
                <span class="glyphicon glyphicon-search"></span>
            </button>
        </div>
    </div>
</form> 

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

Change image onmouseover

Try something like this:

HTML:

<img src='/folder/image1.jpg' id='imageid'/>

jQuery: ?

$('#imageid').hover(function() {
  $(this).attr('src', '/folder/image2.jpg');
}, function() {
  $(this).attr('src', '/folder/image1.jpg');
});

EDIT: (After OP HTML posted)

HTML:

<a href="#" id="name">
    <img title="Hello" src="/ico/view.png"/>
</a>

jQuery:

$('#name img').hover(function() {
  $(this).attr('src', '/ico/view1.png');
}, function() {
  $(this).attr('src', '/ico/view.png');
});

Emulator: ERROR: x86 emulation currently requires hardware acceleration

I had the same issue. In my case I found two issues causing the problem

  1. I had Hyper-V running, I think if any Virtualization programs running you need to uninstall
  2. I was running under Standard Account / Not Administrator

Python dictionary get multiple values

As I see no similar answer here - it is worth pointing out that with the usage of a (list / generator) comprehension, you can unpack those multiple values and assign them to multiple variables in a single line of code:

first_val, second_val = (myDict.get(key) for key in [first_key, second_key])

Inserting into Oracle and retrieving the generated sequence ID

There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:

insert into table(batch_id, ...) values(my_sequence.nextval, ...)

...to return the next number. To find out the last created sequence nr (in your session), you would use:

my_sequence.currval

This site has several complete examples on how to use sequences.

How to automatically indent source code?

I have tried both ways, and from the Edit|Advanced menu, and they are not doing anything to my source code. Other options like line indent are working. What could be wrong? – Chucky Jul 12 '13 at 11:06

Sometimes if it doesnt work, try to select a couple lines above and below or the whole block of code (whole function, whole cycle, whole switch, etc.), so that it knows how to indent.

Like for example if you copy/paste something into a case statement of a switch and it has wrong indentation, you need to select the text + the line with the case statement above to get it to work.

In C#, why is String a reference type that behaves like a value type?

Isn't just as simple as Strings are made up of characters arrays. I look at strings as character arrays[]. Therefore they are on the heap because the reference memory location is stored on the stack and points to the beginning of the array's memory location on the heap. The string size is not known before it is allocated ...perfect for the heap.

That is why a string is really immutable because when you change it even if it is of the same size the compiler doesn't know that and has to allocate a new array and assign characters to the positions in the array. It makes sense if you think of strings as a way that languages protect you from having to allocate memory on the fly (read C like programming)

How to recover deleted rows from SQL server table?

I think thats impossible, sorry.

Thats why whenever running a delete or update you should always use BEGIN TRANSACTION, then COMMIT if successful or ROLLBACK if not.

Download a div in a HTML page as pdf using javascript

You can do it using jsPDF

HTML:

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

JavaScript:

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});

DateDiff to output hours and minutes

this would hep you

 DECLARE @DATE1 datetime = '2014-01-22 9:07:58.923'
 DECLARE @DATE2 datetime = '2014-01-22 10:20:58.923'
 SELECT DATEDIFF(HOUR, @DATE1,@DATE2) ,
        DATEDIFF(MINUTE, @DATE1,@DATE2) - (DATEDIFF(HOUR,@DATE1,@DATE2)*60)

 SELECT CAST(DATEDIFF(HOUR, @DATE1,@DATE2) AS nvarchar(200)) +
        ':'+ CAST(DATEDIFF(MINUTE, @DATE1,@DATE2)  -
                 (DATEDIFF(HOUR,@DATE1,@DATE2)*60) AS nvarchar(200))
As TotalHours 

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Pillow is new version

PIL-1.1.7.win-amd64-py2.x installers are available at

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

How to read a file in Groovy into a string?

String fileContents = new File('/path/to/file').text

If you need to specify the character encoding, use the following instead:

String fileContents = new File('/path/to/file').getText('UTF-8')

Iterate over object keys in node.js

For simple iteration of key/values, sometimes libraries like underscorejs can be your friend.

const _ = require('underscore');

_.each(a, function (value, key) {
    // handle
});

just for reference

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

- Another Update -

Since Twitter Bootstrap version 2.0 - which saw the removal of the .container-fluid class - it has not been possible to implement a two column fixed-fluid layout using just the bootstrap classes - however I have updated my answer to include some small CSS changes that can be made in your own CSS code that will make this possible

It is possible to implement a fixed-fluid structure using the CSS found below and slightly modified HTML code taken from the Twitter Bootstrap Scaffolding : layouts documentation page:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="fixed">  <!-- we want this div to be fixed width -->
            ...
        </div>
        <div class="hero-unit filler">  <!-- we have removed spanX class -->
            ...
        </div>
    </div>
</div>

CSS

/* CSS for fixed-fluid layout */

.fixed {
    width: 150px;  /* the fixed width required */
    float: left;
}

.fixed + div {
     margin-left: 150px;  /* must match the fixed width in the .fixed class */
     overflow: hidden;
}


/* CSS to ensure sidebar and content are same height (optional) */

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
    position: relative;
}

.filler:after{
    background-color:inherit;
    bottom: 0;
    content: "";
    height: auto;
    min-height: 100%;
    left: 0;
    margin:inherit;
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

I have kept the answer below - even though the edit to support 2.0 made it a fluid-fluid solution - as it explains the concepts behind making the sidebar and content the same height (a significant part of the askers question as identified in the comments)


Important

Answer below is fluid-fluid

Update As pointed out by @JasonCapriotti in the comments, the original answer to this question (created for v1.0) did not work in Bootstrap 2.0. For this reason, I have updated the answer to support Bootstrap 2.0

To ensure that the main content fills at least 100% of the screen height, we need to set the height of the html and body to 100% and create a new css class called .fill which has a minimum-height of 100%:

html, body {
    height: 100%;
}

.fill { 
    min-height: 100%;
}

We can then add the .fill class to any element that we need to take up 100% of the sceen height. In this case we add it to the first div:

<div class="container-fluid fill">
    ...
</div>

To ensure that the Sidebar and the Content columns have the same height is very difficult and unnecessary. Instead we can use the ::after pseudo selector to add a filler element that will give the illusion that the two columns have the same height:

.filler::after {
    background-color: inherit;
    bottom: 0;
    content: "";
    right: 0;
    position: absolute;
    top: 0;
    width: inherit;
    z-index: -1;  
}

To make sure that the .filler element is positioned relatively to the .fill element we need to add position: relative to .fill:

.fill { 
    min-height: 100%;
    position: relative;
}

And finally add the .filler style to the HTML:

HTML

<div class="container-fluid fill">
    <div class="row-fluid">
        <div class="span3">
            ...
        </div>
        <div class="span9 hero-unit filler">
            ...
        </div>
    </div>
</div>

Notes

  • If you need the element on the left of the page to be the filler then you need to change right: 0 to left: 0.

git switch branch without discarding local changes

You can use :

  1. git stash to save your work
  2. git checkout <your-branch>
  3. git stash apply or git stash pop to load your last work

Git stash extremely useful when you want temporarily save undone or messy work, while you want to doing something on another branch.

git -stash documentation

How can I make visible an invisible control with jquery? (hide and show not work)

.show() and .hide() modify the css display rule. I think you want:

$(selector).css('visibility', 'hidden'); // Hide element
$(selector).css('visibility', 'visible'); // Show element

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

public static void main(String arg[])
{
    HashMap<String, ArrayList<String>> hashmap = 
        new HashMap<String, ArrayList<String>>();
    ArrayList<String> arraylist = new ArrayList<String>();
    arraylist.add("Hello");
    arraylist.add("World.");
    hashmap.put("my key", arraylist);
    arraylist = hashmap.get("not inserted");
    System.out.println(arraylist);
    arraylist = hashmap.get("my key");
    System.out.println(arraylist);
}

null
[Hello, World.]

Works fine... maybe you find your mistake in my code.

How to render an ASP.NET MVC view as a string?

Additional tip for ASP NET CORE:

Interface:

public interface IViewRenderer
{
  Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model);
}

Implementation:

public class ViewRenderer : IViewRenderer
{
  private readonly IRazorViewEngine viewEngine;

  public ViewRenderer(IRazorViewEngine viewEngine) => this.viewEngine = viewEngine;

  public async Task<string> RenderAsync<TModel>(Controller controller, string name, TModel model)
  {
    ViewEngineResult viewEngineResult = this.viewEngine.FindView(controller.ControllerContext, name, false);

    if (!viewEngineResult.Success)
    {
      throw new InvalidOperationException(string.Format("Could not find view: {0}", name));
    }

    IView view = viewEngineResult.View;
    controller.ViewData.Model = model;

    await using var writer = new StringWriter();
    var viewContext = new ViewContext(
       controller.ControllerContext,
       view,
       controller.ViewData,
       controller.TempData,
       writer,
       new HtmlHelperOptions());

       await view.RenderAsync(viewContext);

       return writer.ToString();
  }
}

Registration in Startup.cs

...
 services.AddSingleton<IViewRenderer, ViewRenderer>();
...

And usage in controller:

public MyController: Controller
{
  private readonly IViewRenderer renderer;
  public MyController(IViewRendere renderer) => this.renderer = renderer;
  public async Task<IActionResult> MyViewTest
  {
    var view = await this.renderer.RenderAsync(this, "MyView", model);
    return new OkObjectResult(view);
  }
}

Change selected value of kendo ui dropdownlist

It's possible to "natively" select by value:

dropdownlist.select(1);

MomentJS getting JavaScript Date in UTC

Or simply:

Date.now

From MDN documentation:

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970

Available since ECMAScript 5.1

It's the same as was mentioned above (new Date().getTime()), but more shortcutted version.

$(form).ajaxSubmit is not a function

I'm guessing you don't have a jquery form plugin included. ajaxSubmit isn't a core jquery function, I believe.

Something like this : http://jquery.malsup.com/form/

UPD

<script src="http://malsup.github.com/jquery.form.js"></script> 

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How to scan multiple paths using the @ComponentScan annotation?

I use:

@ComponentScan(basePackages = {"com.package1","com.package2","com.package3", "com.packagen"})

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

What are the lesser known but useful data structures?

Half edge data structure and winged edge for polygonal meshes.

Useful for computational geometry algorithms.

Number of times a particular character appears in a string

You may do this completely in-line by replacing the desired character with an empty string, calling LENGTH function and substracting from the original string's length.

SELECT 
  CustomerName, 
  LENGTH(CustomerName) -
  LENGTH(REPLACE(CustomerName, ' ', '')) AS NumberOfSpaces
FROM Customers;

How to execute Python code from within Visual Studio Code

In order to launch the current file with the respective venv, I added this to file launch.json:

 {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "pythonPath": "${workspaceFolder}/FOO/DIR/venv/bin/python3"
    },

In the bin folder resides the source .../venv/bin/activate script which is regularly sourced when running from a regular terminal.

JFrame.dispose() vs System.exit()

JFrame.dispose()

public void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

System.exit()

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

What is the difference between private and protected members of C++ classes?

private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.

You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.

How to append to the end of an empty list?

Note that you also can use insert in order to put number into the required position within list:

initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]

And also note that in python you can always get a list length using method len()

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

When to use margin vs padding in CSS

There are more technical explanations for your question, but if you want a way to think about margin and padding, this analogy might help.

Imagine block elements as picture frames hanging on a wall:

  • The photo is the content.
  • The matting is the padding.
  • The frame moulding is the border.
  • The wall is the viewport.
  • The space between two frames is the margin.

With this in mind, a good rule of thumb is to use margin when you want to space an element in relationship to other elements on the wall, and padding when you're adjusting the appearance of the element itself. Margin won't change the size of the element, but padding will make the element bigger1.


1 You can alter this behavior with the box-sizing attribute.

Remove characters from a String in Java

Java strings are immutable. But you has many options:

You can use:

The StringBuilder class instead, so you can remove everything you want and control your string.

The replace method.

And you can actually use a loop £:

How can I create a link to a local file on a locally-run web page?

If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.

http://sitename.com/virtual_folder_name/filename.fileextension

By the way, this also works with Chrome that otherwise does not accept the file-protocol file://

Hope this helps someone :)

Converting String to "Character" array in Java

another way to do it.

String str="I am a good boy";
    char[] chars=str.toCharArray();

    Character[] characters=new Character[chars.length];
    for (int i = 0; i < chars.length; i++) {
        characters[i]=chars[i];
        System.out.println(chars[i]);
    }

Escaping Double Quotes in Batch Script

As an addition to mklement0's excellent answer:

Almost all executables accept \" as an escaped ". Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal " to some process, assign \" to an environment variable, and then use that variable, whenever you need to pass a quote. Example:

SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"

Note SETLOCAL ENABLEDELAYEDEXPANSION seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON.

If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:

::region without DELAYEDEXPANSION

SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL

::region without DELAYEDEXPANSION

If you want to pass dynamic content from a variable that contains quotes that are escaped as "" you can replace "" with \" on expansion:

SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL

This replacement is not safe with %...% style expansion!

In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!" is the safe version.


If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:

Using \" from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)

To achieve this, one precedes any quote with a caret (^"), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"). ALL shell meta characters must be escaped with ^ as well, e.g. & => ^&; | => ^|; > => ^>; etc.

Example:

child ^"malicious argument\^"^&whoami^"

Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"


To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe (This is impossible if the variable can contain quotes - don't write %var:""=\"%). To achieve this, the last " before the variable and the first " after the variable are not ^-escaped. cmd-metacharacters between those two " must not be escaped. Example:

foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"

This isn't safe, if %dynamic_content% can contain unmatched quotes.

How to disable "prevent this page from creating additional dialogs"?

I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.

So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:

var countdown = 99;
function annoy(){
    if(countdown>0){
        alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
        countdown--;

        // Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
        setTimeout(function(){
            annoy();
        }, 1000);
    }
}

// Don't alert right away or Chrome will catch you
setTimeout(function(){
    annoy();
}, 1000);

Is there a real solution to debug cordova apps

You can debug Cordova Android Applications which are installed on your phone remotely from your computer via the USB cable (you can also remotely click on the web application as if you were viewing the web application from your compueter) with "Chrome Remote Debugging". You can also debug web application viewed in the Stock Android browser or Chrome on Android this way.

  1. Enable developer mode on your Android device (go to settings -> about phone -> tap 7x on the build number).

  2. Connect your computer with your phone via USB cable.

  3. Lunch Chrome on your computer and navigate to chrome://inspect and click the "Inspect" button next to the remote device which you want to debug (under the "Devices" tab). OR right click inside Chrome on your computer -> Inspect -> Costumize and control DevTools (3 vertical dots - top right corner of the developer tools) -> More tools -> Remote Devices -> under Devices on the left side, click on your device to which you are connected via USB -> click on the Inspect button for the application you want.

  4. Then click on "Console" and you can debug JavaScript the same way, as you would on a normal web application with Chrome developer tools.

Excel - programm cells to change colour based on another cell

Select ColumnB and as two CF formula rules apply:

Green: =AND(B1048576="X",B1="Y")

Red: =AND(B1048576="X",B1="W")

enter image description here

How to count the NaN values in a column in pandas DataFrame

Here is the code for counting Null values column wise :

df.isna().sum()

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

Go to

File->settings->Buil,Execution,Deployment->Instant Run->Disable it.

//now you are good to go.

Difference between Console.Read() and Console.ReadLine()?

Console.Read()

=> reads only one character from the standard input

Console.ReadLine()

=> reads all characters in the line from the standard input

The 'json' native gem requires installed build tools

I have found that the error is sometimes caused by a missing library.

so If you install RDOC first by running

gem install rdoc

then install rails with:

gem install rails

then go back and install the devtools as mentioned before with:

1) Extract DevKit to path C:\Ruby193\DevKit
2) cd C:\Ruby192\DevKit
3) ruby dk.rb init
4) ruby dk.rb review
5) ruby dk.rb install

then try installing json

which culminate with you finally being able to run

rails new project_name - without errors.

good luck

What is the difference between cache and persist?

Cache() and persist() both the methods are used to improve performance of spark computation. These methods help to save intermediate results so they can be reused in subsequent stages.

The only difference between cache() and persist() is ,using Cache technique we can save intermediate results in memory only when needed while in Persist() we can save the intermediate results in 5 storage levels(MEMORY_ONLY, MEMORY_AND_DISK, MEMORY_ONLY_SER, MEMORY_AND_DISK_SER, DISK_ONLY).

Convert Enumeration to a Set/List

You can use Collections.list() to convert an Enumeration to a List in one line:

List<T> list = Collections.list(enumeration);

There's no similar method to get a Set, however you can still do it one line:

Set<T> set = new HashSet<T>(Collections.list(enumeration));

How to unset a JavaScript variable?

If you are implicitly declaring the variable without var, the proper way would be to use delete foo.

However after you delete it, if you try to use this in an operation such as addition a ReferenceError will be thrown because you can't add a string to an undeclared, undefined identifier. Example:

x = 5;
delete x
alert('foo' + x )
// ReferenceError: x is not defined

It may be safer in some situations to assign it to false, null, or undefined so it's declared and won't throw this type of error.

foo = false

Note that in ECMAScript null, false, undefined, 0, NaN, or '' would all evaluate to false. Just make sure you dont use the !== operator but instead != when type checking for booleans and you don't want identity checking (so null would == false and false == undefined).

Also note that delete doesn't "delete" references but just properties directly on the object, e.g.:

bah = {}, foo = {}; bah.ref = foo;

delete bah.ref;
alert( [bah.ref, foo ] )
// ,[object Object] (it deleted the property but not the reference to the other object)

If you have declared a variable with var you can't delete it:

(function() {
    var x = 5;
    alert(delete x)
    // false
})();

In Rhino:

js> var x
js> delete x
false

Nor can you delete some predefined properties like Math.PI:

js> delete Math.PI
false

There are some odd exceptions to delete as with any language, if you care enough you should read:

Configuring ObjectMapper in Spring

There is org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean for a long time. Starting from 1.2 release of Spring Boot there is org.springframework.http.converter.json.Jackson2ObjectMapperBuilder for Java Config.

In String Boot configuration can be as simple as:

spring.jackson.deserialization.<feature_name>=true|false
spring.jackson.generator.<feature_name>=true|false
spring.jackson.mapper.<feature_name>=true|false
spring.jackson.parser.<feature_name>=true|false
spring.jackson.serialization.<feature_name>=true|false
spring.jackson.default-property-inclusion=always|non_null|non_absent|non_default|non_empty

in classpath:application.properties or some Java code in @Configuration class:

@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    return builder;
}

See:

MySQL Workbench Dark Theme

Edit: Advise: This answer is old and a better solution can be found in this same page. This answer referred to MySQL Workbench 6.3 and is outdated. If you are using a new version (8.0 as today) look for @VSingh comment in this very page.


Original answer:

Just a copy of Gaston's answer, but with Monokai theme colors.

<!-- 
    dark-gray:         #282828;
    brown-gray:        #49483E;
    gray:              #888888;
    light-gray:        #CCCCCC;
    ghost-white:       #F8F8F0;
    light-ghost-white: #F8F8F2;
    yellow:            #E6DB74;
    blue:              #66D9EF;
    pink:              #F92672;
    purple:            #AE81FF;
    brown:             #75715E;
    orange:            #FD971F;
    light-orange:      #FFD569;
    green:             #A6E22E;
    sea-green:         #529B2F; 
-->
<style id="32" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- STYLE_DEFAULT       !BACKGROUND!   -->
<style id="33" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- STYLE_LINENUMBER                   -->
<style id= "0" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DEFAULT                  -->
<style id= "1" fore-color="#999999" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id= "2" fore-color="#999999" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id= "3" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id= "4" fore-color="#66D9EF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id= "5" fore-color="#66D9EF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id= "6" fore-color="#AE81FF" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id= "7" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id= "8" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id= "9" fore-color="#9B859D" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="10" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="11" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="12" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="13" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="14" fore-color="#F92672" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="15" fore-color="#9B859D" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="16" fore-color="#DDDDDD" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="17" fore-color="#E6DB74" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="18" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="19" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="20" fore-color="#529B2F" back-color="#282828" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="21" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="22" fore-color="#909090" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->
<!-- All styles again in their variant in a hidden command -->
<style id="65" fore-color="#999999" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENT                  -->
<style id="66" fore-color="#999999" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_COMMENTLINE              -->
<style id="67" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_VARIABLE                 -->
<style id="68" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_SYSTEMVARIABLE           -->
<style id="69" fore-color="#66D9EF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_KNOWNSYSTEMVARIABLE      -->
<style id="70" fore-color="#AE81FF" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_NUMBER                   -->
<style id="71" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_MAJORKEYWORD             -->
<style id="72" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_KEYWORD                  -->
<style id="73" fore-color="#9B859D" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_DATABASEOBJECT           -->
<style id="74" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_PROCEDUREKEYWORD         -->
<style id="75" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_STRING                   -->
<style id="76" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_SQSTRING                 -->
<style id="77" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_DQSTRING                 -->
<style id="78" fore-color="#F92672" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_OPERATOR                 -->
<style id="79" fore-color="#9B859D" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_FUNCTION                 -->
<style id="80" fore-color="#DDDDDD" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_IDENTIFIER               -->
<style id="81" fore-color="#E6DB74" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_QUOTEDIDENTIFIER         -->
<style id="82" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER1                    -->
<style id="83" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER2                    -->
<style id="84" fore-color="#529B2F" back-color="#49483E" bold="No" />   <!-- SCE_MYSQL_USER3                    -->
<style id="85" fore-color="#66D9EF" back-color="#888888" bold="No" />   <!-- SCE_MYSQL_HIDDENCOMMAND            -->
<style id="86" fore-color="#AAAAAA" back-color="#888888" bold="No" />   <!-- SCE_MYSQL_PLACEHOLDER              -->

Stop mouse event propagation

Disable href link with JavaScript

<a href="#" onclick="return yes_js_login();">link</a>

yes_js_login = function() {
     // Your code here
     return false;
}

How it should also work in TypeScript with Angular (My Version: 4.1.2)

Template
<a class="list-group-item list-group-item-action" (click)="employeesService.selectEmployeeFromList($event); false" [routerLinkActive]="['active']" [routerLink]="['/employees', 1]">
    RouterLink
</a>
TypeScript
public selectEmployeeFromList(e) {

    e.stopPropagation();
    e.preventDefault();

    console.log("This onClick method should prevent routerLink from executing.");

    return false;
}

But it does not disable the executing of routerLink!

Java serialization - java.io.InvalidClassException local class incompatible

The short answer here is the serial ID is computed via a hash if you don't specify it. (Static members are not inherited--they are static, there's only (1) and it belongs to the class).

http://docs.oracle.com/javase/6/docs/platform/serialization/spec/class.html

The getSerialVersionUID method returns the serialVersionUID of this class. Refer to Section 4.6, "Stream Unique Identifiers." If not specified by the class, the value returned is a hash computed from the class's name, interfaces, methods, and fields using the Secure Hash Algorithm (SHA) as defined by the National Institute of Standards.

If you alter a class or its hierarchy your hash will be different. This is a good thing. Your objects are different now that they have different members. As such, if you read it back in from its serialized form it is in fact a different object--thus the exception.

The long answer is the serialization is extremely useful, but probably shouldn't be used for persistence unless there's no other way to do it. Its a dangerous path specifically because of what you're experiencing. You should consider a database, XML, a file format and probably a JPA or other persistence structure for a pure Java project.

TypeError: Cannot read property "0" from undefined

For me, the problem was I was using a package that isn't included in package.json nor installed.

import { ToastrService } from 'ngx-toastr';

So when the compiler tried to compile this, it threw an error.

(I installed it locally, and when running a build on an external server the error was thrown)

Android Studio: Plugin with id 'android-library' not found

Instruct Gradle to download Android plugin from Maven Central repository.

You do it by pasting the following code at the beginning of the Gradle build file:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.1'
    }
}

Replace version string 1.0.+ with the latest version. Released versions of Gradle plugin can be found in official Maven Repository or on MVNRepository artifact search.

how to use php DateTime() function in Laravel 5

If you just want to get the current UNIX timestamp I'd just use time()

$timestamp = time(); 

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Execution time of C program

Comparison of execution time of bubble sort and selection sort I have a program which compares the execution time of bubble sort and selection sort. To find out the time of execution of a block of code compute the time before and after the block by

 clock_t start=clock();
 …
 clock_t end=clock();
 CLOCKS_PER_SEC is constant in time.h library

Example code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
   int a[10000],i,j,min,temp;
   for(i=0;i<10000;i++)
   {
      a[i]=rand()%10000;
   }
   //The bubble Sort
   clock_t start,end;
   start=clock();
   for(i=0;i<10000;i++)
   {
     for(j=i+1;j<10000;j++)
     {
       if(a[i]>a[j])
       {
         int temp=a[i];
         a[i]=a[j];
         a[j]=temp;
       }
     }
   }
   end=clock();
   double extime=(double) (end-start)/CLOCKS_PER_SEC;
   printf("\n\tExecution time for the bubble sort is %f seconds\n ",extime);

   for(i=0;i<10000;i++)
   {
     a[i]=rand()%10000;
   }
   clock_t start1,end1;
   start1=clock();
   // The Selection Sort
   for(i=0;i<10000;i++)
   {
     min=i;
     for(j=i+1;j<10000;j++)
     {
       if(a[min]>a[j])
       {
         min=j;
       }
     }
     temp=a[min];
     a[min]=a[i];
     a[i]=temp;
   }
   end1=clock();
   double extime1=(double) (end1-start1)/CLOCKS_PER_SEC;
   printf("\n");
   printf("\tExecution time for the selection sort is %f seconds\n\n", extime1);
   if(extime1<extime)
     printf("\tSelection sort is faster than Bubble sort by %f seconds\n\n", extime - extime1);
   else if(extime1>extime)
     printf("\tBubble sort is faster than Selection sort by %f seconds\n\n", extime1 - extime);
   else
     printf("\tBoth algorithms have the same execution time\n\n");
}

Viewing all defined variables

To get the names:

for name in vars().keys():
  print(name)

To get the values:

for value in vars().values():
  print(value)

vars() also takes an optional argument to find out which vars are defined within an object itself.

GitHub: How to make a fork of public repository private?

The current answers are a bit out of date so, for clarity:

The short answer is:

  1. Do a bare clone of the public repo.
  2. Create a new private one.
  3. Do a mirror push to the new private one.

This is documented on GitHub: duplicating-a-repository

How to make graphics with transparent background in R using ggplot2?

Just to improve YCR's answer:

1) I added black lines on x and y axis. Otherwise they are made transparent too.

2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.

Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

Hashset vs Treeset

The TreeSet is one of two sorted collections (the other being TreeMap). It uses a Red-Black tree structure (but you knew that), and guarantees that the elements will be in ascending order, according to natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator

and A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted

HttpRequest maximum allowable size in tomcat?

Although other answers include some of the following information, this is the absolute minimum that needs to be changed on EC2 instances, specifically regarding deployment of large WAR files, and is the least likely to cause issues during future updates. I've been running into these limits about every other year due to the ever-increasing size of the Jenkins WAR file (now ~72MB).

More specifically, this answer is applicable if you encounter a variant of the following error in catalina.out:

SEVERE [https-jsse-nio-8443-exec-17] org.apache.catalina.core.ApplicationContext.log HTMLManager:
FAIL - Deploy Upload Failed, Exception:
[org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:
the request was rejected because its size (75333656) exceeds the configured maximum (52428800)]

On Amazon EC2 Linux instances, the only file that needs to be modified from the default installation of Tomcat (sudo yum install tomcat8) is:

/usr/share/tomcat8/webapps/manager/WEB-INF/web.xml

By default, the maximum upload size is exactly 50MB:

<multipart-config>
  <!-- 50MB max -->
  <max-file-size>52428800</max-file-size>
  <max-request-size>52428800</max-request-size>
  <file-size-threshold>0</file-size-threshold>
</multipart-config>

There are only two values that need to be modified (max-file-size and max-request-size):

<multipart-config>
  <!-- 100MB max -->
  <max-file-size>104857600</max-file-size>
  <max-request-size>104857600</max-request-size>
  <file-size-threshold>0</file-size-threshold>
</multipart-config>

When Tomcat is upgraded on these instances, the new version of the manager web.xml will be placed in web.xml.rpmnew, so any modifications to the original file will not be overwritten during future updates.

How to add additional libraries to Visual Studio project?

For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.

Next open Configuration Properties and then Linker.

Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,

Linker -> Input you'll add the actual library files under Additional Dependencies.

For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.

If there is a dll have a copy of it in your main project folder, and done.

I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.

Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.

This was written for Visual Studio 2008. For 2010 it should be roughly the same.

How are iloc and loc different?

  • DataFrame.loc() : Select rows by index value
  • DataFrame.iloc() : Select rows by rows number

example :

  1. Select first 5 rows of a table, df1 is your dataframe

df1.iloc[:5]

  1. Select first A, B rows of a table, df1 is your dataframe

df1.loc['A','B']

Bootstrap date time picker

Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
    <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
</head>_x000D_
<body>_x000D_
     <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Which @NotNull Java annotation should I use?

There are already too many answers here, but (a) it's 2019, and there's still no "standard" Nullable and (b) no other answer references Kotlin.

The reference to Kotlin is important, because Kotlin is 100% interoperable with Java and it has a core Null Safety feature. When calling Java libraries, it can take advantage of those annotations to let Kotlin tools know if a Java API can accept or return null.

As far as I know, the only Nullable packages compatible with Kotlin are org.jetbrains.annotations and android.support.annotation (now androidx.annotation). The latter is only compatible with Android so it can't be used in non-Android JVM/Java/Kotlin projects. However, the JetBrains package works everywhere.

So if you develop Java packages that should also work in Android and Kotlin (and be supported by Android Studio and IntelliJ), your best choice is probably the JetBrains package.

Maven:

<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations-java5</artifactId>
    <version>15.0</version>
</dependency>

Gradle:

implementation 'org.jetbrains:annotations-java5:15.0'

How to extract file name from path?

Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "\")(UBound(Split(sFilePath, "\")))

How to import js-modules into TypeScript file?

2021 Solution

If you're still getting this error message:

TS7016: Could not find a declaration file for module './myjsfile'

Then you might need to add the following to tsconfig.json

{
  "compilerOptions": {
    ...
    "allowJs": true,
    "checkJs": false,
    ...
  }
}

This prevents typescript from trying to apply module types to the imported javascript.

Convert PDF to clean SVG?

If DVI to SVG is an option, you can also use dvisvgm to convert a DVI file to an SVG file. This works perfectly for instance for LaTeX formulas (with option --no-fonts):

dvisvgm --no-fonts input.dvi -o output.svg

There is also pdf2svg which uses poppler and Cairo to convert a pdf into SVG. When I tried this, the SVG was perfectly rendered in inkscape.

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar problem but it had to do with the structure and class of the object. I would check how dih_y2$MemberID is formatted.

A variable modified inside a while loop is not remembered

UPDATED#2

Explanation is in Blue Moons's answer.

Alternative solutions:

Eliminate echo

while read line; do
...
done <<EOT
first line
second line
third line
EOT

Add the echo inside the here-is-the-document

while read line; do
...
done <<EOT
$(echo -e $lines)
EOT

Run echo in background:

coproc echo -e $lines
while read -u ${COPROC[0]} line; do 
...
done

Redirect to a file handle explicitly (Mind the space in < <!):

exec 3< <(echo -e  $lines)
while read -u 3 line; do
...
done

Or just redirect to the stdin:

while read line; do
...
done < <(echo -e  $lines)

And one for chepner (eliminating echo):

arr=("first line" "second line" "third line");
for((i=0;i<${#arr[*]};++i)) { line=${arr[i]}; 
...
}

Variable $lines can be converted to an array without starting a new sub-shell. The characters \ and n has to be converted to some character (e.g. a real new line character) and use the IFS (Internal Field Separator) variable to split the string into array elements. This can be done like:

lines="first line\nsecond line\nthird line"
echo "$lines"
OIFS="$IFS"
IFS=$'\n' arr=(${lines//\\n/$'\n'}) # Conversion
IFS="$OIFS"
echo "${arr[@]}", Length: ${#arr[*]}
set|grep ^arr

Result is

first line\nsecond line\nthird line
first line second line third line, Length: 3
arr=([0]="first line" [1]="second line" [2]="third line")

How to clone object in C++ ? Or Is there another solution?

The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.

class Foo
{ 
public:
  Foo();
  Foo(const Foo& rhs) { /* copy construction from rhs*/ }
  Foo& operator=(const Foo& rhs) {};
};

// ...

Foo orig;
Foo copy = orig;  // clones orig if implemented correctly

Sometimes it is beneficial to provide an explicit clone() method, especially for polymorphic classes.

class Interface
{
public:
  virtual Interface* clone() const = 0;
};

class Foo : public Interface
{
public:
  Interface* clone() const { return new Foo(*this); }
};

class Bar : public Interface
{
public:
  Interface* clone() const { return new Bar(*this); }
};


Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();

EDIT: Since Stack has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack's members from the so-called "right hand side" (rhs). However, you still need to ensure that any base classes are given the opportunity to initialize their members.

You do this by calling the base class:

Stack(const Stack& rhs) 
: List(rhs)  // calls copy ctor of List class
{
}

Stack& operator=(const Stack& rhs) 
{
  List::operator=(rhs);
  return * this;
};

Send parameter to Bootstrap modal window?

I found the solution at: Passing data to a bootstrap modal

So simply use:

 $(e.relatedTarget).data('book-id'); 

with 'book-id' is a attribute of modal with pre-fix 'data-'

How to get default gateway in Mac OSX

Using System Preferences:

Step 1: Click the Apple icon (at the top left of the screen) and select System Preferences.

Step 2: Click Network.

Step 3: Select your network connection and then click Advanced.

Step 4: Select the TCP/IP tab and find your gateway IP address listed next to Router.

pip install - locale.Error: unsupported locale setting

Run the following command (it will work):

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales

.gitignore all the .DS_Store files in every folder and subfolder

I think the problem you're having is that in some earlier commit, you've accidentally added .DS_Store files to the repository. Of course, once a file is tracked in your repository, it will continue to be tracked even if it matches an entry in an applicable .gitignore file.

You have to manually remove the .DS_Store files that were added to your repository. You can use

git rm --cached .DS_Store

Once removed, git should ignore it. You should only need the following line in your root .gitignore file: .DS_Store. Don't forget the period!

git rm --cached .DS_Store

removes only .DS_Store from the current directory. You can use

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

to remove all .DS_Stores from the repository.

Felt tip: Since you probably never want to include .DS_Store files, make a global rule. First, make a global .gitignore file somewhere, e.g.

echo .DS_Store >> ~/.gitignore_global

Now tell git to use it for all repositories:

git config --global core.excludesfile ~/.gitignore_global

This page helped me answer your question.

Node.js: Difference between req.query[] and req.params

You should be able to access the query using dot notation now.

If you want to access say you are receiving a GET request at /checkEmail?type=email&utm_source=xxxx&email=xxxxx&utm_campaign=XX and you want to fetch out the query used.

var type = req.query.type,
    email = req.query.email,
    utm = {
     source: req.query.utm_source,
     campaign: req.query.utm_campaign
    };

Params are used for the self defined parameter for receiving request, something like (example):

router.get('/:userID/food/edit/:foodID', function(req, res){
 //sample GET request at '/xavg234/food/edit/jb3552'

 var userToFind = req.params.userID;//gets xavg234
 var foodToSearch = req.params.foodID;//gets jb3552
 User.findOne({'userid':userToFind}) //dummy code
     .then(function(user){...})
     .catch(function(err){console.log(err)});
});

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

For Angular versions 5 and above, the updated importing line looks like :

import { map } from 'rxjs/operators';

OR

import { map } from 'rxjs/operators';

Also these versions totally supports Pipable Operators so you can easily use .pipe() and .subscribe().

If you are using Angular version 2, then the following line should work absolutely fine :

import 'rxjs/add/operator/map';

OR

import 'rxjs/add/operators/map';

If you still encounter a problem then you must go with :

import 'rxjs/Rx';

I won't prefer you to use it directly bcoz it boosts the Load time, as it has a large number of operators in it (useful and un-useful ones) which is not a good practice according to the industry norms, so make sure you try using the above mentioned importing lines first, and if that not works then you should go for rxjs/Rx

How to create and write to a txt file using VBA

Use FSO to create the file and write to it.

Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test" 
oFile.Close
Set fso = Nothing
Set oFile = Nothing    

See the documentation here:

How to get week numbers from dates?

If you want to get the week number with the year, Grant Shannon's solution using strftime works, but you need to make some corrections for the dates around january 1st. For instance, 2016-01-03 (yyyy-mm-dd) is week 53 of year 2015, not 2016. And 2018-12-31 is week 1 of 2019, not of 2018. This codes provides some examples and a solution. In column "yearweek" the years are sometimes wrong, in "yearweek2" they are corrected (rows 2 and 5).

library(dplyr)
library(lubridate)

# create a testset
test <- data.frame(matrix(data = c("2015-12-31",
                                   "2016-01-03",
                                   "2016-01-04",
                                   "2018-12-30",
                                   "2018-12-31",
                                   "2019-01-01") , ncol=1, nrow = 6 ))
# add a colname
colnames(test) <- "date_txt"

# this codes provides correct year-week numbers
test <- test %>%
        mutate(date = as.Date(date_txt, format = "%Y-%m-%d")) %>%
        mutate(yearweek = as.integer(strftime(date, format = "%Y%V"))) %>%
        mutate(yearweek2 = ifelse(test = day(date) > 7 & substr(yearweek, 5, 6) == '01',
                                 yes  = yearweek + 100,
                                 no   = ifelse(test = month(date) == 1 & as.integer(substr(yearweek, 5, 6)) > 51,
                                               yes  = yearweek - 100,
                                               no   = yearweek)))
# print the result
print(test)

    date_txt       date yearweek yearweek2
1 2015-12-31 2015-12-31   201553    201553
2 2016-01-03 2016-01-03   201653    201553
3 2016-01-04 2016-01-04   201601    201601
4 2018-12-30 2018-12-30   201852    201852
5 2018-12-31 2018-12-31   201801    201901
6 2019-01-01 2019-01-01   201901    201901

Set Background cell color in PHPExcel

  $objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');

It's in the documentation, located here: https://github.com/PHPOffice/PHPExcel/wiki/User-Documentation-Overview-and-Quickstart-Guide

How do I get the file name from a String containing the Absolute file path?

extract file name using java regex *.

public String extractFileName(String fullPathFile){
        try {
            Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
            Matcher regexMatcher = regex.matcher(fullPathFile);
            if (regexMatcher.find()){
                return regexMatcher.group(1);
            }
        } catch (PatternSyntaxException ex) {
            LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
        }
        return fullPathFile;
    }

How to determine day of week by passing specific date?

private String getDay(Date date){

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
    //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());                       
    return simpleDateFormat.format(date).toUpperCase();
}

private String getDay(String dateStr){
    //dateStr must be in DD-MM-YYYY Formate
    Date date = null;
    String day=null;

    try {
        date = new SimpleDateFormat("DD-MM-YYYY").parse(dateStr);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
        //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
        day = simpleDateFormat.format(date).toUpperCase();


    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return day;
}

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Now I return Object. I don't know better solution, but it works.

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> getAll() {
    List<Entity> entityList = entityManager.findAll();

    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return new ResponseEntity<Object>(entities, HttpStatus.OK);
}

Setting the default page for ASP.NET (Visual Studio) server configuration

This One Method For Published Solution To Show SpeciFic Page on startup.

Here Is the Route Example to Redirect to Specific Page...

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "YourSolutionName.Controllers" }
        );
    }
}

By Default Home Controllers Index method is executed when application is started, Here You Can Define yours.

Note : I am Using Visual Studio 2013 and "YourSolutionName" is to changed to your project Name..