Programs & Examples On #Export to word

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

For me, using Image(fit: BoxFit.fill ...) worked when in a bounded container.

Eclipse: How do I add the javax.servlet package to a project?

To expound on darioo's answer with a concrete example. Tomcat 7 installed using homebrew on OS X, using Eclipse:

  1. Right click your project folder, select Properties at the bottom of the context menu.
  2. Select "Java Build Path"
  3. Click Libraries" tab
  4. Click "Add Library..." button on right (about halfway down)
  5. Select "Server Runtime" click "Next"
  6. Select your Tomcat version from the list
  7. Click Finish

What? No Tomcat version is listed even though you have it installed via homebrew??

  1. Switch to the Java EE perspective (top right)
  2. In the "Window" menu select "Show View" -> "Servers"
  3. In the Servers tab (typically at bottom) right click and select "New > Server"
  4. Add the path to the homebrew tomcat installation in the dialog/wizard (something like: /usr/local/Cellar/tomcat/7.0.14/libexec)

Hope that helps someone who is just getting started out a little.

How to parse JSON array in jQuery?

Do NOT eval. use a real parser, i.e., from json.org

Create an empty data.frame

I keep this function handy for whenever I need it, and change the column names and classes to suit the use case:

make_df <- function() { data.frame(name=character(),
                     profile=character(),
                     sector=character(),
                     type=character(),
                     year_range=character(),
                     link=character(),
                     stringsAsFactors = F)
}

make_df()
[1] name       profile    sector     type       year_range link      
<0 rows> (or 0-length row.names)

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Android Studio Stuck at Gradle Download on create new project

If you're using OS X, and it continues to hang indefinitely, I'd recommend shutting down Android Studio (may have to force kill), then going to your ~/.gradle directory on the console. You'll see a wrapper/dists directory there and whatever version of gradle AS is trying to download. Check the timestamp of the download underneath the randomly named subdirectory. If you see that it is never changing, most likely your download was interrupted and AS wasn't able to restart it properly and will not unless you delete everything below the dists directory and start over.

So, with AS shutdown delete everything below ~/.gradle/wrapper/dists and then try again with a new project in AS. You can check the progress of the gradle download file (it will end in .part) to make sure that it's growing. Give it plenty of time as it IS a large file.

That's what finally worked for me.

Maximum call stack size exceeded on npm install

npm rebuild will work for sure

angularjs to output plain text instead of html

Use this function like

 String.prototype.text=function(){
   return this ? String(this).replace(/<[^>]+>/gm, '') : '';
 }

  "<span>My text</span>".text()
  output:
  My text

Fiddle

Python Iterate Dictionary by Index

There are several ways to call the for-loop in python and here what I found so far:

A = [1,2,3,4]
B = {"col1": [1,2,3],"col2":[4,5,6]}

# Forms of for loop in python:
# Forms with a list-form,
for item in A:
    print(item)
print("-----------")
  for item in B.keys():
    print(item)
print("-----------")
  for item in B.values():
    print(item)
print("-----------")
  for item in B.items():
    print(item)
    print("The value of keys is {} and the value of list of a key is {}".format(item[0],item[1]))
print("-----------")

Results are:

1
2
3
4
-----------
col1
col2
-----------
[1, 2, 3]
[4, 5, 6]
-----------
('col1', [1, 2, 3])
The value of keys is col1 and the value of list of a key is [1, 2, 3]
('col2', [4, 5, 6])
The value of keys is col2 and the value of list of a key is [4, 5, 6]
-----------

#pragma once vs include guards?

#pragma once allows the compiler to skip the file completely when it occurs again - instead of parsing the file until it reaches the #include guards.

As such, the semantics are a little different, but they are identical if they are used they way they are intended to be used.

Combining both is probably the safest route to go, as in the worst case (a compiler flagging unknown pragmas as actual errors, not just warnings) you would just to have to remove the #pragma's themselves.

When you limit your platforms to, say "mainstream compilers on the desktop", you could safely omit the #include guards, but I feel uneasy on that, too.

OT: if you have other tips/experiences to share on speeding up builds, I'd be curious.

Aggregate function in SQL WHERE-Clause

UPDATED query:

select id from t where id < (select max(id) from t);

It'll select all but the last row from the table t.

Format number to 2 decimal places

Just use format(number, qtyDecimals) sample: format(1000, 2) result 1000.00

How can I close a dropdown on click outside?

I've made a directive to address this similar problem and I'm using Bootstrap. But in my case, instead of waiting for the click event outside the element to close the current opened dropdown menu I think it is better if we watch over the 'mouseleave' event to automatically close the menu.

Here's my solution:

Directive

import { Directive, HostListener, HostBinding } from '@angular/core';
@Directive({
  selector: '[appDropdown]'
})
export class DropdownDirective {

  @HostBinding('class.open') isOpen = false;

  @HostListener('click') toggleOpen() {
    this.isOpen = !this.isOpen;
  }

  @HostListener('mouseleave') closeDropdown() {
    this.isOpen = false;
  }

}

HTML

<ul class="nav navbar-nav navbar-right">
    <li class="dropdown" appDropdown>
      <a class="dropdown-toggle" data-toggle="dropdown">Test <span class="caret"></span>
      </a>
      <ul class="dropdown-menu">
          <li routerLinkActive="active"><a routerLink="/test1">Test1</a></li>
          <li routerLinkActive="active"><a routerLink="/test2/">Test2</a></li>
      </ul>
    </li>
</ul>

java.lang.IllegalArgumentException: No converter found for return value of type

I was getting the same error for a while.I had verify getter methods were available for all properties.Still was getting the same error. To resolve an issue Configure MVC xml(configuration) with

 <mvc:annotation-driven/>

.This is required for Spring to detect the presence of jackson and setup the corresponding converters.

How can I call a method in Objective-C?

calling the method is like this

[className methodName] 

however if you want to call the method in the same class you can use self

[self methodName] 

all the above is because your method was not taking any parameters

however if your method takes parameters you will need to do it like this

[self methodName:Parameter]

How to bind list to dataGridView?

I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.

public class FileName
{        
     public string ThisFieldWorks {get;set;}
     public string ThisFieldDoesNot;
}

Operation Not Permitted when on root - El Capitan (rootless disabled)

Correct solution is to copy or install to /usr/local/bin not /usr/bin.This is due to System Integrity Protection (SIP). SIP makes /usr/bin read-only but leaves /usr/local as read-write.

SIP should not be disabled as stated in the answer above because it adds another layer of protection against malware gaining root access. Here is a complete explanation of what SIP does and why it is useful.

As suggested in this answer one should not disable SIP (rootless mode) "It is not recommended to disable rootless mode! The best practice is to install custom stuff to "/usr/local" only."

Python - IOError: [Errno 13] Permission denied:

Just Close the opened file where you are going to write.

Android: How to Programmatically set the size of a Layout

You can get the actual height of called layout with this code:

public int getLayoutSize() {
// Get the layout id
    final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
    final AtomicInteger layoutHeight = new AtomicInteger();

    root.post(new Runnable() { 
    public void run() { 
        Rect rect = new Rect(); 
        Window win = getWindow();  // Get the Window
                win.getDecorView().getWindowVisibleDisplayFrame(rect);

                // Get the height of Status Bar
                int statusBarHeight = rect.top;

                // Get the height occupied by the decoration contents 
                int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();

                // Calculate titleBarHeight by deducting statusBarHeight from contentViewTop  
                int titleBarHeight = contentViewTop - statusBarHeight; 
                Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop); 

                // By now we got the height of titleBar & statusBar
                // Now lets get the screen size
                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);   
                int screenHeight = metrics.heightPixels;
                int screenWidth = metrics.widthPixels;
                Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);   

                // Now calculate the height that our layout can be set
                // If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also 
                layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
                Log.i("MY", "Layout Height = " + layoutHeight);   

            // Lastly, set the height of the layout       
            FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
            rootParams.height = layoutHeight.get();
            root.setLayoutParams(rootParams);
        }
    });

return layoutHeight.get();
}

HTTP 404 when accessing .svc file in IIS

What worked for me, On Windows 2012 Server R2:

WCF HTTP 404

Thanks goes to "Aaron D"

What is process.env.PORT in Node.js?

  • if you run node index.js ,Node will use 3000

  • If you run PORT=4444 node index.js, Node will use process.env.PORT which equals to 4444 in this example. Run with sudo for ports below 1024.

UTF-8, UTF-16, and UTF-32

Unicode is a standard and about UTF-x you can think as a technical implementation for some practical purposes:

  • UTF-8 - "size optimized": best suited for Latin character based data (or ASCII), it takes only 1 byte per character but the size grows accordingly symbol variety (and in worst case could grow up to 6 bytes per character)
  • UTF-16 - "balance": it takes minimum 2 bytes per character which is enough for existing set of the mainstream languages with having fixed size on it to ease character handling (but size is still variable and can grow up to 4 bytes per character)
  • UTF-32 - "performance": allows using of simple algorithms as result of fixed size characters (4 bytes) but with memory disadvantage

I need to round a float to two decimal places in Java

You can make use of DecimalFormat to give you the style you wish.

DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number));  // prints 1.30E7

Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Resizing UITableView to fit content

Swift 5 and 4.2 solution without KVO, DispatchQueue, or setting constraints yourself.

This solution is based on Gulz's answer.

1) Create a subclass of UITableView:

import UIKit

final class ContentSizedTableView: UITableView {
    override var contentSize:CGSize {
        didSet {
            invalidateIntrinsicContentSize()
        }
    }

    override var intrinsicContentSize: CGSize {
        layoutIfNeeded()
        return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
    }
}

2) Add a UITableView to your layout and set constraints on all sides. Set the class of it to ContentSizedTableView.

3) You should see some errors, because Storyboard doesn't take our subclass' intrinsicContentSize into account. Fix this by opening the size inspector and overriding the intrinsicContentSize to a placeholder value. This is an override for design time. At runtime it will use the override in our ContentSizedTableView class


Update: Changed code for Swift 4.2. If you're using a prior version, use UIViewNoIntrinsicMetric instead of UIView.noIntrinsicMetric

How to print a date in a regular format?

You can do:

mylist.append(str(today))

How to correctly iterate through getElementsByClassName

If you use the new querySelectorAll you can call forEach directly.

document.querySelectorAll('.edit').forEach(function(button) {
    // Now do something with my button
});

Per the comment below. nodeLists do not have a forEach function.

If using this with babel you can add Array.from and it will convert non node lists to a forEach array. Array.from does not work natively in browsers below and including IE 11.

Array.from(document.querySelectorAll('.edit')).forEach(function(button) {
    // Now do something with my button
});

At our meetup last night I discovered another way to handle node lists not having forEach

[...document.querySelectorAll('.edit')].forEach(function(button) {
    // Now do something with my button
});

Browser Support for [...]

Showing as Node List

Showing as Node List

Showing as Array

Showing as Array

How to count how many values per level in a given factor?

Use the package plyr with lapply to get frequencies for every value (level) and every variable (factor) in your data frame.

library(plyr)
lapply(df, count)

Make footer stick to bottom of page correctly

The simplest solution is to use min-height on the <html> tag and position the <footer> with position:absolute;

Demo: jsfiddle and SO snippet:

_x000D_
_x000D_
html {_x000D_
    position: relative;_x000D_
    min-height: 100%;_x000D_
}_x000D_
_x000D_
body {_x000D_
    margin: 0 0 100px;_x000D_
    /* bottom = footer height */_x000D_
    padding: 25px;_x000D_
}_x000D_
_x000D_
footer {_x000D_
    background-color: orange;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    height: 100px;_x000D_
    width: 100%;_x000D_
    overflow: hidden;_x000D_
}
_x000D_
<article>_x000D_
    <!-- or <div class="container">, etc. -->_x000D_
    <h1>James Dean CSS Sticky Footer</h1>_x000D_
    <p>Blah blah blah blah</p>_x000D_
    <p>More blah blah blah</p>_x000D_
</article>_x000D_
<footer>_x000D_
    <h1>Footer Content</h1>_x000D_
</footer>
_x000D_
_x000D_
_x000D_

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Just after your Page_Load add this:

public override void VerifyRenderingInServerForm(Control control)
{
    //base.VerifyRenderingInServerForm(control);
}

Note that I don't do anything in the function.

EDIT: Tim answered the same thing. :) You can also find the answer Here

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

This error occurs when there are some non ASCII characters in our string and we are performing any operations on that string without proper decoding. This helped me solve my problem. I am reading a CSV file with columns ID,Text and decoding characters in it as below:

train_df = pd.read_csv("Example.csv")
train_data = train_df.values
for i in train_data:
    print("ID :" + i[0])
    text = i[1].decode("utf-8",errors="ignore").strip().lower()
    print("Text: " + text)

How to implement an android:background that doesn't stretch?

The key is to set the drawable as the image of the button, not as a background. Like this:

rb.setButtonDrawable(R.drawable.whatever_drawable);

How to prevent long words from breaking my div?

CSS Cross Browser Word Wrap

.word_wrap
{
    white-space: pre-wrap; /* css-3 */
    white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
    white-space: -pre-wrap; /* Opera 4-6 */
    white-space: -o-pre-wrap; /* Opera 7 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */
}

How to create a GUID in Excel?

As of modern version of Excel, there's the syntax with commas, not semicolons. I'm posting this answer for convenience of others so they don't have to replace the strings- We're all lazy... hrmp... human, right?

=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4))

Or, if you like me dislike when a guid screams and shouts and you, we can go lower-cased like this.

=LOWER(CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,42949),4),"-",DEC2HEX(RANDBETWEEN(0,4294967295),8),DEC2HEX(RANDBETWEEN(0,42949),4)))

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Combine two tables that have no common fields

There are a number of ways to do this, depending on what you really want. With no common columns, you need to decide whether you want to introduce a common column or get the product.

Let's say you have the two tables:

parts:              custs:
+----+----------+   +-----+------+
| id | desc     |   |  id | name |
+----+----------+   +-----+------+
|  1 | Sprocket |   | 100 | Bob  |
|  2 | Flange   |   | 101 | Paul |
+----+----------+   +-----+------+

Forget the actual columns since you'd most likely have a customer/order/part relationship in this case; I've just used those columns to illustrate the ways to do it.

A cartesian product will match every row in the first table with every row in the second:

> select * from parts, custs;
      id desc     id  name
      -- ----     --- ----
      1  Sprocket 101 Bob
      1  Sprocket 102 Paul
      2  Flange   101 Bob
      2  Flange   102 Paul

That's probably not what you want since 1000 parts and 100 customers would result in 100,000 rows with lots of duplicated information.

Alternatively, you can use a union to just output the data, though not side-by-side (you'll need to make sure column types are compatible between the two selects, either by making the table columns compatible or coercing them in the select):

> select id as pid, desc, null as cid, null as name from parts
  union
  select null as pid, null as desc, id as cid, name from custs;
    pid desc     cid name
    --- ----     --- ----
                 101 Bob 
                 102 Paul
    1   Sprocket
    2   Flange

In some databases, you can use a rowid/rownum column or pseudo-column to match records side-by-side, such as:

id desc     id  name
-- ----     --- ----
1  Sprocket 101 Bob
2  Flange   101 Bob

The code would be something like:

select a.id, a.desc, b.id, b.name
from parts a, custs b
where a.rownum = b.rownum;

It's still like a cartesian product but the where clause limits how the rows are combined to form the results (so not a cartesian product at all, really).

I haven't tested that SQL for this since it's one of the limitations of my DBMS of choice, and rightly so, I don't believe it's ever needed in a properly thought-out schema. Since SQL doesn't guarantee the order in which it produces data, the matching can change every time you do the query unless you have a specific relationship or order by clause.

I think the ideal thing to do would be to add a column to both tables specifying what the relationship is. If there's no real relationship, then you probably have no business in trying to put them side-by-side with SQL.

If you just want them displayed side-by-side in a report or on a web page (two examples), the right tool to do that is whatever generates your report or web page, coupled with two independent SQL queries to get the two unrelated tables. For example, a two-column grid in BIRT (or Crystal or Jasper) each with a separate data table, or a HTML two column table (or CSS) each with a separate data table.

In Perl, how can I read an entire file into a string?

This is more of a suggestion on how NOT to do it. I've just had a bad time finding a bug in a rather big Perl application. Most of the modules had its own configuration files. To read the configuration files as-a-whole, I found this single line of Perl somewhere on the Internet:

# Bad! Don't do that!
my $content = do{local(@ARGV,$/)=$filename;<>};

It reassigns the line separator as explained before. But it also reassigns the STDIN.

This had at least one side effect that cost me hours to find: It does not close the implicit file handle properly (since it does not call closeat all).

For example, doing that:

use strict;
use warnings;

my $filename = 'some-file.txt';

my $content = do{local(@ARGV,$/)=$filename;<>};
my $content2 = do{local(@ARGV,$/)=$filename;<>};
my $content3 = do{local(@ARGV,$/)=$filename;<>};

print "After reading a file 3 times redirecting to STDIN: $.\n";

open (FILE, "<", $filename) or die $!;

print "After opening a file using dedicated file handle: $.\n";

while (<FILE>) {
    print "read line: $.\n";
}

print "before close: $.\n";
close FILE;
print "after close: $.\n";

results in:

After reading a file 3 times redirecting to STDIN: 3
After opening a file using dedicated file handle: 3
read line: 1
read line: 2
(...)
read line: 46
before close: 46
after close: 0

The strange thing is, that the line counter $. is increased for every file by one. It's not reset, and it does not contain the number of lines. And it is not reset to zero when opening another file until at least one line is read. In my case, I was doing something like this:

while($. < $skipLines) {<FILE>};

Because of this problem, the condition was false because the line counter was not reset properly. I don't know if this is a bug or simply wrong code... Also calling close; oder close STDIN; does not help.

I replaced this unreadable code by using open, string concatenation and close. However, the solution posted by Brad Gilbert also works since it uses an explicit file handle instead.

The three lines at the beginning can be replaced by:

my $content = do{local $/; open(my $f1, '<', $filename) or die $!; my $tmp1 = <$f1>; close $f1 or die $!; $tmp1};
my $content2 = do{local $/; open(my $f2, '<', $filename) or die $!; my $tmp2 = <$f2>; close $f2 or die $!; $tmp2};
my $content3 = do{local $/; open(my $f3, '<', $filename) or die $!; my $tmp3 = <$f3>; close $f3 or die $!; $tmp3};

which properly closes the file handle.

Codeigniter - no input file specified

RewriteEngine, DirectoryIndex in .htaccess file of CodeIgniter apps

I just changed the .htaccess file contents and as shown in the following links answer. And tried refreshing the page (which didn't work, and couldn't find the request to my controller) it worked.

Then just because of my doubt I undone the changes I did to my .htaccess inside my public_html folder back to original .htaccess content. So it's now as follows (which is originally it was):

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]

And now also it works.

Hint: Seems like before the Rewrite Rules haven't been clearly setup within the Server context.

My file structure is as follows:

/
|- gheapp
|    |- application
|    L- system
|
|- public_html
|    |- .htaccess
|    L- index.php

And in the index.php I have set up the following paths to the system and the application:

$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';

Note: by doing so, our application source code becomes hidden to the public at first.

Please, if you guys find anything wrong with my answer, comment and re-correct me!
Hope beginners would find this answer helpful.

Thanks!

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

How do I rename all folders and files to lowercase on Linux?

Man, you guys/gals like to over complicate things... Use:

rename 'y/A-Z/a-z/' *

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

How to convert a string to integer in C?

int atoi(const char* str){
    int num = 0;
    int i = 0;
    bool isNegetive = false;
    if(str[i] == '-'){
        isNegetive = true;
        i++;
    }
    while (str[i] && (str[i] >= '0' && str[i] <= '9')){
        num = num * 10 + (str[i] - '0');
        i++;
    }
    if(isNegetive) num = -1 * num;
    return num;
}

Where do I find the current C or C++ standard documents?

The actual standards documents may not be the most useful. Most compilers do not fully implement the standards and may sometimes actually conflict. So the compiler documentation that you would already have will be more useful. Additionally, the documentation will contain platform-specific remarks and notes on any caveats.

Given a URL to a text file, what is the simplest way to read the contents of the text file?

For me, none of the above responses worked straight ahead. Instead, I had to do the following (Python 3):

from urllib.request import urlopen

data = urlopen("[your url goes here]").read().decode('utf-8')

# Do what you need to do with the data.

When should an IllegalArgumentException be thrown?

The API doc for IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

From looking at how it is used in the JDK libraries, I would say:

  • It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.

  • It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).

I would use IllegalArgumentException to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.

Declaring a python function with an array parameters and passing an array argument to the function call?

What you have is on the right track.

def dosomething( thelist ):
    for element in thelist:
        print element

dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )  

Produces the output:

1
2
3
red
green
blue

A couple of things to note given your comment above: unlike in C-family languages, you often don't need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list) to get index,element pairs, rather than doing the x in range(len(thelist)) dance.

Letter Count on a string

Alternatively You can use:

mystring = 'banana'
number = mystring.count('a')

How to float 3 divs side by side using CSS?

The modern way is to use the CSS flexbox, see support tables.

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
.container > div {_x000D_
  flex: 1; /*grow*/_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>Left div</div>_x000D_
  <div>Middle div</div>  _x000D_
  <div>Right div</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also use CSS grid, see support tables.

_x000D_
_x000D_
.container {_x000D_
  display: grid;_x000D_
  grid-template-columns: 1fr 1fr 1fr; /* fraction*/_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>Left div</div>_x000D_
  <div>Middle div</div>  _x000D_
  <div>Right div</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Force drop mysql bypassing foreign key constraint

Drop database exist in all versions of MySQL. But if you want to keep the table structure, here is an idea

mysqldump --no-data --add-drop-database --add-drop-table -hHOSTNAME -uUSERNAME -p > dump.sql

This is a program, not a mysql command

Then, log into mysql and

source dump.sql;

uppercase first character in a variable with bash

It can be done in pure bash with bash-3.2 as well:

# First, get the first character.
fl=${foo:0:1}

# Safety check: it must be a letter :).
if [[ ${fl} == [a-z] ]]; then
    # Now, obtain its octal value using printf (builtin).
    ord=$(printf '%o' "'${fl}")

    # Fun fact: [a-z] maps onto 0141..0172. [A-Z] is 0101..0132.
    # We can use decimal '- 40' to get the expected result!
    ord=$(( ord - 40 ))

    # Finally, map the new value back to a character.
    fl=$(printf '%b' '\'${ord})
fi

echo "${fl}${foo:1}"

Add a pipe separator after items in an unordered list unless that item is the last on a line

I know I'm a bit late to the party, but if you can put up with having the lines left-justified, one hack is to put the pipes before the items and then put a mask over the left edge, basically like so:

li::before {
  content: " | ";
  white-space: nowrap;
}

ul, li {
  display: inline;
}

.mask {
  width:4px;
  position: absolute;
  top:8px; //position as needed
}

more complete example: http://jsbin.com/hoyaduxi/1/edit

How to check size of a file using Bash?

I would use du's --threshold for this. Not sure if this option is available in all versions of du but it is implemented in GNU's version.

Quoting from du(1)'s manual:

-t, --threshold=SIZE
       exclude entries smaller than SIZE if positive, or entries greater
       than SIZE if negative

Here's my solution, using du --threshold= for OP's use case:

THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
    mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
    mv -f /root/tmp/file.txt /var/www/file.txt
fi

The advantage of that, is that du can accept an argument to that option in a known format - either human as in 10K, 10MiB or what ever you feel comfortable with - you don't need to manually convert between formats / units since du handles that.

For reference, here's the explanation on this SIZE argument from the man page:

The SIZE argument is an integer and optional unit (example: 10K is 
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.

Calculate RSA key fingerprint

On Fedora I do locate ~/.ssh which tells me keys are at

/root/.ssh
/root/.ssh/authorized_keys

How to know which is running in Jupyter notebook?

import sys
sys.executable

will give you the interpreter. You can select the interpreter you want when you create a new notebook. Make sure the path to your anaconda interpreter is added to your path (somewhere in your bashrc/bash_profile most likely).

For example I used to have the following line in my .bash_profile, that I added manually :

export PATH="$HOME/anaconda3/bin:$PATH"

EDIT: As mentioned in a comment, this is not the proper way to add anaconda to the path. Quoting Anaconda's doc, this should be done instead after install, using conda init:

Should I add Anaconda to the macOS or Linux PATH?

We do not recommend adding Anaconda to the PATH manually. During installation, you will be asked “Do you wish the installer to initialize Anaconda3 by running conda init?” We recommend “yes”. If you enter “no”, then conda will not modify your shell scripts at all. In order to initialize after the installation process is done, first run source <path to conda>/bin/activate and then run conda init

Cast IList to List

Try

List<SubProduct> subProducts = new List<SubProduct>(Model.subproduct);

or

List<SubProduct> subProducts = Model.subproducts as List<SubProduct>;

Convert javascript array to string

Four methods to convert an array to a string.

Coercing to a string

var arr = ['a', 'b', 'c'] + [];  // "a,b,c"

var arr = ['a', 'b', 'c'] + '';  // "a,b,c"

Calling .toString()

var arr = ['a', 'b', 'c'].toString();  // "a,b,c"

Explicitly joining using .join()

var arr = ['a', 'b', 'c'].join();  // "a,b,c" (Defaults to ',' seperator)

var arr = ['a', 'b', 'c'].join(',');  // "a,b,c"

You can use other separators, for example, ', '

var arr = ['a', 'b', 'c'].join(', ');  // "a, b, c"

Using JSON.stringify()

This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.

var arr = JSON.stringify(['a', 'b', 'c']);  // '["a","b","c"]'

How to get the home directory in Python?

You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

What is a web service endpoint?

Updated answer, from Peter in comments :

This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").


Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html

A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

  • Types– a container for data type definitions using some type system (such as XSD).
  • Message– an abstract, typed definition of the data being communicated.
  • Operation– an abstract description of an action supported by the service.
  • Port Type–an abstract set of operations supported by one or more endpoints.
  • Binding– a concrete protocol and data format specification for a particular port type.
  • Port– a single endpoint defined as a combination of a binding and a network address.
  • Service– a collection of related endpoints.

http://www.ehow.com/info_12212371_definition-service-endpoint.html

The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.

How to change root logging level programmatically for logback

I seem to be having success doing

org.jboss.logmanager.Logger logger = org.jboss.logmanager.Logger.getLogger("");
logger.setLevel(java.util.logging.Level.ALL);

Then to get detailed logging from netty, the following has done it

org.slf4j.impl.SimpleLogger.setLevel(org.slf4j.impl.SimpleLogger.TRACE);

403 Forbidden error when making an ajax Post request in Django framework

Because you did not post the csrfmiddlewaretoken, so Django forbid you. this document can help you.

Why doesn't list have safe "get" method like dictionary?

This works if you want the first element, like my_list.get(0)

>>> my_list = [1,2,3]
>>> next(iter(my_list), 'fail')
1
>>> my_list = []
>>> next(iter(my_list), 'fail')
'fail'

I know it's not exactly what you asked for but it might help others.

Check empty string in Swift?

I can recommend add small extension to String or Array that looks like

extension Collection {
    public var isNotEmpty: Bool {
        return !self.isEmpty
    }
}

With it you can write code that is easier to read. Compare this two lines

if !someObject.someParam.someSubParam.someString.isEmpty {}

and

if someObject.someParam.someSubParam.someString.isNotEmpty {}

It is easy to miss ! sign in the beginning of fist line.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

Working with select using AngularJS's ng-options

In CoffeeScript:

#directive
app.directive('select2', ->
    templateUrl: 'partials/select.html'
    restrict: 'E'
    transclude: 1
    replace: 1
    scope:
        options: '='
        model: '='
    link: (scope, el, atr)->
        el.bind 'change', ->
            console.log this.value
            scope.model = parseInt(this.value)
            console.log scope
            scope.$apply()
)
<!-- HTML partial -->
<select>
  <option ng-repeat='o in options'
          value='{{$index}}' ng-bind='o'></option>
</select>

<!-- HTML usage -->
<select2 options='mnuOffline' model='offlinePage.toggle' ></select2>

<!-- Conclusion -->
<p>Sometimes it's much easier to create your own directive...</p>

Email address validation using ASP.NET MVC data type attributes

if you aren't yet using .net 4.5:

/// <summary>
/// TODO: AFTER WE UPGRADE TO .NET 4.5 THIS WILL NO LONGER BE NECESSARY.
/// </summary>
public class EmailAnnotation : RegularExpressionAttribute
{
    static EmailAnnotation()
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAnnotation), typeof(RegularExpressionAttributeAdapter));
    }

    /// <summary>
    /// from: http://stackoverflow.com/a/6893571/984463
    /// </summary>
    public EmailAnnotation()
        : base(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
            + "@"
            + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") { }

    public override string FormatErrorMessage(string name)
    {
        return "E-mail is not valid";
    }
}

Then you can do this:

    public class ContactEmailAddressDto
    {
        public int ContactId { get; set; }
        [Required]
        [Display(Name = "New Email Address")]
        [EmailAnnotation] //**<----- Nifty.**
        public string EmailAddressToAdd { get; set; }
    }

How to ignore whitespace in a regular expression subject string?

You could put \s* inbetween every character in your search string so if you were looking for cat you would use c\s*a\s*t\s*s\s*s

It's long but you could build the string dynamically of course.

You can see it working here: http://www.rubular.com/r/zzWwvppSpE

Creating a Shopping Cart using only HTML/JavaScript

You simply need to use simpleCart

It is a free and open-source javascript shopping cart that easily integrates with your current website.

You will get the full source code at github

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

Bluetooth pairing without user confirmation

If you are asking if you can pair two devices without the user EVER approving the pairing, no it cannot be done, it is a security feature. If you are paired over Bluetooth there is no need to exchange data over NFC, just exchange data over the Bluetooth link.

I don't think you can circumvent Bluetooth security by passing an authentication packet over NFC, but I could be wrong.

Javascript Iframe innerHTML

You can get the source from another domain if you install the ForceCORS filter on Firefox. When you turn on this filter, it will bypass the security feature in the browser and your script will work even if you try to read another webpage. For example, you could open FoxNews.com in an iframe and then read its source. The reason modern web brwosers deny this ability by default is because if the other domain includes a piece of JavaScript and you're reading that and displaying it on your page, it could contain malicious code and pose a security threat. So, whenever you're displaying data from another domain on your page, you must beware of this real threat and implement a way to filter out all JavaScript code from your text before you're going to display it. Remember, when a supposed piece of raw text contains some code enclosed within script tags, they won't show up when you display it on your page, nevertheless they will run! So, realize this is a threat.

http://www-jo.se/f.pfleger/forcecors

Creating an empty list in Python

I do not really know about it, but it seems to me, by experience, that jpcgt is actually right. Following example: If I use following code

t = [] # implicit instantiation
t = t.append(1)

in the interpreter, then calling t gives me just "t" without any list, and if I append something else, e.g.

t = t.append(2)

I get the error "'NoneType' object has no attribute 'append'". If, however, I create the list by

t = list() # explicit instantiation

then it works fine.

Best way to update an element in a generic List

AllDogs.First(d => d.Id == "2").Name = "some value";

However, a safer version of that might be this:

var dog = AllDogs.FirstOrDefault(d => d.Id == "2");
if (dog != null) { dog.Name = "some value"; }

Parse String to Date with Different Format in Java

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

How to check if a MySQL query using the legacy API was successful?

mysql_query function is used for executing mysql query in php. mysql_query returns false if query execution fails.Alternatively you can try using mysql_error() function For e.g

$result=mysql_query($sql)

or

die(mysql_error());

In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.

Create request with POST, which response codes 200 or 201 and content

Another answer I would have for this would be to take a pragmatic approach and keep your REST API contract simple. In my case I had refactored my REST API to make things more testable without resorting to JavaScript or XHR, just simple HTML forms and links.

So to be more specific on your question above, I'd just use return code 200 and have the returned message contain a JSON message that your application can understand. Depending on your needs it may require the ID of the object that is newly created so the web application can get the data in another call.

One note, in my refactored API contract, POST responses should not contain any cacheable data as POSTs are not really cachable, so limit it to IDs that can be requested and cached using a GET request.

Load a WPF BitmapImage from a System.Drawing.Bitmap

I came to this question because I was trying to do the same, but in my case the Bitmap is from a resource/file. I found the best solution is as described in the following link:

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx

// Create the image element.
Image simpleImage = new Image();    
simpleImage.Width = 200;
simpleImage.Margin = new Thickness(5);

// Create source.
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
bi.UriSource = new Uri(@"/sampleImages/cherries_larger.jpg",UriKind.RelativeOrAbsolute);
bi.EndInit();
// Set the image source.
simpleImage.Source = bi;

Input widths on Bootstrap 3

Bootstrap uses the class 'form-input' for controlling the attributes of 'input fields'. Simply, add your own 'form-input' class with the desired width, border, text size, etc in your css file or head section.

(or else, directly add the size='5' inline code in input attributes in the body section.)

<script async src="//jsfiddle.net/tX3ae/embed/"></script> 

change background image in body

Just set an onload function on the body:

<body onload="init()">

Then do something like this in javascript:

function init() {
  var someimage = 'changableBackgroudImage';
  document.body.style.background = 'url(img/'+someimage+'.png) no-repeat center center'
}

You can change the 'someimage' variable to whatever you want depending on some conditions, such as the time of day or something, and that image will be set as the background image.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

None of the solutions worked for me as of today. My situation was that I got my Android studio updated. The most popular thing to replace the tools folder with the latest one wouldn't work for me. Infact is not required in some cases.

npm update -g cordova did the trick for me.

Then I removed the platform and added it again.

ionic platform remove android

ionic platform add android

This works for me in Ionic. I am surecordova platform remove/add android will do the same stuff. Not tested though.

Working again !

Rounding a double to turn it into an int (java)

You really need to post a more complete example, so we can see what you're trying to do. From what you have posted, here's what I can see. First, there is no built-in round() method. You need to either call Math.round(n), or statically import Math.round, and then call it like you have.

what is trailing whitespace and how can I handle this?

I have got similar pep8 warning W291 trailing whitespace

long_text = '''Lorem Ipsum is simply dummy text  <-remove whitespace
of the printing and typesetting industry.'''

Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text

How to increment a datetime by one day?

A short solution without libraries at all. :)

d = "8/16/18"
day_value = d[(d.find('/')+1):d.find('/18')]
tomorrow = f"{d[0:d.find('/')]}/{int(day_value)+1}{d[d.find('/18'):len(d)]}".format()
print(tomorrow)
# 8/17/18

Make sure that "string d" is actually in the form of %m/%d/%Y so that you won't have problems transitioning from one month to the next.

TypeError: Cannot read property "0" from undefined

Looks like what you're trying to do is access property '0' of an undefined value in your 'data' array. If you look at your while statement, it appears this is happening because you are incrementing 'i' by 1 for each loop. Thus, the first time through, you will access, 'data[1]', but on the next loop, you'll access 'data[2]' and so on and so forth, regardless of the length of the array. This will cause you to eventually hit an array element which is undefined, if you never find an item in your array with property '0' which is equal to 'name'.

Ammend your while statement to this...

for(var iIndex = 1; iIndex <= data.length; iIndex++){
    if (data[iIndex][0] === name){
         break;
    };
    Logger.log(data[i][0]);
 };

Determine if char is a num or letter

You can normally check for ASCII letters or numbers using simple conditions

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
    /*This is an alphabet*/
}

For digits you can use

if (ch >= '0' && ch <= '9')
{
    /*It is a digit*/
}

But since characters in C are internally treated as ASCII values you can also use ASCII values to check the same.

How to check if a character is number or letter

How do I debug Node.js applications?

IntelliJ works wonderfully for Node.js.

In addition, IntelliJ supports 'Code Assistance' well.

Beginner Python Practice?

You could also try CheckIO which is kind of a quest where you have to post solutions in Python 2.7 or 3.3 to move up in the game. Fun and has quite a big community for questions and support.

From their Main Wiki Page:

Welcome to CheckIO – a service that has united all levels of Python developers – from beginners up to the real experts!

Here you can learn Python coding, try yourself in solving various kinds of problems and share your ideas with others. Moreover, you can consider original solutions of other users, exchange opinions and find new friends.

If you are just starting with Python – CheckIO is a great chance for you to learn the basics and get a rich practice in solving different tasks. If you’re an experienced coder, here you’ll find an exciting opportunity to perfect your skills and learn new alternative logics from others. On CheckIO you can not only resolve the existing tasks, but also provide your own ones and even get points for them. Enjoy the possibility of playing logical games, participating in exciting competitions and share your success with friends in CheckIO.org!

How can I make a UITextField move up when the keyboard is present - on starting to edit?

If you want your UIView shift properly and your active textfield should accurately position to user need so that he/she can see whatever they are input .

For that you must use Scrollview . This suppose to be your UIView hierarchy . ContainerView -> ScrollView -> ContentView -> Your View .

If you have made UIView design as per above discuss hierarchy, now in your controller class you need add notifications observer in viewwillappear and remove observer in viewwilldissappear .

But this approach needs to add on every controller where ever UIView need to shifts . I have been using 'TPKeyboardAvoiding' pod . It is reliable and easily handle shift of UIView for every possible case wether if you are Scrollview , TableView or CollectionView . You just need to pass class to your 'scrolling view' .

Like below

demo Image

You can change this class if you are tableview to 'TPKeyboardAvoidingTableView'. You can find complete running project Project Link

This robust approach I've been followed for development . Hope this helps!

How do I align views at the bottom of the screen?

This also works.

<LinearLayout 
    android:id="@+id/linearLayout4"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_below="@+id/linearLayout3"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal" 
    android:gravity="bottom"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="20dp"
>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" 

    />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" 


    />

</LinearLayout>

gravity="bottom" to float LinearLayout elements to bottom

Difference between checkout and export in SVN

As you stated, a checkout includes the .svn directories. Thus it is a working copy and will have the proper information to make commits back (if you have permission). If you do an export you are just taking a copy of the current state of the repository and will not have any way to commit back any changes.

How to pattern match using regular expression in Scala?

As delnan pointed out, the match keyword in Scala has nothing to do with regexes. To find out whether a string matches a regex, you can use the String.matches method. To find out whether a string starts with an a, b or c in lower or upper case, the regex would look like this:

word.matches("[a-cA-C].*")

You can read this regex as "one of the characters a, b, c, A, B or C followed by anything" (. means "any character" and * means "zero or more times", so ".*" is any string).

How to add headers to a multicolumn listbox in an Excel userform using VBA

Why not just add Labels to the top of the Listbox and if changes are needed, the only thing you need to programmatically change are the labels.

How to add link to flash banner

@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.

movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
  var url:String = "http://site";
  var request:URLRequest = new URLRequest(url);
  try {
    navigateToURL(request, '_blank');
  } catch (e:Error) {
    trace("Error occurred!");
  }
}

source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/

How to make Java work with SQL Server?

Maybe a little late, but using different drivers altogether is overkill for a case of user error:

db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );

should be either one of these:

db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );

(using named pipe) or:

db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );

using port number directly; you can leave out 1433 because it's the default port, leaving:

db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );

How do I use cx_freeze?

You can change the setup.py code to this:

    from cx_freeze import setup, Executable
    setup( name = "foo",
           version = "1.1",
           description = "Description of the app here.",
           executables = [Executable("foo.py")]
         )

I am sure it will work. I have tried it on both windows 7 as well as ubuntu 12.04

Get content uri from file path in android

Is better to use a validation to support versions pre Android N, example:

  if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N) {
     imageUri = Uri.parse(filepath);
  } else{
     imageUri = Uri.fromFile(new File(filepath));
  }

  if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N) {
     ImageView.setImageURI(Uri.parse(new File("/sdcard/cats.jpg").toString()));         
  } else{
     ImageView.setImageURI(Uri.fromFile(new File("/sdcard/cats.jpg")));
  }

https://es.stackoverflow.com/questions/71443/reporte-crash-android-os-fileuriexposedexception-en-android-n

Display QImage with QtGui

One common way is to add the image to a QLabel widget using QLabel::setPixmap(), and then display the QLabel as you would any other widget. Example:

#include <QtGui>

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  QPixmap pm("your-image.jpg");
  QLabel lbl;
  lbl.setPixmap(pm);
  lbl.show();
  return app.exec();
}

Are vectors passed to functions by value or by reference in C++

A vector is functionally same as an array. But, to the language vector is a type, and int is also a type. To a function argument, an array of any type (including vector[]) is treated as pointer. A vector<int> is not same as int[] (to the compiler). vector<int> is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.

So, you must use vector<int>& (preferably with const, if function isn't modifying it) to pass it as a reference.

File path issues in R using Windows ("Hex digits in character string" error)

The best way to deal with this in case of txt file which contains data for text mining (speech, newsletter, etc.) is to replace "\" with "/".

Example:

file<-Corpus(DirSource("C:/Users/PRATEEK/Desktop/training tool/Text Analytics/text_file_main"))

Modifying a query string without reloading the page

Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam() with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:

//function to remove query params from a URL
function removeURLParameter(url, parameter) {
    //better to use l.search if you have a location/link object
    var urlparts= url.split('?');   
    if (urlparts.length>=2) {

        var prefix= encodeURIComponent(parameter)+'=';
        var pars= urlparts[1].split(/[&;]/g);

        //reverse iteration as may be destructive
        for (var i= pars.length; i-- > 0;) {    
            //idiom for string.startsWith
            if (pars[i].lastIndexOf(prefix, 0) !== -1) {  
                pars.splice(i, 1);
            }
        }

        url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
        return url;
    } else {
        return url;
    }
}

//function to add/update query params
function insertParam(key, value) {
    if (history.pushState) {
        // var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
        var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
        var hash = window.location.hash
        //remove any param for the same key
        var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);

        //figure out if we need to add the param with a ? or a &
        var queryStart;
        if(currentUrlWithOutHash.indexOf('?') !== -1){
            queryStart = '&';
        } else {
            queryStart = '?';
        }

        var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
        window.history.pushState({path:newurl},'',newurl);
    }
}

Regular Expressions- Match Anything

(.*?) matches anything - I've been using it for years.

Switch in Laravel 5 - Blade

You can just add these code in AppServiceProvider class boot method.

Blade::extend(function($value, $compiler){
        $value = preg_replace('/(\s*)@switch\((.*)\)(?=\s)/', '$1<?php switch($2):', $value);
        $value = preg_replace('/(\s*)@endswitch(?=\s)/', '$1endswitch; ?>', $value);
        $value = preg_replace('/(\s*)@case\((.*)\)(?=\s)/', '$1case $2: ?>', $value);
        $value = preg_replace('/(?<=\s)@default(?=\s)/', 'default: ?>', $value);
        $value = preg_replace('/(?<=\s)@breakswitch(?=\s)/', '<?php break;', $value);
        return $value;
    });

then you can use as:

@switch( $item )
    @case( condition_1 )
        // do something
    @breakswitch
    @case( condition_2 )
        // do something else
    @breakswitch
    @default
        // do default behaviour
    @breakswitch
@endswitch

Enjoy It~

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Set default option in mat-select

Try this

<mat-form-field>
    <mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
    </mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
    public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

Displaying files (e.g. images) stored in Google Drive on a website

You can follow below steps to embed the files you want to your website.

  1. Find the PDF file in Google Drive
  2. Preview the PDF file in Google Drive
  3. Pop-out the Google Drive preview
  4. Use the More actions menu and choose Embed item
  5. Copy code provided
  6. Edit Google Sites page where you want to embed
  7. Open the HTML Editor
  8. Paste the HTML embed code provided by the Google Drive preview
  9. Use the Update button and Save the page

References: https://www.steegle.com/websites/google-sites-howtos/embed-drive-pdf

Get average color of image via Javascript

First: it can be done without HTML5 Canvas or SVG.
Actually, someone just managed to generate client-side PNG files using JavaScript, without canvas or SVG, using the data URI scheme.

Second: you might actually not need Canvas, SVG or any of the above at all.
If you only need to process images on the client side, without modifying them, all this is not needed.

You can get the source address from the img tag on the page, make an XHR request for it - it will most probably come from the browser cache - and process it as a byte stream from Javascript.
You will need a good understanding of the image format. (The above generator is partially based on libpng sources and might provide a good starting point.)

How to use this boolean in an if statement?

if(stop = true) should be if(stop == true), or simply (better!) if(stop).

This is actually a good opportunity to see a reason to why always use if(something) if you want to see if it's true instead of writing if(something == true) (bad style!).

By doing stop = true then you are assigning true to stop and not comparing.

So why the code below the if statement executed?

See the JLS - 15.26. Assignment Operators:

At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

So because you wrote stop = true, then you're satisfying the if condition.

Vagrant stuck connection timeout retrying

One more possible solution for users of the VMware provider: For me the issue was resolved after removing a parallel installation of VirtualBox on the same host machine. Network interfaces between VMware and VirtualBox were apparently conflicting

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

How to get all count of mongoose model?

The code below works. Note the use of countDocuments.

 var mongoose = require('mongoose');
 var db = mongoose.connect('mongodb://localhost/myApp');
 var userSchema = new mongoose.Schema({name:String,password:String});
 var userModel =db.model('userlists',userSchema);
 var anand = new userModel({ name: 'anand', password: 'abcd'});
 anand.save(function (err, docs) {
   if (err) {
       console.log('Error');
   } else {
       userModel.countDocuments({name: 'anand'}, function(err, c) {
           console.log('Count is ' + c);
      });
   }
 }); 

How to access ssis package variables inside script component

First List the Variable that you want to use them in Script task at ReadOnlyVariables in the Script task editor and Edit the Script

To use your ReadOnlyVariables in script code

String codeVariable = Dts.Variables["User::VariableNameinSSIS"].Value.ToString();

this line of code will treat the ssis package variable as a string.

Deep-Learning Nan loss reasons

The reason for nan, inf or -inf often comes from the fact that division by 0.0 in TensorFlow doesn't result in a division by zero exception. It could result in a nan, inf or -inf "value". In your training data you might have 0.0 and thus in your loss function it could happen that you perform a division by 0.0.

a = tf.constant([2., 0., -2.])
b = tf.constant([0., 0., 0.])
c = tf.constant([1., 1., 1.])
print((a / b) + c)

Output is the following tensor:

tf.Tensor([ inf  nan -inf], shape=(3,), dtype=float32)

Adding a small eplison (e.g., 1e-5) often does the trick. Additionally, since TensorFlow 2 the opteration tf.math.division_no_nan is defined.

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

How to plot data from multiple two column text files with legends in Matplotlib?

Assume your file looks like this and is named test.txt (space delimited):

1 2
3 4
5 6
7 8

Then:

#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt

with open("test.txt") as f:
    data = f.read()

data = data.split('\n')

x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]

fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.set_title("Plot title...")    
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')

ax1.plot(x,y, c='r', label='the data')

leg = ax1.legend()

plt.show()

Example plot:

I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

mutable does exist as you infer to allow one to modify data in an otherwise constant function.

The intent is that you might have a function that "does nothing" to the internal state of the object, and so you mark the function const, but you might really need to modify some of the objects state in ways that don't affect its correct functionality.

The keyword may act as a hint to the compiler -- a theoretical compiler could place a constant object (such as a global) in memory that was marked read-only. The presence of mutable hints that this should not be done.

Here are some valid reasons to declare and use mutable data:

  • Thread safety. Declaring a mutable boost::mutex is perfectly reasonable.
  • Statistics. Counting the number of calls to a function, given some or all of its arguments.
  • Memoization. Computing some expensive answer, and then storing it for future reference rather than recomputing it again.

npm can't find package.json

if the package.json file in the project directory is missing then you can create it by npm init.

if the package.json file is already created in the project directory then there is a possibility that you are not running your project from the right path. Use cd your-project-path in the terminal and then run your project from there.

Kill Attached Screen in Linux

Suppose your screen id has a pattern. Then you can use the following code to kill all the attached screen at once.

result=$(screen -ls | grep 'pattern_of_screen_id' -o)
for i in $result; 
do      
    `screen -X -S $i quit`;
done

Angular no provider for NameService

In Angular 2 there are three places you can "provide" services:

  1. bootstrap
  2. root component
  3. other components or directives

"The bootstrap provider option is intended for configuring and overriding Angular's own preregistered services, such as its routing support." -- reference

If you only want one instance of NameService across your entire app (i.e., Singleton), then include it in the providers array of your root component:

@Component({
   providers: [NameService],
   ...
)}
export class AppComponent { ... }

Plunker

If you would rather have one instance per component, use the providers array in the component's configuration object instead:

@Component({
   providers: [NameService],
   ...
)}
export class SomeOtherComponentOrDirective { ... }

See the Hierarchical Injectors doc for more info.

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

When to use which design pattern?

Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.

Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.

Using comma as list separator with AngularJS

Also:

angular.module('App.filters', [])
    .filter('joinBy', function () {
        return function (input,delimiter) {
            return (input || []).join(delimiter || ',');
        };
    });

And in template:

{{ itemsArray | joinBy:',' }}

How to round up integer division and have int result in Java?

Expanding on Peter's solution, this is what I've found works for me to always round 'towards positive infinity':

public static long divideAndRoundUp(long num, long divisor) {
    if (num == 0 || divisor == 0) { return 0; }

    int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);

    if (sign > 0) {
        return (num + divisor - 1) / divisor;
    }
    else {
        return (num / divisor);
    }
}

How to generate .json file with PHP?

Insert your fetched values into an array instead of echoing.

Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.

Recursively add the entire folder to a repository

I ran into this problem that cost me a little time, then remembered that git won't store empty folders. Remember that if you have a folder tree you want stored, put a file in at least the deepest folder of that tree, something like a file called ".gitkeep", just to affect storage by git.

Stopping an Android app from console

If all you are looking for is killing a package

pkill package_name 

should work

Border around specific rows in a table?

Group rows together using the <tbody> tag and then apply style.

<table>
  <tr><td>No Style here</td></tr>
  <tbody class="red-outline">
    <tr><td>Style me</td></tr>
    <tr><td>And me</td></tr>
  </tbody>
  <tr><td>No Style here</td></tr>
</table>  

And the css in style.css

.red-outline {
  outline: 1px solid red;
}

How to convert a String into an ArrayList?

Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:

List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));

How to debug Google Apps Script (aka where does Logger.log log to?)

Just as a notice. I made a test function for my spreadsheet. I use the variable google throws in the onEdit(e) function (I called it e). Then I made a test function like this:

function test(){
var testRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,7)
var testObject = {
    range:testRange,
    value:"someValue"
}
onEdit(testObject)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,6).setValue(Logger.getLog())
}

Calling this test function makes all the code run as you had an event in the spreadsheet. I just put in the possision of the cell i edited whitch gave me an unexpected result, setting value as the value i put into the cell. OBS! for more variables googles gives to the function go here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I've just been working on this for a few hours, trying various combinations of things from this and other pages. The thing that worked for me in the end was to make a site wrapper div, as suggested in the accepted answer, but to set both overflows to hidden instead of just the x overflow. If I leave overflow-y at scroll, I end up with a page that only scrolls vertically by a few pixels and then stops.

#all-wrapper {
  overflow: hidden;
}

Just this was enough, without setting anything on the body or html elements.

Change EditText hint color when using TextInputLayout

If you are using new androidx Material design library com.google.android.material then you can use colorstatelist to control hint text color in focused, hovered and default state as follows. (inspired by this)

In res/color/text_input_box_stroke.xml put something like the following:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="#fcc" android:state_focused="true"/>
    <item android:color="#cfc" android:state_hovered="true"/>
    <item android:color="#ccf"/>
</selector>

Then in your styles.xml you would put:

<style name="MtTILStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">
    <item name="boxStrokeColor">@color/text_input_box_stroke</item>
    <item name="hintTextColor">@color/text_input_box_stroke</item>
</style>

Finally indicate your style in the actual TextInputLayout For some reason you also need to set android:textColorHint for default text color of hint:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/my_layout_id"
    style="@style/LoginTextInputLayoutStyle"
    android:textColorHint="#ccf"
    ...

Linq UNION query to select two elements

EDIT:

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

This works on my side :

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

On yours it should be like this:

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

Thanks, i've learnt something today :)

Laravel: Validation unique on update

Here is the solution:

For Update:

public function controllerName(Request $request, $id)

{

    $this->validate($request, [
        "form_field_name" => 'required|unique:db_table_name,db_table_column_name,'.$id
    ]);

    // the rest code
}

That's it. Happy Coding :)

Creating a random string with A-Z and 0-9 in Java

You can easily do that with a for loop,

public static void main(String[] args) {
  String aToZ="ABCD.....1234"; // 36 letter.
  String randomStr=generateRandom(aToZ);

}

private static String generateRandom(String aToZ) {
    Random rand=new Random();
    StringBuilder res=new StringBuilder();
    for (int i = 0; i < 17; i++) {
       int randIndex=rand.nextInt(aToZ.length()); 
       res.append(aToZ.charAt(randIndex));            
    }
    return res.toString();
}

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

Iterating a JavaScript object's properties using jQuery

You can use each for objects too and not just for arrays:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Can I safely delete contents of Xcode Derived data folder?

XCODE 10 UPDATE

On the tab:

  1. Click Xcode
  2. Preferences
  3. Locations -> Derived Data

You can access all derived data and clear by deleting them.

Replace multiple whitespaces with single whitespace in JavaScript string

Here's a non-regex solution (just for fun):

_x000D_
_x000D_
var s = ' a   b   word word. word, wordword word   ';

// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"

// or ES2015:
s = s.split(' ').filter(n => n).join(' '); 
console.log(s); // "a b word word. word, wordword word"
_x000D_
_x000D_
_x000D_

Can even substitute filter(n => n) with .filter(String)

It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.

What function is to replace a substring from a string in C?

// Here is the code for unicode strings!


int mystrstr(wchar_t *txt1,wchar_t *txt2)
{
    wchar_t *posstr=wcsstr(txt1,txt2);
    if(posstr!=NULL)
    {
        return (posstr-txt1);
    }else
    {
        return -1;
    }
}

// assume: supplied buff is enough to hold generated text
void StringReplace(wchar_t *buff,wchar_t *txt1,wchar_t *txt2)
{
    wchar_t *tmp;
    wchar_t *nextStr;
    int pos;

    tmp=wcsdup(buff);

    pos=mystrstr(tmp,txt1);
    if(pos!=-1)
    {
        buff[0]=0;
        wcsncpy(buff,tmp,pos);
        buff[pos]=0;

        wcscat(buff,txt2);

        nextStr=tmp+pos+wcslen(txt1);

        while(wcslen(nextStr)!=0)
        {
            pos=mystrstr(nextStr,txt1);

            if(pos==-1)
            {
                wcscat(buff,nextStr);
                break;
            }

            wcsncat(buff,nextStr,pos);
            wcscat(buff,txt2);

            nextStr=nextStr+pos+wcslen(txt1);   
        }
    }

    free(tmp);
}

How to send email in ASP.NET C#

You can try this using hotmail like this:-

MailMessage o = new MailMessage("From", "To","Subject", "Body");
NetworkCredential netCred= new NetworkCredential("Sender Email","Sender Password");
SmtpClient smtpobj= new SmtpClient("smtp.live.com", 587); 
smtpobj.EnableSsl = true;
smtpobj.Credentials = netCred;
smtpobj.Send(o);

Why do I get a SyntaxError for a Unicode escape in my file path?

All the three syntax work very well.

Another way is to first write

path = r'C:\user\...................' (whatever is the path for you)

and then passing it to os.chdir(path)

Normalizing a list of numbers in Python

try:

normed = [i/sum(raw) for i in raw]

normed
[0.25, 0.5, 0.25]

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Smooth scroll to div id jQuery

This code will be useful for any internal link on the web

    $("[href^='#']").click(function() {
        id=$(this).attr("href")
        $('html, body').animate({
            scrollTop: $(id).offset().top
        }, 2000);
    });

Remove all occurrences of char from string

Using

public String replaceAll(String regex, String replacement)

will work.

Usage would be str.replace("X", "");.

Executing

"Xlakjsdf Xxx".replaceAll("X", "");

returns:

lakjsdf xx

How do you delete an ActiveRecord object?

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

PostgreSQL delete all content

The content of the table/tables in PostgreSQL database can be deleted in several ways.

Deleting table content using sql:

Deleting content of one table:

TRUNCATE table_name;
DELETE FROM table_name;

Deleting content of all named tables:

TRUNCATE table_a, table_b, …, table_z;

Deleting content of named tables and tables that reference to them (I will explain it in more details later in this answer):

TRUNCATE table_a, table_b CASCADE;

Deleting table content using pgAdmin:

Deleting content of one table:

Right click on the table -> Truncate

Deleting content of table and tables that reference to it:

Right click on the table -> Truncate Cascaded

Difference between delete and truncate:

From the documentation:

DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html

TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html

Working with table that is referenced from other table:

When you have database that has more than one table the tables have probably relationship. As an example there are three tables:

create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);

create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);

And some prepared data for these tables:

insert into customers values (1, 'John', 'Smith');

insert into orders values 
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);        

insert into loyalty_cards values (100, 'A123456789', 1);

Table orders references table customers and table loyalty_cards references table customers. When you try to TRUNCATE / DELETE FROM the table that is referenced by other table/s (the other table/s has foreign key constraint to the named table) you get an error. To delete content from all three tables you have to name all these tables (the order is not important)

TRUNCATE customers, loyalty_cards, orders;

or just the table that is referenced with CASCADE key word (you can name more tables than just one)

TRUNCATE customers CASCADE;

The same applies for pgAdmin. Right click on customers table and choose Truncate Cascaded.

Fastest way to add an Item to an Array

Not very clean but it works :)

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4

arr = arr.Concat({newItem}).ToArray

How to launch multiple Internet Explorer windows/tabs from batch file?

There is a setting in the IE options that controls whether it should open new links in an existing window or in a new window. I'm not sure if you can control it from the command line but maybe changing this option would be enough for you.

In IE7 it looks like the option is "Reuse windows for launching shortcuts (when tabbed browsing is disabled)".

Detect page change on DataTable

$('#tableId').on('draw.dt', function() {
    //This will get called when data table data gets redrawn to the      table.
});

How can I check if a value is of type Integer?

To check if a String contains digit character which represent an integer, you can use Integer.parseInt().

To check if a double contains a value which can be an integer, you can use Math.floor() or Math.ceil().

How to present popover properly in iOS 8

The following has a pretty comprehensive guide on how to configure and present popovers. https://www.appcoda.com/presentation-controllers-tutorial/

In summary, a viable implementation (with some updates from the original article syntax for Swift 4.2), to then be called from elsewhere, would be something like the following:

func showPopover(ofViewController popoverViewController: UIViewController, originView: UIView) {
    popoverViewController.modalPresentationStyle = UIModalPresentationStyle.popover
    if let popoverController = popoverViewController.popoverPresentationController {
        popoverController.delegate = self
        popoverController.sourceView = originView
        popoverController.sourceRect = originView.bounds
        popoverController.permittedArrowDirections = UIPopoverArrowDirection.any
    }
    self.present(popoverViewController, animated: true)
}

A lot of this was already covered in the answer from @mmc, but the article helps to explain some of those code elements used, and also show how it could be expanded.

It also provides a lot of additional detail about using delegation to handle the presentation style for iPhone vs. iPad, and to allow dismissal of the popover if it's ever shown full-screen. Again, updated for Swift 4.2:

func adaptivePresentationStyle(for: UIPresentationController) -> UIModalPresentationStyle {
    //return UIModalPresentationStyle.fullScreen
    return UIModalPresentationStyle.none
}

func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
    if traitCollection.horizontalSizeClass == .compact {
        return UIModalPresentationStyle.none
        //return UIModalPresentationStyle.fullScreen
    }
    //return UIModalPresentationStyle.fullScreen
    return UIModalPresentationStyle.none
}

func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? {
    switch style {
    case .fullScreen:
        let navigationController = UINavigationController(rootViewController: controller.presentedViewController)
        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: #selector(doneWithPopover))
        navigationController.topViewController?.navigationItem.rightBarButtonItem = doneButton
        return navigationController
    default:
        return controller.presentedViewController
    }
}

// As of Swift 4, functions used in selectors must be declared as @objc
@objc private func doneWithPopover() {
    self.dismiss(animated: true, completion: nil)
}

Hope this helps.

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

How to create a POJO?

According to Martin Fowler

The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.

Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.

  1. Each variable in a POJO should be declared as private.
  2. Default constructor should be overridden with public accessibility.
  3. Each variable should have its Setter-Getter method with public accessibility.
  4. Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
  5. Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).

And according to Java Language Specification, a POJO should not have to

  1. Extend pre-specified classes
  2. Implement pre-specified interfaces
  3. Contain pre-specified annotations

However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.

A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.

Read more on Plain Old Java Object (POJO) Explained.

Combining two lists and removing duplicates, without removing duplicates in original list

You can also combine RichieHindle's and Ned Batchelder's responses for an average-case O(m+n) algorithm that preserves order:

first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]

fs = set(first_list)
resulting_list = first_list + [x for x in second_list if x not in fs]

assert(resulting_list == [1, 2, 2, 5, 7, 9])

Note that x in s has a worst-case complexity of O(m), so the worst-case complexity of this code is still O(m*n).

Cleanest Way to Invoke Cross-Thread Events

I think the cleanest way is definitely to go the AOP route. Make a few aspects, add the necessary attributes, and you never have to check thread affinity again.

How to add more than one machine to the trusted hosts list using winrm

I prefer to work with the PSDrive WSMan:\.

Get TrustedHosts

Get-Item WSMan:\localhost\Client\TrustedHosts

Set TrustedHosts

provide a single, comma-separated, string of computer names

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'

or (dangerous) a wild-card

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'

to append to the list, the -Concatenate parameter can be used

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate

How can I check if my python object is a number?

Test if your variable is an instance of numbers.Number:

>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]

This uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number ABC).

However, in many cases you shouldn't worry about checking types manually - Python is duck typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"), so manually checking this is rarely really needed. It's just a bonus. You can add it when finishing a module to avoid pestering others with implementation details.

This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.

Scanner is never closed

According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.

(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Then NumPy sum function takes an optional axis argument that specifies along which axis you would like the sum performed:

>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])

Or, equivalently:

>>> numpy.sum(a, 0)
array([18, 22, 26])

Is there a way to iterate over a dictionary?

The block approach avoids running the lookup algorithm for every key:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
  NSLog(@"%@ => %@", key, value);
}];

Even though NSDictionary is implemented as a hashtable (which means that the cost of looking up an element is O(1)), lookups still slow down your iteration by a constant factor.

My measurements show that for a dictionary d of numbers ...

NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
  NSNumber* value = @(i);
  dict[value.stringValue] = value;
}

... summing up the numbers with the block approach ...

__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
  sum += value.intValue;
}];

... rather than the loop approach ...

int sum = 0;
for (NSString* key in dict)
  sum += [dict[key] intValue];

... is about 40% faster.

EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.

What does the following Oracle error mean: invalid column index

If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.

For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.

Difference between webdriver.Dispose(), .Close() and .Quit()

My understanding is driver.close(); will close the current browser, and driver.quit(); will terminate all the browser that.

How to upgrade safely php version in wamp server

  1. Simply Download the PHP version that you want from this url: http://wampserver.aviatechno.net/
  2. Goto your wamp\bin\php directory and extract it like this(Note: you need to rename your folder to phpversionOfPhp list of installed version in the directory
  3. Start wamp and click wamp icon and choose the version of php you want to use: https://gyazo.com/de5727d7e254795e238422783dec3758

Node.js getaddrinfo ENOTFOUND

If you need to use https, then use the https library

https = require('https');

// options
var options = {
    host: 'eternagame.wikia.com',
    path: '/wiki/EteRNA_Dictionary'
}

// get
https.get(options, callback);

For homebrew mysql installs, where's my.cnf?

For MacOS (High Sierra), MySQL that has been installed with home brew.

Increasing the global variables from mysql environment was not successful. So in that case creating of ~/.my.cnf is the safest option. Adding variables with [mysqld] will include the changes (Note: if you change with [mysql] , the change might not work).

<~/.my.cnf> [mysqld] connect_timeout = 43200 max_allowed_packet = 2048M net_buffer_length = 512M

Restart the mysql server. and check the variables. y

sql> SELECT @@max_allowed_packet; +----------------------+ | @@max_allowed_packet | +----------------------+ | 1073741824 | +----------------------+

1 row in set (0.00 sec)

Merge Cell values with PHPExcel - PHP

Try this

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

Make anchor link go some pixels above where it's linked to

window.addEventListener("hashchange", function () {
    window.scrollTo(window.scrollX, window.scrollY - 100);
});

This will allow the browser to do the work of jumping to the anchor for us and then we will use that position to offset from.

EDIT 1:

As was pointed out by @erb, this only works if you are on the page while the hash is changed. Entering the page with a #something already in the URL does not work with the above code. Here is another version to handle that:

// The function actually applying the offset
function offsetAnchor() {
    if(location.hash.length !== 0) {
        window.scrollTo(window.scrollX, window.scrollY - 100);
    }
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).

NOTE: To use jQuery, you could just replace window.addEventListener with $(window).on in the examples. Thanks @Neon.

EDIT 2:

As pointed out by a few, the above will fail if you click on the same anchor link two or more times in a row because there is no hashchange event to force the offset.

This solution is very slightly modified version of the suggestion from @Mave and uses jQuery selectors for simplicity

// The function actually applying the offset
function offsetAnchor() {
  if (location.hash.length !== 0) {
    window.scrollTo(window.scrollX, window.scrollY - 100);
  }
}

// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
  // Click events are captured before hashchanges. Timeout
  // causes offsetAnchor to be called after the page jump.
  window.setTimeout(function() {
    offsetAnchor();
  }, 0);
});

// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);

JSFiddle for this example is here

How to remove only 0 (Zero) values from column in excel 2010

Consider your data is into column A and will write coding now

Sub deletezeros()
    Dim c As Range
    Dim searchrange As Range
    Dim i As Long

    Set searchrange = ActiveSheet.Range("A1", ActiveSheet.Range("A65536").End(xlUp))

    For i = searchrange.Cells.Count To 1 Step -1
        Set c = searchrange.Cells(i)
        If c.Value = "0" Then c.EntireRow.delete
    Next i
End Sub

How can I do string interpolation in JavaScript?

Since ES6, you can use template literals:

_x000D_
_x000D_
const age = 3_x000D_
console.log(`I'm ${age} years old!`)
_x000D_
_x000D_
_x000D_

P.S. Note the use of backticks: ``.

Issue with background color and Google Chrome

Never heard of it. Try:

html, body {
  width: 100%;
  height: 100%;
  background-color: #000;
  color: #fff;
  font-family: ...;
}

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Global events are also deprecated.

Here's a patch, which fixes the browser and event issues:

--- jquery.fancybox-1.3.4.js.orig   2010-11-11 23:31:54.000000000 +0100
+++ jquery.fancybox-1.3.4.js    2013-03-22 23:25:29.996796800 +0100
@@ -26,7 +26,9 @@

        titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),

-       isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
+       isIE = !+"\v1",
+       
+       isIE6 = isIE && window.XMLHttpRequest === undefined,

        /*
         * Private methods 
@@ -322,7 +324,7 @@
            loading.hide();

            if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
-               $.event.trigger('fancybox-cancel');
+               $('.fancybox-inline-tmp').trigger('fancybox-cancel');

                busy = false;
                return;
@@ -389,7 +391,7 @@
                        content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
                    };

-                   $.event.trigger('fancybox-change');
+                   $('.fancybox-inline-tmp').trigger('fancybox-change');

                    content
                        .empty()
@@ -612,7 +614,7 @@
            }

            if (currentOpts.type == 'iframe') {
-               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
+               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + (isIE ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
            }

            wrap.show();
@@ -912,7 +914,7 @@

        busy = true;

-       $.event.trigger('fancybox-cancel');
+       $('.fancybox-inline-tmp').trigger('fancybox-cancel');

        _abort();

@@ -957,7 +959,7 @@
            title.empty().hide();
            wrap.hide();

-           $.event.trigger('fancybox-cleanup');
+           $('.fancybox-inline-tmp, select:not(#fancybox-tmp select)').trigger('fancybox-cleanup');

            content.empty();

Can I catch multiple Java exceptions in the same catch clause?

If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:

try {
   ...
} catch (Exception e) {
   someCode();
}

In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}

The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together. Since Java 7, as per @OscarRyz's answer above:

try { 
  ...
} catch( IOException | SQLException ex ) { 
  ...
}

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Update in July 2020:

During the last 16 months, maybe the most notable change in the React community is React hooks.

According to what I observe, in order to gain better compatibility with functional components and hooks, projects (even those large ones) would tend to use:

  1. hook + async thunk (hook makes everything very flexible so you could actually place async thunk in where you want and use it as normal functions, for example, still write thunk in action.ts and then useDispatch() to trigger the thunk: https://stackoverflow.com/a/59991104/5256695),
  2. useRequest,
  3. GraphQL/Apollo useQuery useMutation
  4. react-fetching-library
  5. other popular choices of data fetching/API call libraries, tools, design patterns, etc

In comparison, redux-saga doesn't really provide significant benefit in most normal cases of API calls comparing to the above approaches for now, while increasing project complexity by introducing many saga files/generators (also because the last release v1.1.1 of redux-saga was on 18 Sep 2019, which was a long time ago).

But still, redux-saga provides some unique features such as racing effect and parallel requests. Therefore, if you need these special functionalities, redux-saga is still a good choice.


Original post in March 2019:

Just some personal experience:

  1. For coding style and readability, one of the most significant advantages of using redux-saga in the past is to avoid callback hell in redux-thunk — one does not need to use many nesting then/catch anymore. But now with the popularity of async/await thunk, one could also write async code in sync style when using redux-thunk, which may be regarded as an improvement in redux-thunk.

  2. One may need to write much more boilerplate codes when using redux-saga, especially in Typescript. For example, if one wants to implement a fetch async function, the data and error handling could be directly performed in one thunk unit in action.js with one single FETCH action. But in redux-saga, one may need to define FETCH_START, FETCH_SUCCESS and FETCH_FAILURE actions and all their related type-checks, because one of the features in redux-saga is to use this kind of rich “token” mechanism to create effects and instruct redux store for easy testing. Of course one could write a saga without using these actions, but that would make it similar to a thunk.

  3. In terms of the file structure, redux-saga seems to be more explicit in many cases. One could easily find an async related code in every sagas.ts, but in redux-thunk, one would need to see it in actions.

  4. Easy testing may be another weighted feature in redux-saga. This is truly convenient. But one thing that needs to be clarified is that redux-saga “call” test would not perform actual API call in testing, thus one would need to specify the sample result for the steps which may be used after the API call. Therefore before writing in redux-saga, it would be better to plan a saga and its corresponding sagas.spec.ts in detail.

  5. Redux-saga also provides many advanced features such as running tasks in parallel, concurrency helpers like takeLatest/takeEvery, fork/spawn, which are far more powerful than thunks.

In conclusion, personally, I would like to say: in many normal cases and small to medium size apps, go with async/await style redux-thunk. It would save you many boilerplate codes/actions/typedefs, and you would not need to switch around many different sagas.ts and maintain a specific sagas tree. But if you are developing a large app with much complex async logic and the need for features like concurrency/parallel pattern, or have a high demand for testing and maintenance (especially in test-driven development), redux-sagas would possibly save your life.

Anyway, redux-saga is not more difficult and complex than redux itself, and it does not have a so-called steep learning curve because it has well-limited core concepts and APIs. Spending a small amount of time learning redux-saga may benefit yourself one day in the future.

Java 8 - Difference between Optional.flatMap and Optional.map

Note:- below is the illustration of map and flatmap function, otherwise Optional is primarily designed to be used as a return type only.

As you already may know Optional is a kind of container which may or may not contain a single object, so it can be used wherever you anticipate a null value(You may never see NPE if use Optional properly). For example if you have a method which expects a person object which may be nullable you may want to write the method something like this:

void doSome(Optional<Person> person){
  /*and here you want to retrieve some property phone out of person
    you may write something like this:
  */
  Optional<String> phone = person.map((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}
class Person{
  private String phone;
  //setter, getters
}

Here you have returned a String type which is automatically wrapped in an Optional type.

If person class looked like this, i.e. phone is also Optional

class Person{
  private Optional<String> phone;
  //setter,getter
}

In this case invoking map function will wrap the returned value in Optional and yield something like:

Optional<Optional<String>> 
//And you may want Optional<String> instead, here comes flatMap

void doSome(Optional<Person> person){
  Optional<String> phone = person.flatMap((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}

PS; Never call get method (if you need to) on an Optional without checking it with isPresent() unless you can't live without NullPointerExceptions.

How do I start a program with arguments when debugging?

For Visual Studio Code:

  • Open launch.json file
  • Add args to your configuration:

"args": ["some argument", "another one"],

How to call a method after a delay in Android

There are a lot of ways to do this but the best is to use handler like below

long millisecDelay=3000

Handler().postDelayed({
  // do your work here
 },millisecDelay)

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

Adding default parameter value with type hint in Python

If you're using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

def foo(arg: Optional[int] = None) -> None:
    ...

Is it possible to display my iPhone on my computer monitor?

This is a tool that will help you, i installed it myself

Here is the link

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

Argument list too long error for rm, cp, mv commands

I found that for extremely large lists of files (>1e6), these answers were too slow. Here is a solution using parallel processing in python. I know, I know, this isn't linux... but nothing else here worked.

(This saved me hours)

# delete files
import os as os
import glob
import multiprocessing as mp

directory = r'your/directory'
os.chdir(directory)


files_names = [i for i in glob.glob('*.{}'.format('pdf'))]

# report errors from pool

def callback_error(result):
    print('error', result)

# delete file using system command
def delete_files(file_name):
     os.system('rm -rf ' + file_name)

pool = mp.Pool(12)  
# or use pool = mp.Pool(mp.cpu_count())


if __name__ == '__main__':
    for file_name in files_names:
        print(file_name)
        pool.apply_async(delete_files,[file_name], error_callback=callback_error)

How to get the part of a file after the first line that matches a regular expression?

As a simple approximation you could use

grep -A100000 TERMINATE file

which greps for TERMINATE and outputs up to 100000 lines following that line.

From man page

-A NUM, --after-context=NUM

Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.

Get next / previous element using JavaScript?

use the nextSibling and previousSibling properties:

<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>

document.getElementById('foo2').nextSibling; // #foo3
document.getElementById('foo2').previousSibling; // #foo1

However in some browsers (I forget which) you also need to check for whitespace and comment nodes:

var div = document.getElementById('foo2');
var nextSibling = div.nextSibling;
while(nextSibling && nextSibling.nodeType != 1) {
    nextSibling = nextSibling.nextSibling
}

Libraries like jQuery handle all these cross-browser checks for you out of the box.

How to use the IEqualityComparer

Your GetHashCode implementation always returns the same value. Distinct relies on a good hash function to work efficiently because it internally builds a hash table.

When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1

In your code, the solution is to forward GetHashCode to Class_reglement.Numf.GetHashCode and implement it appropriately there.

Apart from that, your Equals method is full of unnecessary code. It could be rewritten as follows (same semantics, ¼ of the code, more readable):

public bool Equals(Class_reglement x, Class_reglement y)
{
    return x.Numf == y.Numf;
}

Lastly, the ToList call is unnecessary and time-consuming: AddRange accepts any IEnumerable so conversion to a List isn’t required. AsEnumerable is also redundant here since processing the result in AddRange will cause this anyway.


1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

SQL Server 2005 Using DateAdd to add a day to a date

DECLARE @MyDate datetime

-- ... set your datetime's initial value ...'

DATEADD(d, 1, @MyDate)

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

In case it helps anyone, my issue was extremely silly. Totally my fault of course. A notification was triggering a method that was calling the modal. But I wasn't removing the notification correctly, so at some point, I would have more than one notification, so the modal would get called multiple times. Of course, after you call the modal once, the viewcontroller that calls it it's not longer in the view hierarchy, that's why we see this issue. My situation caused a bunch of other issue too, as you would expect.

So to summarize, whatever you're doing make sure the modal is not being called more than once.

the getSource() and getActionCommand()

getActionCommand()

Returns the command string associated with this action. This string allows a "modal" component to specify one of several commands, depending on its state. For example, a single button might toggle between "show details" and "hide details". The source object and the event would be the same in each case, but the command string would identify the intended action.

IMO, this is useful in case you a single command-component to fire different commands based on it's state, and using this method your handler can execute the right lines of code.

JTextField has JTextField#setActionCommand(java.lang.String) method that you can use to set the command string used for action events generated by it.

getSource()

Returns: The object on which the Event initially occurred.

We can use getSource() to identify the component and execute corresponding lines of code within an action-listener. So, we don't need to write a separate action-listener for each command-component. And since you have the reference to the component itself, you can if you need to make any changes to the component as a result of the event.

If the event was generated by the JTextField then the ActionEvent#getSource() will give you the reference to the JTextField instance itself.

sql searching multiple words in a string

Maybe EXISTS can help.

and exists (select 1 from @DocumentNames where pcd.Name like DocName+'%' or CD.DocumentName like DocName+'%')

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

How to reset radiobuttons in jQuery so that none is checked

I know this is old and that this is a little off topic, but supposing you wanted to uncheck only specific radio buttons in a collection:

_x000D_
_x000D_
$("#go").click(function(){_x000D_
    $("input[name='correctAnswer']").each(function(){_x000D_
      if($(this).val() !== "1"){_x000D_
        $(this).prop("checked",false);_x000D_
      }_x000D_
    });_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>_x000D_
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>_x000D_
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>_x000D_
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>_x000D_
<input type="button" id="go" value="go">
_x000D_
_x000D_
_x000D_

And if you are dealing with a radiobutton list, you can use the :checked selector to get just the one you want.

$("#go").click(function(){
  $("input[name='correctAnswer']:checked").prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="correctAnswer" value="1">1</input>
<input id="radio2" type="radio" name="correctAnswer" value="2">2</input>
<input id="radio3" type="radio" name="correctAnswer" value="3">3</input>
<input id="radio4" type="radio" name="correctAnswer" value="4">4</input>
<input type="button" id="go" value="go">

Common sources of unterminated string literal

You might try running the script through JSLint.

MySQL OPTIMIZE all tables?

This bash script will accept the root password as option and optimize it one by one, with status output:

#!/bin/bash

if [ -z "$1" ] ; then
  echo
  echo "ERROR: root password Parameter missing."
  exit
fi
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
TBLLIST=""
COMMA=""
SQL="SELECT CONCAT(table_schema,'.',table_name) FROM information_schema.tables WHERE"
SQL="${SQL} table_schema NOT IN ('information_schema','mysql','performance_schema')"
for DBTB in `mysql ${MYSQL_CONN} -ANe"${SQL}"`
do
    echo OPTIMIZE TABLE "${DBTB};"
    SQL="OPTIMIZE TABLE ${DBTB};"
    mysql ${MYSQL_CONN} -ANe"${SQL}"
done

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

You can use the template syntax of ngFor on groups and the usual syntax inside it for the actual rows like:

<table>
  <template let-group ngFor [ngForOf]="groups">
    <tr *ngFor="let row of group.items">{{row}}</tr>
  </template>
</table>

Check this plunk