Programs & Examples On #Uiactivityindicatorview

On iOS, you can use an activity indicator to show that a task is in progress. An activity indicator appears as a “gear” that is either spinning or stopped. You control when an activity indicator animates by calling the startAnimating and stopAnimating methods. To automatically hide the activity indicator when animation stops, set the hidesWhenStopped property to YES.

How to use pull to refresh in Swift?

I would like to mention a PRETTY COOL feature that has been included since iOS 10, which is:

For now, UIRefreshControl is directly supported in each of UICollectionView, UITableView and UIScrollView!

Each one of these views have refreshControl instance property, which means that there is no longer a need to add it as a subview in your scroll view, all you have to do is:

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(doSomething), for: .valueChanged)

    // this is the replacement of implementing: "collectionView.addSubview(refreshControl)"
    collectionView.refreshControl = refreshControl
}

func doSomething(refreshControl: UIRefreshControl) {
    print("Hello World!")

    // somewhere in your code you might need to call:
    refreshControl.endRefreshing()
}

Personally, I find it more natural to treat it as a property for scroll view more than add it as a subview, especially because the only appropriate view to be as a superview for a UIRefreshControl is a scrollview, i.e the functionality of using UIRefreshControl is only useful when working with a scroll view; That's why this approach should be more obvious to setup the refresh control view.

However, you still have the option of using the addSubview based on the iOS version:

if #available(iOS 10.0, *) {
  collectionView.refreshControl = refreshControl
} else {
  collectionView.addSubview(refreshControl)
}

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

Combine two integer arrays

NOTE: didn't test it

int[] concatArray(int[] a, int[] b) {
  int[] c = new int[a.length + b.length];
  int i = 0;
  for (int x : a) { c[i] = x; i ++; }
  for (int x : b) { c[i] = x; i ++; }
  return c;
}

Using malloc for allocation of multi-dimensional arrays with different row lengths

First, you need to allocate array of pointers like char **c = malloc( N * sizeof( char* )), then allocate each row with a separate call to malloc, probably in the loop:


/* N is the number of rows  */
/* note: c is char** */
if (( c = malloc( N*sizeof( char* ))) == NULL )
{ /* error */ }

for ( i = 0; i < N; i++ )
{
  /* x_i here is the size of given row, no need to
   * multiply by sizeof( char ), it's always 1
   */
  if (( c[i] = malloc( x_i )) == NULL )
  { /* error */ }

  /* probably init the row here */
}

/* access matrix elements: c[i] give you a pointer
 * to the row array, c[i][j] indexes an element
 */
c[i][j] = 'a';

If you know the total number of elements (e.g. N*M) you can do this in a single allocation.

Password Protect a SQLite DB. Is it possible?

Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.

How to replace all dots in a string using JavaScript

Here's another implementation of replaceAll. Hope it helps someone.

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

Then you can use it:

var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

Change Default branch in gitlab

in the GitLab Enterprise Edition 12.2.0-pre you have to use following: Setting ? Repository ? Default Branch ( expand it) and change the default branch Here

Cannot connect to local SQL Server with Management Studio

Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.

Frontend tool to manage H2 database

If you are running it as an embedded database in spring I use the following configuration to enable the built in web client when the main app is running:

<!-- Run H2 web server within application that will access the same in-memory database -->
<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,-webPort,8082"/>
</bean>

Set android shape color programmatically

Nothing work for me but when i set tint color it works on Shape Drawable

 Drawable background = imageView.getBackground();
 background.setTint(getRandomColor())

require android 5.0 API 21

Dynamic height for DIV

You should be okay to just take the height property out of the CSS.

Node.js check if path is file or directory

The answers above check if a filesystem contains a path that is a file or directory. But it doesn't identify if a given path alone is a file or directory.

The answer is to identify directory-based paths using "/." like --> "/c/dos/run/." <-- trailing period.

Like a path of a directory or file that has not been written yet. Or a path from a different computer. Or a path where both a file and directory of the same name exists.

// /tmp/
// |- dozen.path
// |- dozen.path/.
//    |- eggs.txt
//
// "/tmp/dozen.path" !== "/tmp/dozen.path/"
//
// Very few fs allow this. But still. Don't trust the filesystem alone!

// Converts the non-standard "path-ends-in-slash" to the standard "path-is-identified-by current "." or previous ".." directory symbol.
function tryGetPath(pathItem) {
    const isPosix = pathItem.includes("/");
    if ((isPosix && pathItem.endsWith("/")) ||
        (!isPosix && pathItem.endsWith("\\"))) {
        pathItem = pathItem + ".";
    }
    return pathItem;
}
// If a path ends with a current directory identifier, it is a path! /c/dos/run/. and c:\dos\run\.
function isDirectory(pathItem) {
    const isPosix = pathItem.includes("/");
    if (pathItem === "." || pathItem ==- "..") {
        pathItem = (isPosix ? "./" : ".\\") + pathItem;
    }
    return (isPosix ? pathItem.endsWith("/.") || pathItem.endsWith("/..") : pathItem.endsWith("\\.") || pathItem.endsWith("\\.."));
} 
// If a path is not a directory, and it isn't empty, it must be a file
function isFile(pathItem) {
    if (pathItem === "") {
        return false;
    }
    return !isDirectory(pathItem);
}

Node version: v11.10.0 - Feb 2019

Last thought: Why even hit the filesystem?

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

It's because the tab is a naming container aswell... your update should be update="Search:insTable:display" What you can do aswell is just place your dialog outside the form and still inside the tab then it would be: update="Search:display"

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

How to use sbt from behind proxy?

If you are using a Proxy which requires authentication, I have a solution for you :)

As @Faiz explained above, SBT has a very hard time handling proxy requiring authentication. The solution is to bypass this authentication, if you cannot turn off your proxy on demand (corporate proxy for example). To do so, I suggest you use a squid proxy, and configure it with your username and password to access your corporate proxy. See : https://doc.ubuntu-fr.org/squid Then, you can set JAVA_OPTS or SBT_OPTS environment variables so that SBT connects to your own local squid proxy instead of your corporate proxy :

export JAVA_OPTS = "-Dhttps.proxyHost=localhost -Dhttps.proxyPort=3128 -Dhttp.proxyHost=localhost -Dhttp.proxyPort=3128"

(just c/c this in your bashrc without modifying anything and it should work fine).

The trick is that Squid Proxy does not require any authentication, and acts as an intermediate between SBT and your other proxy.

If you have troubles in applying this advise, please let me know.

Regards,

Edgar

Hash function that produces short hashes?

If you don't need an algorithm that's strong against intentional modification, I've found an algorithm called adler32 that produces pretty short (~8 character) results. Choose it from the dropdown here to try it out:

http://www.sha1-online.com/

Array String Declaration

use:

String[] mStrings = new String[title.length];

How to prevent column break within an element?

<style>
ul li{display: table;}  
</style>

works perfectly

How can I make my own event in C#?

You can declare an event with the following code:

public event EventHandler MyOwnEvent;

A custom delegate type instead of EventHandler can be used if needed.

You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).

How do I create a datetime in Python from milliseconds?

Converting millis to datetime (UTC):

import datetime
time_in_millis = 1596542285000
dt = datetime.datetime.fromtimestamp(time_in_millis / 1000.0, tz=datetime.timezone.utc)

Converting datetime to string following the RFC3339 standard (used by Open API specification):

from rfc3339 import rfc3339
converted_to_str = rfc3339(dt, utc=True, use_system_timezone=False)
# 2020-08-04T11:58:05Z

Android: Pass data(extras) to a fragment

Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int value to a fragment I would create a bundle, put the int into that bundle, and then set that bundle as an argument to be used when the fragment was created.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:

Bundle bundle = this.getArguments();
if (bundle != null) {
    int i = bundle.getInt(key, defaulValue);
}

What you are getting changes depending on what you put. Also the default value is usually null but does not need to be. It depends on if you set a default value for that argument.

Lastly I do not think you can do this in onCreateView. I think you must retrieve this data within your fragment's onActivityCreated method. My reasoning is as follows. onActivityCreated runs after the underlying activity has finished its own onCreate method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate method, it will not exist during your fragment's onCreateView. Try using this in onActivityCreated and just update your ListView contents later.

How to change ViewPager's page?

I'm not sure that I fully understand the question, but from the title of your question, I'm guessing that what you're looking for is pager.setCurrentItem( num ). That allows you to programatically switch to another page within the ViewPager.

I'd need to see a stack trace from logcat to be more specific if this is not the problem.

How do I bind onchange event of a TextBox using JQuery?

if you're trying to use jQuery autocomplete plugin, then I think you don't need to bind to onChange event, it will

Multiple queries executed in java in single statement

Why dont you try and write a Stored Procedure for this?

You can get the Result Set out and in the same Stored Procedure you can Insert what you want.

The only thing is you might not get the newly inserted rows in the Result Set if you Insert after the Select.

no target device found android studio 2.1.1

trick that works for me when target device not found:

  • click the "attach debugger to android process" button. (that will enable adb integration for you)

  • click the run button

col align right

For Bootstrap 4 I find the following very handy because:

  • the column on the right takes exactly the space it needs and will pull right
  • while the left col always gets the maximum amount of space!.

It is the combination of col and col-auto which does the magic. So you don't have to define a col width (like col-2,...)

<div class="row">
    <div class="col">Left</div>
    <div class="col-auto">Right</div>
</div>

Ideal for aligning words, icons, buttons,... to the right.

An example to have this responsive on small devices:

<div class="row">
    <div class="col">Left</div>
    <div class="col-12 col-sm-auto">Right (Left on small)</div>
</div>

Check this Fiddle https://jsfiddle.net/Julesezaar/tx08zveL/

Formatting PowerShell Get-Date inside string

You can use the -f operator

$a = "{0:D}" -f (get-date)
$a = "{0:dddd}" -f (get-date)

Spécificator    Type                                Example (with [datetime]::now)
d   Short date                                        26/09/2002
D   Long date                                       jeudi 26 septembre 2002
t   Short Hour                                      16:49
T   Long Hour                                       16:49:31
f   Date and hour                                   jeudi 26 septembre 2002 16:50
F   Long Date and hour                              jeudi 26 septembre 2002 16:50:51
g   Default Date                                    26/09/2002 16:52
G   Long default Date and hour                      26/09/2009 16:52:12
M   Month Symbol                                    26 septembre
r   Date string RFC1123                             Sat, 26 Sep 2009 16:54:50 GMT
s   Sortable string date                            2009-09-26T16:55:58
u   Sortable string date universal local hour       2009-09-26 16:56:49Z
U   Sortable string date universal GMT hour         samedi 26 septembre 2009 14:57:22 (oups)
Y   Year symbol                                     septembre 2002

Spécificator    Type                       Example      Output Example
dd              Jour                       {0:dd}       10
ddd             Name of the day            {0:ddd}      Jeu.
dddd            Complet name of the day    {0:dddd}     Jeudi
f, ff, …        Fractions of seconds       {0:fff}      932
gg, …           position                   {0:gg}       ap. J.-C.
hh              Hour two digits            {0:hh}       10
HH              Hour two digits (24 hours) {0:HH}       22
mm              Minuts 00-59               {0:mm}       38
MM              Month 01-12                {0:MM}       12
MMM             Month shortcut             {0:MMM}      Sep.
MMMM            complet name of the month  {0:MMMM}     Septembre
ss              Seconds 00-59              {0:ss}       46
tt              AM or PM                   {0:tt}       ““
yy              Years, 2 digits            {0:yy}       02
yyyy            Years                      {0:yyyy}     2002
zz              Time zone, 2 digits        {0:zz}       +02
zzz             Complete Time zone         {0:zzz}      +02:00
:               Separator                  {0:hh:mm:ss}     10:43:20
/               Separator                  {0:dd/MM/yyyy}   10/12/2002

How to form a correct MySQL connection string?

string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

Following what @viveknuna suggested, I upgraded to the latest version of node.js and npm using the downloaded installer. I also installed the latest version of yarn using a downloaded installer. Then, as you can see below, I upgraded angular-cli and typescript. Here's what that process looked like:

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g @angular/cli@latest
C:\Users\Jack\AppData\Roaming\npm\ng -> C:\Users\Jack\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@angular\cli\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ @angular/[email protected]
added 75 packages, removed 166 packages, updated 61 packages and moved 24 packages in 29.084s

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g typescript
C:\Users\Jack\AppData\Roaming\npm\tsserver -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\Jack\AppData\Roaming\npm\tsc -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ [email protected]
updated 1 package in 2.427s

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>node -v
v8.10.0

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm -v
5.6.0

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn --version
1.5.1

Thereafter, I ran yarn and npm start in my angular folder and all appears to be well. Here's what that looked like:

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn
yarn install v1.5.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "@angular/cli > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning "@angular/cli > @angular-devkit/schematics > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning " > [email protected]" has incorrect peer dependency "@angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0".
warning " > [email protected]" has incorrect peer dependency "@angular/core@^2.3.1 || >=4.0.0-beta <5.0.0".
[4/4] Building fresh packages...
Done in 232.79s.

D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm start

> [email protected] start D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular
> ng serve --host 0.0.0.0 --port 4200

** NG Live Development Server is listening on 0.0.0.0:4200, open your browser on http://localhost:4200/ **
Date: 2018-03-22T13:17:28.935Z
Hash: 8f226b6fa069b7c201ea
Time: 22494ms
chunk {account.module} account.module.chunk.js () 129 kB  [rendered]
chunk {app.module} app.module.chunk.js () 497 kB  [rendered]
chunk {common} common.chunk.js (common) 1.46 MB  [rendered]
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 515 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.1 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.53 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 15.1 MB [initial] [rendered]

webpack: Compiled successfully.

Is it possible to clone html element objects in JavaScript / JQuery?

With native JavaScript:

newelement = element.cloneNode(bool)

where the Boolean indicates whether to clone child nodes or not.

Here is the complete documentation on MDN.

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

What does the servlet <load-on-startup> value signify

Servlet Life Cycle

The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.

  1. If an instance of the servlet does not exist, the web container:

    a. Loads the servlet class

    b. Creates an instance of the servlet class

    c. Initializes the servlet instance by calling the init method (initialization is covered in Creating and Initializing a Servlet)

  2. The container invokes the service method, passing request and response objects. Service methods are discussed in Writing Service Methods.

A 0 value on load-on-startup means that point 1 is executed when a request comes to that servlet. Other values means that point 1 is executed at container startup.

Reset the database (purge all), then seed a database

You can use rake db:reset when you want to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following: Drop the database: rake db:drop Load the schema: rake db:schema:load Seed the data: rake db:seed

But if you want to completely drop your database you can use rake db:drop. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.

This is a detailed article about the most important rake database commands.

What's "tools:context" in Android layout files?

tools:context=".MainActivity" thisline is used in xml file which indicate that which java source file is used to access this xml file. it means show this xml preview for perticular java files.

Pretty printing XML in Python

XML pretty print for python looks pretty good for this task. (Appropriately named, too.)

An alternative is to use pyXML, which has a PrettyPrint function.

Flattening a shallow list in Python

If you're just looking to iterate over a flattened version of the data structure and don't need an indexable sequence, consider itertools.chain and company.

>>> list_of_menuitems = [['image00', 'image01'], ['image10'], []]
>>> import itertools
>>> chain = itertools.chain(*list_of_menuitems)
>>> print(list(chain))
['image00', 'image01', 'image10']

It will work on anything that's iterable, which should include Django's iterable QuerySets, which it appears that you're using in the question.

Edit: This is probably as good as a reduce anyway, because reduce will have the same overhead copying the items into the list that's being extended. chain will only incur this (same) overhead if you run list(chain) at the end.

Meta-Edit: Actually, it's less overhead than the question's proposed solution, because you throw away the temporary lists you create when you extend the original with the temporary.

Edit: As J.F. Sebastian says itertools.chain.from_iterable avoids the unpacking and you should use that to avoid * magic, but the timeit app shows negligible performance difference.

how to make password textbox value visible when hover an icon

<html>
<head>
</head>
<body>
<script>
function demo(){
    var d=document.getElementById('s1');
    var e=document.getElementById('show_f').value;
    var f=document.getElementById('show_f').type; 

    if(d.value=="show"){
        var f= document.getElementById('show_f').type="text";
        var g=document.getElementById('show_f').value=e;
        d.value="Hide";

    } else{
        var f= document.getElementById('show_f').type="password";
        var g=document.getElementById('show_f').value=e;
        d.value="show";
     }     
  }   
</script>   

<form method='post'>
Password: <input type='password' name='pass_f' maxlength='30' id='show_f'><input type="button" onclick="demo()" id="s1" value="show" style="height:25px; margin-left:5px;margin-top:3px;"><br><br>
<input type='submit' name='sub' value='Submit Now'>

</form>
</body>
</html>

Foreign keys in mongo?

Short answer: You should to use "weak references" between collections, using ObjectId properties:

References store the relationships between data by including links or references from one document to another. Applications can resolve these references to access the related data. Broadly, these are normalized data models.

https://docs.mongodb.com/manual/core/data-modeling-introduction/#references

This will of course not check any referential integrity. You need to handle "dead links" on your side (application level).

Hadoop/Hive : Loading data from .csv on a local machine

Let me work you through the following simple steps:

Steps:

First, create a table on hive using the field names in your csv file. Lets say for example, your csv file contains three fields (id, name, salary) and you want to create a table in hive called "staff". Use the below code to create the table in hive.

hive> CREATE TABLE Staff (id int, name string, salary double) row format delimited fields terminated by ',';

Second, now that your table is created in hive, let us load the data in your csv file to the "staff" table on hive.

hive>  LOAD DATA LOCAL INPATH '/home/yourcsvfile.csv' OVERWRITE INTO TABLE Staff;

Lastly, display the contents of your "Staff" table on hive to check if the data were successfully loaded

hive> SELECT * FROM Staff;

Thanks.

python: urllib2 how to send cookie with urlopen request

Maybe using cookielib.CookieJar can help you. For instance when posting to a page containing a form:

import urllib2
import urllib
from cookielib import CookieJar

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

EDIT:

After Piotr's comment I'll elaborate a bit. From the docs:

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

So whatever requests you make with your CookieJar instance, all cookies will be handled automagically. Kinda like your browser does :)

I can only speak from my own experience and my 99% use-case for cookies is to receive a cookie and then need to send it with all subsequent requests in that session. The code above handles just that, and it does so transparently.

Have bash script answer interactive prompts

If you only have Y to send :

$> yes Y |./your_script

If you only have N to send :

$> yes N |./your_script

Is there a free GUI management tool for Oracle Database Express?

There are a few options:

  • Database.net is a windows GUI to connect to many different types of databases, oracle included.
  • Oracle SQL Developer is a free tool from Oracle.
  • SQuirreL SQL is a java based client that can connect to any database that uses JDBC drivers.

I'm sure there are others out there that you could use too...

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

@ChrisPratt's answer about the use of Display Template is wrong. The correct code to make it work is:

@model DateTime?

@if (Model.HasValue)
{
    @Convert.ToDateTime(Model).ToString("MM/dd/yyyy")
}

That's because .ToString() for Nullable<DateTime> doesn't accept Format parameter.

Should we @Override an interface's method implementation?

You should always annotate methods with @Override if it's available.

In JDK 5 this means overriding methods of superclasses, in JDK 6, and 7 it means overriding methods of superclasses, and implementing methods of interfaces. The reason, as mentioned previously, is it allows the compiler to catch errors where you think you are overriding (or implementing) a method, but are actually defining a new method (different signature).

The equals(Object) vs. equals(YourObject) example is a standard case in point, but the same argument can be made for interface implementations.

I'd imagine the reason it's not mandatory to annotate implementing methods of interfaces is that JDK 5 flagged this as a compile error. If JDK 6 made this annotation mandatory, it would break backwards compatibility.

I am not an Eclipse user, but in other IDEs (IntelliJ), the @Override annotation is only added when implementing interface methods if the project is set as a JDK 6+ project. I would imagine that Eclipse is similar.

However, I would have preferred to see a different annotation for this usage, maybe an @Implements annotation.

Django. Override save for model

In new version it is like this:

def validate(self, attrs):
    has_unknown_fields = set(self.initial_data) - set(self.fields.keys())
    if has_unknown_fields:
        raise serializers.ValidationError("Do not send extra fields")
    return attrs

excel delete row if column contains value from to-remove-list

Given sheet 2:

ColumnA
-------
apple
orange

You can flag the rows in sheet 1 where a value exists in sheet 2:

ColumnA  ColumnB
-------  --------------
pear     =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple    =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry   =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange   =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum     =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")

The resulting data looks like this:

ColumnA  ColumnB
-------  --------------
pear     Keep
apple    Delete
cherry   Keep
orange   Delete
plum     Keep

You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.

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

I solved the issue by using overflow-x:hidden; as follows

@media screen and (max-width: 441px){

#end_screen { (NOte:-the end_screen is the wrapper div for all other div's inside it.)
  overflow-x: hidden;
   }
 }

structure is as follows

1st div end_screen >> inside it >> end_screen_2(div) >> inside it >> end_screen_2.

'end_screen is the wrapper of end_screen_1 and end_screen_2 div's

Visual C++: How to disable specific linker warnings?

The PDB file is typically used to store debug information. This warning is caused probably because the file vc80.pdb is not found when linking the target object file. Read the MSDN entry on LNK4099 here.

Alternatively, you can turn off debug information generation from the Project Properties > Linker > Debugging > Generate Debug Info field.

How to check db2 version

For DB2:

"SELECT * FROM SYSIBMADM.ENV_INST_INFO" - SERVICE_LEVEL

Get the new record primary key ID from MySQL insert query?

If you are using PHP: On a PDO object you can simple invoke the lastInsertId method after your insert.

Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

The cleanest approach is to use the Array#concat method; it will not create a new array (unlike Array#+ which will do the same thing but create a new array).

Straight from the docs (http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-concat):

concat(other_ary)

Appends the elements of other_ary to self.

So

[1,2].concat([3,4])  #=> [1,2,3,4]  

Array#concat will not flatten a multidimensional array if it is passed in as an argument. You'll need to handle that separately:

arr= [3,[4,5]]
arr= arr.flatten   #=> [3,4,5]
[1,2].concat(arr)  #=> [1,2,3,4,5]

Lastly, you can use our corelib gem (https://github.com/corlewsolutions/corelib) which adds useful helpers to the Ruby core classes. In particular we have an Array#add_all method which will automatically flatten multidimensional arrays before executing the concat.

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

public String read(InputStream in) throws IOException {
    try (BufferedReader buffer = new BufferedReader(new InputStreamReader(in))) {
        return buffer.lines().collect(Collectors.joining("\n"));
    }
}

how to remove the bold from a headline?

for "THIS IS" not to be bold - add <span></span> around the text

<h1>><span>THIS IS</span> A HEADLINE</h1>

and in style

h1 span{font-weight:normal}

How can I enable the MySQLi extension in PHP 7?

The problem is that the package that used to connect PHP to MySQL is deprecated (php5-mysql). If you install the new package,

sudo apt-get install php-mysql

this will automatically update Apache and PHP 7.

How do I use a C# Class Library in a project?

There are necessary steps that are missing in the above answers to work for all levels of devs:

  1. compile your class library project
  2. the dll file will be available in the bin folder
  3. in another project, right click ProjectName and select "Add" => "Existing Item"
  4. Browser to the bin folder of the class library project and select the dll file (3 & 4 steps are important if you plan to ship your app to other machines)
  5. as others mentioned, add reference to the dll file you "just" added to your project
  6. as @Adam mentioned, just call the library name from anywhere in your program, you do not need a using statement

.attr('checked','checked') does not work

I don't think you can call

$.attr('checked',true);

because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!

How to test for $null array in PowerShell

How do you want things to behave?

If you want arrays with no elements to be treated the same as unassigned arrays, use:

[array]$foo = @() #example where we'd want TRUE to be returned
@($foo).Count -eq 0

If you want a blank array to be seen as having a value (albeit an empty one), use:

[array]$foo = @() #example where we'd want FALSE to be returned
$foo.PSObject -eq $null

If you want an array which is populated with only null values to be treated as null:

[array]$foo = $null,$null
@($foo | ?{$_.PSObject}).Count -eq 0 

NB: In the above I use $_.PSObject over $_ to avoid [bool]$false, [int]0, [string]'', etc from being filtered out; since here we're focussed solely on nulls.

How to install .MSI using PowerShell

When trying to silently install an MSI via PowerShell using this command:

Start-Process $webDeployInstallerFilePath -ArgumentList '/quiet' -Wait

I was getting the error:

The specified executable is not a valid application for this OS platform.

I instead switched to using msiexec.exe to execute the MSI with this command, and it worked as expected:

$arguments = "/i `"$webDeployInstallerFilePath`" /quiet"
Start-Process msiexec.exe -ArgumentList $arguments -Wait

Hopefully others find this useful.

Android device is not connected to USB for debugging (Android studio)

For me, this simple trick worked:

I actually enabled and disabled the listed USB Adapter for android in the device manager (Control Panel -> Hardware & Sound -> Device Manager). And holy moly it's working! :D

jQuery issue - #<an Object> has no method

For anyone else arriving at this question:

I was performing the most simple jQuery, trying to hide an element:

('#fileselection').hide();

and I was getting the same type of error, "Uncaught TypeError: Object #fileselection has no method 'hide'

Of course, now it is obvious, but I just left off the jQuery indicator '$'. The code should have been:

$('#fileselection').hide();

This fixes the no-brainer problem. I hope this helps someone save a few minutes debugging!

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

Replacing a character from a certain index

You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.

>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'

Convert output of MySQL query to utf8

SELECT CONVERT(CAST(column as BINARY) USING utf8) as column FROM table 

How to get the list of all installed color schemes in Vim?

Another simpler way is while you are editing a file - tabe ~/.vim/colors/ ENTER Will open all the themes in a new tab within vim window.

You may come back to the file you were editing using - CTRL + W + W ENTER

Note: Above will work ONLY IF YOU HAVE a .vim/colors directory within your home directory for current $USER (I have 70+ themes)

[user@host ~]$ ls -l ~/.vim/colors | wc -l

72

gdb: how to print the current line or find the current line number?

I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.

Try compiling with -g3 remove any optimization flag. Then it might work. HTH!

What is a LAMP stack?

There are various technological stacks present. Have a look:

LAMP:

Linux
Apache
MySQL
PHP

WAMP:

Windows
Apache
MySQL
PHP

MAMP:

Mac operating system
Apache web server
MySQL as database
PHP for scripting

XAMPP:

X is cross-platform
Apache
MySQL
PHP
Perl

MEAN:

MongoDB
Express.js
Angular
Node.js

MERN:

MongoDB
Express.js
React
Node.js

Is try-catch like error handling possible in ASP Classic?

Some scenarios don't always allow developers to switch scripting language.

My preference is definitely for JavaScript (and I have used it in new projects). However, maintaining older projects is still required and necessary. Unfortunately, these are written in VBScript.

So even though this solution doesn't offer true "try/catch" functionaility, the result is the same, and that's good enough for me to get the job done.

jQuery: enabling/disabling datepicker

try this :

$("#form").datetimepicker("disable");

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Python for and if on one line

The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:

arr = []
for i in array :
    if i == "two" :
        arr.push(i)
print(i)

You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.

The english equivalent of what you are doing is:

You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"

The reason 'i' is equal to "three" is because three was the last thing that was defined as I

the computer did:

i = "one"
i = "two"
i = "three"

print(["two"])

Because you asked it to.

If you want the index, go here If you want the values in an array, define the array, like this:

MyArray = [(i) for i in my_list if i=="two"]

How can I properly handle 404 in ASP.NET MVC?

ASP.NET MVC doesn't support custom 404 pages very well. Custom controller factory, catch-all route, base controller class with HandleUnknownAction - argh!

IIS custom error pages are better alternative so far:

web.config

<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" />
    <error statusCode="404" responseMode="ExecuteURL" path="/Error/PageNotFound" />
  </httpErrors>
</system.webServer>

ErrorController

public class ErrorController : Controller
{
    public ActionResult PageNotFound()
    {
        Response.StatusCode = 404;
        return View();
    }
}

Sample Project

How to get input from user at runtime

`DECLARE
c_id customers.id%type := &c_id;
c_name customers.name%type;
c_add customers.address%type;
c_sal customers.salary%type;
a integer := &a`   

Here c_id customers.id%type := &c_id; statement inputs the c_id with type already defined in the table and statement a integer := &a just input integer in variable a.

Promise.all().then() resolve?

But that doesn't seem like the proper way to do it..

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("First handler", data);_x000D_
    return data.map(entry => entry * 10);_x000D_
  })_x000D_
  .then(data => {_x000D_
    console.log("Second handler", data);_x000D_
  });
_x000D_
_x000D_
_x000D_

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

The output we see from that is:

First handler [1,2]
Second handler [10,20]

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

If the additional work you're doing is synchronous, you can also put it in the first handler:

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("Initial data", data);_x000D_
    data = data.map(entry => entry * 10);_x000D_
    console.log("Updated data", data);_x000D_
    return data;_x000D_
  });
_x000D_
_x000D_
_x000D_

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

Responsive image align center bootstrap 3

I would suggest a more "abstract" classification. Add a new class "img-center" which can be used in combination with .img-responsive class:

// Center responsive images
.img-responsive.img-center {
  margin: 0 auto;
}

Add common prefix to all cells in Excel

Michael.. if its just for formatting then you can format the cell to append any value.

Just right click and select Format Cell on the context menu, select custom and then specify type as you wish... for above example it would be X0. Here 'X' is the prefix and 0 is the numeric after.

Hope this helps..

Cheers...

C++, copy set to vector

You need to use a back_inserter:

std::copy(input.begin(), input.end(), std::back_inserter(output));

std::copy doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy, you must make sure it points to a range that is at least large enough to hold the input range.

std::back_inserter creates an output iterator that calls push_back on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector to hold the range being copied:

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

Or, you could use the std::vector range constructor:

std::vector<double> output(input.begin(), input.end()); 

Jetty: HTTP ERROR: 503/ Service Unavailable

Remove/Delete the project from workspace. and Reimport the project to the workspace. This method worked for me.

Validate that a string is a positive integer

My function checks if number is +ve and could be have decimal value as well.

       function validateNumeric(numValue){
            var value = parseFloat(numValue);
            if (!numValue.toString().match(/^[-]?\d*\.?\d*$/)) 
                    return false;
            else if (numValue < 0) {
                return false;
            }
            return true;        
        }

Why does corrcoef return a matrix?

The function Correlate of numpy works with 2 1D arrays that you want to correlate and returns one correlation value.

ssh: check if a tunnel is alive

We can check using ps command

# ps -aux | grep ssh

Will show all shh service running and we can find the tunnel service listed

An object reference is required to access a non-static member

playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).

To solve your problem you can either make audioSounds static:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:

SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
    if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
    {
        playsound = true;
    }
}

asp.net: How can I remove an item from a dropdownlist?

I have Done Like this, i have remove all items except the value coming as 1 and 3.

ListItemCollection liCol = ddlcustomertype.Items;
for (int i = 0; i < liCol.Count;i++ )
{
    ListItem li = liCol[i];
    if (li.Value != "1" || li.Value != "3")
        ddlcustomertype.Items.Remove(li);
}

Windows Forms - Enter keypress activates submit button?

The Form has a KeyPreview property that you can use to intercept the keypress.

java.lang.UnsupportedClassVersionError

Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions

error: (-215) !empty() in function detectMultiScale

You just need to add proper path of the haarcascade_frontalface_default.xml file i.e. you only have to add prefix (cv2.data.haarcascades)

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

Cannot create Maven Project in eclipse

It worked for = I just removed "archetypes" folder from below location

C:\Users\Lenovo.m2\repository\org\apache\maven

But you may change following for experiment - download latest binary zip of Maven, add to you C:\ drive and change following....

enter image description here

enter image description here

enter image description here

Change Proxy

 <proxy>
          <id>optional</id>
          <active>true</active>
          <protocol>http</protocol>
          <username></username>
          <password></password>
          <host>10.23.73.253</host>
          <port>8080</port>
          <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
        </proxy>

git pull error :error: remote ref is at but expected

Unfortunately GIT commands like prune and reset or push didn't work for me. Prune worked once and then the issue returned.

The permanent solution which worked for me is to edit a git file manually. Just go to the project's .git folder and then open the file packed-refs in a text editor like Notepad++. Then navigate to the row with the failing branch and update its guid to the expected one.

If you have a message like:

error: cannot lock ref 'refs/remotes/origin/feature/branch_xxx': is at 425ea23facf96f51f412441f41ad488fc098cf23 but expected 383de86fed394ff1a1aeefc4a522d886adcecd79

then in the file find the row with refs/remotes/origin/feature/branch_xxx. The guid there will be the expected (2nd) one - 383de86fed394ff1a1aeefc4a522d886adcecd79. You need to change it to the real (1st) one - 425ea23facf96f51f412441f41ad488fc098cf23.

Repeat for the other failing branches and you'll be good to proceed. Sometimes after re-fetch I had to repeat for the same branches which i already 'fixed' earlier. On re-fetch GIT updates guids and gives you the latest one.

Anyways the issue isn't a show stopper. The branch list gets updated. This is rather a warning.

Add Bean Programmatically to Spring Web App Context

First initialize Property values

MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());

DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);

context.registerBeanDefinition("beanName", connectionFactory);

Add to the list of beans

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));

Best way to check that element is not present using Selenium WebDriver with java

WebElement element = driver.findElement(locator);
Assert.assertNull(element);

The above assertion will pass if element is not present.

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

Regex to test if string begins with http:// or https://

Case insensitive:

var re = new RegExp("^(http|https)://", "i");
var str = "My String";
var match = re.test(str);

Why can't overriding methods throw exceptions broader than the overridden method?

The subclass's overriding method can only throw multiple checked exceptions that are subclasses of the superclass's method's checked exception, but cannot throw multiple checked exceptions that are unrelated to the superclass's method's checked exception

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

iPad WebApp Full Screen in Safari

This site has a working workaround, same effect, uses some javascript to set the first child div to total height of viewport. http://webapp-net.com/Demo/Index.html

Keras model.summary() result - Understanding the # of Parameters

For Dense Layers:

output_size * (input_size + 1) == number_parameters 

For Conv Layers:

output_channels * (input_channels * window_size + 1) == number_parameters

Consider following example,

model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
Conv2D(128, (3, 3), activation='relu'),
Dense(num_classes, activation='softmax')
])

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 32)      896       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 64)      18496     
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 218, 218, 128)     73856     
_________________________________________________________________
dense_9 (Dense)              (None, 218, 218, 10)      1290      
=================================================================

Calculating params,

assert 32 * (3 * (3*3) + 1) == 896
assert 64 * (32 * (3*3) + 1) == 18496
assert 128 * (64 * (3*3) + 1) == 73856
assert num_classes * (128 + 1) == 1290

What is VanillaJS?

This word, hence, VanillaJS is a just damn joke that changed my life. I had gone to a German company for an interview, I was very poor in JavaScript and CSS, very poor, so the Interviewer said to me: We're working here with VanillaJs, So you should know this framework.

Definitely, I understood that I'was rejected, but for one week I seek for VanillaJS, After all, I found THIS LINK.

What I am just was because of that joke.

VanillaJS === plain `JavaScript`

Tesseract OCR simple example

In my case I had all these worked except for the correct character recognition.

But you need to consider these few things:

  • Use correct tessnet2 library
  • use correct tessdata language version
  • tessdata should be somewhere out of your application folder where you can put in full path in the init parameter. use ocr.Init(@"c:\tessdata", "eng", true);
  • Debugging will cause you headache. Then you need to update your app.config use this. (I can't put the xml code here. give me your email i will email it to you)

hope that this helps

Create view with primary key?

A little late to this party - but this also works well:

CREATE VIEW [ABC].[View_SomeDataUniqueKey]
AS
SELECT 
CAST(CONCAT(CAST([ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY [ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,[ID]
FROM SOME_TABLE JOIN SOME_OTHER_TABLE
GO

In my case the join resulted in [ID] - the primary key being repeated up to 5 times (associated different unique data) The nice trick with this is that the original ID can be determined from each UniqueID effectively [ID]+RowNumber() = 11, 12, 13, 14, 21, 22, 23, 24 etc. If you add RowNumber() and [ID] back into the view - you can easily determine your original key from the data. But - this is not something that should be committed to a table because I am fairly sure that the RowNumber() of a view will never be reliably the same as the underlying data alters, even with the OVER(ORDER BY [ID] ASC) to try and help it.

Example output ( Select UniqueId, ID, ROWNR, Name from [REF].[View_Systems] ) :

UniqueId ID ROWNR Name 11 1 1 Amazon A 12 1 2 Amazon B 13 1 3 Amazon C 14 1 4 Amazon D 15 1 5 Amazon E

Table1:

[ID] [Name] 1 Amazon

Table2:

[ID] [Version] 1 A 1 B 1 C 1 D 1 E

CREATE VIEW [REF].[View_Systems]
AS    
SELECT 
CAST(CONCAT(CAST(TABA.[ID] AS VARCHAR(4)), 
        CAST(ROW_NUMBER() OVER(ORDER BY TABA.[ID] ASC) as VARCHAR(4)) 
        )  AS int) AS [UniqueId]
,TABA.[ID]
,ROW_NUMBER()  OVER(ORDER BY TABA.[ID] ASC) AS ROWNR
,TABA.[Name]  
FROM  [Ref].[Table1] TABA LEFT JOIN [Ref].[Table2] TABB ON TABA.[ID] = TABB.[ID]
GO

Efficient way to do batch INSERTS with JDBC

Using PreparedStatements will be MUCH slower than Statements if you have low iterations. To gain a performance benefit from using a PrepareStatement over a statement, you need to be using it in a loop where iterations are at least 50 or higher.

Remove part of string in Java

Kotlin Solution

If you are removing a specific string from the end, use removeSuffix (Documentation)

var text = "one(two"
text = text.removeSuffix("(two") // "one"

If the suffix does not exist in the string, it just returns the original

var text = "one(three"
text = text.removeSuffix("(two") // "one(three"

If you want to remove after a character, use

// Each results in "one"

text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")

You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar

The Full List is here: (Documentation)

Close all infowindows in Google Maps API v3

If you have multiple markers you can use this simple solution to close a previously opened marker when clicking a new marker:

var infowindow = new google.maps.InfoWindow({
                maxWidth: (window.innerWidth - 160),
                content: content
            });

            marker.infowindow = infowindow;
            var openInfoWindow = '';

            marker.addListener('click', function (map, marker) {
                if (openInfoWindow) {
                    openInfoWindow.close();
                }
                openInfoWindow = this.infowindow;
                this.infowindow.open(map, this);
            });

Why is "forEach not a function" for this object?

If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object

Ex:

import each from 'foreach-object';
   
const object = {
   firstName: 'Arosha',
   lastName: 'Sum',
   country: 'Australia'
};
   
each(object, (value, key, object) => {
   console.log(key + ': ' + value);
});
   
// Console log output will be:
//      firstName: Arosha
//      lastName: Sum
//      country: Australia

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

How do I format XML in Notepad++?

You need to install the XML tool from the Plugins menu item ? Plugins Admin... ? Plugins Admin dialog appears and then scroll to bottom of available plugins and check the XML tools, install it and then Ctrl + Alt + Shift + B OR the option for XML Tool above shows up.

HRESULT: 0x800A03EC on Worksheet.range

I had an error with exact code when I tried to assigned array of cells to range.Value. In my case it was the problem with wrong data format. The cell's data format was set as DATE but the user made an error and instead of "20.02.2013" entered date "20.02.0213". The Excel's COM object refused taking year '0213' and threw exception with this error.

Java 8 lambda get and remove element from list

When we want to get multiple elements from a List into a new list (filter using a predicate) and remove them from the existing list, I could not find a proper answer anywhere.

Here is how we can do it using Java Streaming API partitioning.

Map<Boolean, List<ProducerDTO>> classifiedElements = producersProcedureActive
    .stream()
    .collect(Collectors.partitioningBy(producer -> producer.getPod().equals(pod)));

// get two new lists 
List<ProducerDTO> matching = classifiedElements.get(true);
List<ProducerDTO> nonMatching = classifiedElements.get(false);

// OR get non-matching elements to the existing list
producersProcedureActive = classifiedElements.get(false);

This way you effectively remove the filtered elements from the original list and add them to a new list.

Refer the 5.2. Collectors.partitioningBy section of this article.

Reading a huge .csv file

If you are using pandas and have lots of RAM (enough to read the whole file into memory) try using pd.read_csv with low_memory=False, e.g.:

import pandas as pd
data = pd.read_csv('file.csv', low_memory=False)

How do I use MySQL through XAMPP?

<?php
if(!@mysql_connect('127.0.0.1', 'root', '*your default password*'))
{
    echo "mysql not connected ".mysql_error();
    exit;

}
echo 'great work';
?>

if no error then you will get greatwork as output.

Try it saved my life XD XD

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

how to send multiple data with $.ajax() jquery

you can use FormData

take look at my snippet from MVC

var fd = new FormData();
fd.append("ProfilePicture", $("#mydropzone")[0].files[0]);// getting value from form feleds 
d.append("id", @(((User) Session["User"]).ID));// getting value from session

$.ajax({
    url: '@Url.Action("ChangeUserPicture", "User")',
    dataType: "json",
    data: fd,//here is your data
    processData: false,
    contentType: false,
    type: 'post',
    success: function(data) {},

How to get info on sent PHP curl request

If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_exec($ch);

$info = curl_getinfo($ch);
print_r($info['request_header']);

This will print:

GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*

Note the auth details are base64-encoded:

echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword

Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));

Capture iframe load complete event

Note that the onload event doesn't seem to fire if the iframe is loaded when offscreen. This frequently occurs when using "Open in New Window" /w tabs.

What is duck typing?

I try to understand the famous sentence in my way: "Python dose not care an object is a real duck or not. All it cares is whether the object, first 'quack', second 'like a duck'."

There is a good website. http://www.voidspace.org.uk/python/articles/duck_typing.shtml#id14

The author pointed that duck typing let you create your own classes that have their own internal data structure - but are accessed using normal Python syntax.

Check object empty

This can be done with java reflection,This method returns false if any one attribute value is present for the object ,hope it helps some one

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this)!=null) {
                return false;
            }
        } catch (Exception e) {
          System.out.println("Exception occured in processing");
        }
    }
    return true;
}

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

Get text of label with jquery

It's simple, set a specific value for that label (XXXXXXX for example) and run it, open html source of output (in browser) and look for XXXXXXX, you will see something like this <span id="mylabel">XXXXXX</span> it's what you want, the ID of <span> (I think it's usually same as Label name in asp code) now you can get its value by innerHTML or another method in JQuery

How do I make flex box work in safari?

It works when you set the display value of your menu items from display: inline-block; to display: block;

See your updated code here:

#menu {
    clear: both;
    height: auto;
    font-family: Arial, Tahoma, Verdana;
    font-size: 1em;
    /*padding:10px;*/
    margin: 5px;
    display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box;    /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox;  /* TWEENER - IE 10 */
    display: -webkit-flex; /* NEW - Chrome */
    display: flex;         /* NEW, Spec - Opera 12.1, Firefox 20+ */
    justify-content: center;
    -webkit-box-align: center;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;fffff
    font-style: normal;
    font-weight: 400px;
}

#menu a:link {
    display: block; //here you need to change the display property
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: yellow;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    color: #1689D6;
    font-size: 85%;
}
#menu a:visited {
    //no display property here                                                                       
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: yellow;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    color: #1689D6;
    font-size: 85%;
}
#menu a:hover {
    //no display property here                                                                               
    color: #fff;
    width: 100px;
    height: 50px;
    padding: 5px;
    background-color: red;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-weight: bold;
    font-size: 85%;
}
#menu a:active {
    //no display property here                                                                               
    color: #fff;
    width: 100px;
    height: 50px;
    padding-top: 5px;
    padding-right: 5px;
    padding-left: 5px;
    padding-bottom: 5px;
    background-color: red;
    /*border: 1px solid #cccccc;*/
    margin: 5px;
    display: flex;
    flex-grow: 1;
    align-items: center;
    text-align: center;
    justify-content: center;
    font-style: normal;
    font-weight: bold;
    font-size: 85%;
}

gcc warning" 'will be initialized after'

Make sure the members appear in the initializer list in the same order as they appear in the class

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

or you can turn -Wno-reorder

jwt check if token expired

verify itself returns an error if expired. Safer as @Gabriel said.

const jwt = require('jsonwebtoken')

router.use((req, res, next) => {
  const token = yourJwtService.getToken(req) // Get your token from the request
  jwt.verify(token, req.app.get('your-secret'), function(err, decoded) {
    if (err) throw new Error(err) // Manage different errors here (Expired, untrusted...)
    req.auth = decoded // If no error, token info is returned in 'decoded'
    next()
  });
})

And same written in async/await syntax:

const jwt = require('jsonwebtoken')
const jwtVerifyAsync = util.promisify(jwt.verify);

router.use(async (req, res, next) => {
  const token = yourJwtService.getToken(req) // Get your token from the request
  try {
    req.auth = await jwtVerifyAsync(token, req.app.get('your-secret')) // If no error, token info is returned
  } catch (err) {
    throw new Error(err) // Manage different errors here (Expired, untrusted...)
  }
  next()
});

Calculating difference between two timestamps in Oracle in milliseconds

Select date1 - (date2 - 1) * 24 * 60 *60 * 1000 from Table;

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

Angular2 Material Dialog css, dialog size

You can inspect the dialog element with dev tools and see what classes are applied on mdDialog.

For example, .md-dialog-container is the main classe of the MDDialog and has padding: 24px

you can create a custom CSS to overwrite whatever you want

.md-dialog-container {
      background-color: #000;
      width: 250px;
      height: 250px
}

In my opinion this is not a good option and probably goes against Material guide but since it doesn't have all features it has in it's previous version, you should do what you think is best for you.

Styling the arrow on bootstrap tooltips

The arrow is a border.
You need to change for each arrow the color depending on the 'data-placement' of the tooltip.

.tooltip.top .tooltip-arrow {
  border-top-color: @color;
}
.tooltip.top-left .tooltip-arrow {
  border-top-color: @color;
}
.tooltip.top-right .tooltip-arrow {
  border-top-color:@color;
}
.tooltip.right .tooltip-arrow {
  border-right-color: @color;
}
.tooltip.left .tooltip-arrow {
  border-left-color: @color;
}
.tooltip.bottom .tooltip-arrow {
  border-bottom-color: @color;
}
.tooltip.bottom-left .tooltip-arrow {
  border-bottom-color: @color;
}
.tooltip.bottom-right .tooltip-arrow {
  border-bottom-color: @color;
}
.tooltip > .tooltip-inner {
  background-color: @color;
}

awk partly string match (if column/word partly matches)

awk '$3 ~ /snow/ { print }' dummy_file 

How can I manually set an Angular form field as invalid?

Though its late but following solution worked form me.

    let control = this.registerForm.controls['controlName'];
    control.setErrors({backend: {someProp: "Invalid Data"}});
    let message = control.errors['backend'].someProp;

Python module for converting PDF to text

Repurposing the pdf2txt.py code that comes with pdfminer; you can make a function that will take a path to the pdf; optionally, an outtype (txt|html|xml|tag) and opts like the commandline pdf2txt {'-o': '/path/to/outfile.txt' ...}. By default, you can call:

convert_pdf(path)

A text file will be created, a sibling on the filesystem to the original pdf.

def convert_pdf(path, outtype='txt', opts={}):
    import sys
    from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, process_pdf
    from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter, TagExtractor
    from pdfminer.layout import LAParams
    from pdfminer.pdfparser import PDFDocument, PDFParser
    from pdfminer.pdfdevice import PDFDevice
    from pdfminer.cmapdb import CMapDB

    outfile = path[:-3] + outtype
    outdir = '/'.join(path.split('/')[:-1])

    debug = 0
    # input option
    password = ''
    pagenos = set()
    maxpages = 0
    # output option
    codec = 'utf-8'
    pageno = 1
    scale = 1
    showpageno = True
    laparams = LAParams()
    for (k, v) in opts:
        if k == '-d': debug += 1
        elif k == '-p': pagenos.update( int(x)-1 for x in v.split(',') )
        elif k == '-m': maxpages = int(v)
        elif k == '-P': password = v
        elif k == '-o': outfile = v
        elif k == '-n': laparams = None
        elif k == '-A': laparams.all_texts = True
        elif k == '-D': laparams.writing_mode = v
        elif k == '-M': laparams.char_margin = float(v)
        elif k == '-L': laparams.line_margin = float(v)
        elif k == '-W': laparams.word_margin = float(v)
        elif k == '-O': outdir = v
        elif k == '-t': outtype = v
        elif k == '-c': codec = v
        elif k == '-s': scale = float(v)
    #
    CMapDB.debug = debug
    PDFResourceManager.debug = debug
    PDFDocument.debug = debug
    PDFParser.debug = debug
    PDFPageInterpreter.debug = debug
    PDFDevice.debug = debug
    #
    rsrcmgr = PDFResourceManager()
    if not outtype:
        outtype = 'txt'
        if outfile:
            if outfile.endswith('.htm') or outfile.endswith('.html'):
                outtype = 'html'
            elif outfile.endswith('.xml'):
                outtype = 'xml'
            elif outfile.endswith('.tag'):
                outtype = 'tag'
    if outfile:
        outfp = file(outfile, 'w')
    else:
        outfp = sys.stdout
    if outtype == 'txt':
        device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams)
    elif outtype == 'xml':
        device = XMLConverter(rsrcmgr, outfp, codec=codec, laparams=laparams, outdir=outdir)
    elif outtype == 'html':
        device = HTMLConverter(rsrcmgr, outfp, codec=codec, scale=scale, laparams=laparams, outdir=outdir)
    elif outtype == 'tag':
        device = TagExtractor(rsrcmgr, outfp, codec=codec)
    else:
        return usage()

    fp = file(path, 'rb')
    process_pdf(rsrcmgr, device, fp, pagenos, maxpages=maxpages, password=password)
    fp.close()
    device.close()

    outfp.close()
    return

How to get Last record from Sqlite?

Another option is to use SQLites LAST_VALUE() function in the following way.

Given this table:

+--------+---------+-------+
| OBJECT |  STATUS |  TIME |
+--------+---------+-------+
|        |         |       |
| 1      |  ON     |  100  |
|        |         |       |
| 1      |  OFF    |  102  |
|        |         |       |
| 1      |  ON     |  103  |
|        |         |       |
| 2      |  ON     |  101  |
|        |         |       |
| 2      |  OFF    |  102  |
|        |         |       |
| 2      |  ON     |  103  |
|        |         |       |
| 3      |  OFF    |  102  |
|        |         |       |
| 3      |  ON     |  103  |
+--------+---------+-------+

You can get the last status of every object with the following query

SELECT                           
    DISTINCT OBJECT,             -- Only unique rows
    LAST_VALUE(STATUS) OVER (    -- The last value of the status column
        PARTITION BY OBJECT      -- Taking into account rows with the same value in the object column
        ORDER by time asc        -- "Last" when sorting the rows of every object by the time column in ascending order
        RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING    -- Take all rows in the patition
    ) as lastStatus
FROM
    TABLE

The result would look like:

+--------+--------------+
| OBJECT |  LAST_STATUS |
+--------+--------------+
|        |              |
| 1      |  ON          |
|        |              |
| 2      |  ON          |
|        |              |
| 3      |  ON          |
+--------+--------------+

Python naming conventions for modules

nib is fine. If in doubt, refer to the Python style guide.

From PEP 8:

Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

self.tableView.reloadData() not working in Swift

You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.

//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
    //Update UI
    self.tableView.reloadData()//Your tableView here
})

//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {  
    // Call your function here
    DispatchQueue.main.async {  
        // Update UI
        self.tableView.reloadData()  
    }
}

//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    //Here call your function
    //If you want to do changes in UI use this
    DispatchQueue.main.async(execute: {
        //Update UI
        self.tableView.reloadData()
    })
}

Visual Studio window which shows list of methods

There is no direct equivalent to the Outline View in Eclipse. The closest thing I've found is the Class View, which lists all classes and their members/methods. There is a search box at the top to narrow the selection.

Set timeout for webClient.DownloadFile()

Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
     if (stream != null)
     {
          stream.ReadTimeout = Timeout.Infinite;
          using (var reader = new StreamReader(stream, Encoding.UTF8, false))
          {
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                    if (line != String.Empty)
                    {
                        Console.WriteLine("Count {0}", count++);
                    }
                    Console.WriteLine(line);
               }
          }
     }
}

Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

Maven Out of Memory Build Failure

Using .mvn/jvm.config worked for me plus has the added benefit of being linked with the project.

All com.android.support libraries must use the exact same version specification

I got the same error after adding compile 'com.google.android.gms:play-services:10.2.4' with compile 'com.android.support:appcompat-v7:25.3.1'.

Adding animated-vector-drawable and mediarouter libs fixed the issue.

compile 'com.google.android.gms:play-services:10.2.4'
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:animated-vector-drawable:25.3.1'
compile 'com.android.support:mediarouter-v7:25.3.1'

Installation of SQL Server Business Intelligence Development Studio

I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.

I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.

I hope this helps.

How to safely call an async method in C# without await

Typically async method returns Task class. If you use Wait() method or Result property and code throws exception - exception type gets wrapped up into AggregateException - then you need to query Exception.InnerException to locate correct exception.

But it's also possible to use .GetAwaiter().GetResult() instead - it will also wait async task, but will not wrap exception.

So here is short example:

public async Task MyMethodAsync()
{
}

public string GetStringData()
{
    MyMethodAsync().GetAwaiter().GetResult();
    return "test";
}

You might want also to be able to return some parameter from async function - that can be achieved by providing extra Action<return type> into async function, for example like this:

public string GetStringData()
{
    return MyMethodWithReturnParameterAsync().GetAwaiter().GetResult();
}

public async Task<String> MyMethodWithReturnParameterAsync()
{
    return "test";
}

Please note that async methods typically have ASync suffix naming, just to be able to avoid collision between sync functions with same name. (E.g. FileStream.ReadAsync) - I have updated function names to follow this recommendation.

Is it possible to import a whole directory in sass using @import?

If you are using Sass in a Rails project, the sass-rails gem, https://github.com/rails/sass-rails, features glob importing.

@import "foo/*"     // import all the files in the foo folder
@import "bar/**/*"  // import all the files in the bar tree

To answer the concern in another answer "If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity."

Some would argue that organizing your files into directories can REDUCE complexity.

My organization's project is a rather complex app. There are 119 Sass files in 17 directories. These correspond roughly to our views and are mainly used for adjustments, with the heavy lifting being handled by our custom framework. To me, a few lines of imported directories is a tad less complex than 119 lines of imported filenames.

To address load order, we place files that need to load first – mixins, variables, etc. — in an early-loading directory. Otherwise, load order is and should be irrelevant... if we are doing things properly.

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

PHPExcel - set cell type before writing a value in it

try this

$currencyFormat = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
$textFormat='@';//'General','0.00','@'
$excel->getActiveSheet()->getStyle('B1')->getNumberFormat()->setFormatCode($currencyFormat);
$excel->getActiveSheet()->getStyle('C1')->getNumberFormat()->setFormatCode($textFormat);`

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

How to call gesture tap on UIView programmatically in swift

Complete answer for Swift 4

Step 1: create an outlet for the view

@IBOutlet weak var rightViewOutlet: UIView!

Step 2: define a tap gesture

var tapGesture = UITapGestureRecognizer()

Step 3: create ObjC function (called when view tapped)

@objc func rightViewTapped(_ recognizer: UIGestureRecognizer) {
    print("Right button is tapped")
}

Step 4: add the following within viewDidLoad()

let rightTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.rightViewTapped(_:)))
    rightViewOutlet.addGestureRecognizer(rightTap)

How to find the index of an element in an int array?

    Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
    List<Integer> arrlst = Arrays.asList(arr);
    System.out.println(arrlst.lastIndexOf(1));

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

SVN 405 Method Not Allowed

The quickest way for me to fix it was to duplicate the affected folder, and commit it with an alternative name. Then svn mv duplicateFolder originalFolder. Pretty easy.

So, take folder1 and make a folder1Copy:

svn delete folder1
svn add folder1Copy

Commit and update:

svn mv folder1Copy/ folder1/

Commit again and it's fixed.

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Creating SubString (prefix and suffix) from String using Swift 4:

let str : String = "ilike"
for i in 0...str.count {
    let index = str.index(str.startIndex, offsetBy: i) // String.Index
    let prefix = str[..<index] // String.SubSequence
    let suffix = str[index...] // String.SubSequence
    print("prefix \(prefix), suffix : \(suffix)")
}

Output

prefix , suffix : ilike
prefix i, suffix : like
prefix il, suffix : ike
prefix ili, suffix : ke
prefix ilik, suffix : e
prefix ilike, suffix : 

If you want to generate a substring between 2 indices , use :

let substring1 = string[startIndex...endIndex] // including endIndex
let subString2 = string[startIndex..<endIndex] // excluding endIndex

javascript - replace dash (hyphen) with a space

Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.

var str = "This-is---a--news-----item----";

Then to replace all dashes with single spaces, you could do this:

var newStr = str.split('-').filter(function(item) {
  item = item ? item.replace(/-/g, ''): item
  return item;
}).join(' ');

Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:

item = item ? item.replace(/-/g, ''): item

The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.

Then when your string join runs on the filtered elements, you end up with this output:

"This is a news item"

Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.

What is the difference between UNION and UNION ALL?

UNION ALL also works on more data types as well. For example when trying to union spatial data types. For example:

select a.SHAPE from tableA a
union
select b.SHAPE from tableB b

will throw

The data type geometry cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable.

However union all will not.

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

PHP remove special character from string

See example.

/**
 * nv_get_plaintext()
 *
 * @param mixed $string
 * @return
 */
function nv_get_plaintext( $string, $keep_image = false, $keep_link = false )
{
    // Get image tags
    if( $keep_image )
    {
        if( preg_match_all( "/\<img[^\>]*src=\"([^\"]*)\"[^\>]*\>/is", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $textimg = '';
                if( strpos( $match[1][$key], 'data:image/png;base64' ) === false )
                {
                    $textimg = " " . $match[1][$key];
                }
                if( preg_match_all( "/\<img[^\>]*alt=\"([^\"]+)\"[^\>]*\>/is", $_m, $m_alt ) )
                {
                    $textimg .= " " . $m_alt[1][0];
                }
                $string = str_replace( $_m, $textimg, $string );
            }
        }
    }

    // Get link tags
    if( $keep_link )
    {
        if( preg_match_all( "/\<a[^\>]*href=\"([^\"]+)\"[^\>]*\>(.*)\<\/a\>/isU", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $string = str_replace( $_m, $match[1][$key] . " " . $match[2][$key], $string );
            }
        }
    }

    $string = str_replace( ' ', ' ', strip_tags( $string ) );
    return preg_replace( '/[ ]+/', ' ', $string );
}

libstdc++.so.6: cannot open shared object file: No such file or directory

/usr/local/cilk/bin/../lib32/pinbin is dynamically linked to a library libstdc++.so.6 which is not present anymore. You need to recompile Cilk

How to copy a file from one directory to another using PHP?

You could use the rename() function :

rename('foo/test.php', 'bar/test.php');

This however will move the file not copy

Regex for quoted string with escaping quotes

I faced a similar problem trying to remove quoted strings that may interfere with parsing of some files.

I ended up with a two-step solution that beats any convoluted regex you can come up with:

 line = line.replace("\\\"","\'"); // Replace escaped quotes with something easier to handle
 line = line.replaceAll("\"([^\"]*)\"","\"x\""); // Simple is beautiful

Easier to read and probably more efficient.

Collection was modified; enumeration operation may not execute in ArrayList

You are removing the item during a foreach, yes? Simply, you can't. There are a few common options here:

  • use List<T> and RemoveAll with a predicate
  • iterate backwards by index, removing matching items

    for(int i = list.Count - 1; i >= 0; i--) {
        if({some test}) list.RemoveAt(i);
    }
    
  • use foreach, and put matching items into a second list; now enumerate the second list and remove those items from the first (if you see what I mean)

What is the purpose of global.asax in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.

http://msdn.microsoft.com/en-us/library/2027ewzw.aspx

CSS background-size: cover replacement for Mobile Safari

I have had a similar issue recently and realised that it's not due to background-size:cover but background-attachment:fixed.

I solved the issue by using a media query for iPhone and setting background-attachment property to scroll.

For my case:

.cover {
    background-size: cover;
    background-attachment: fixed;
    background-position: center center;

    @media (max-width: @iphone-screen) {
        background-attachment: scroll;
    }
}

Edit: The code block is in LESS and assumes a pre-defined variable for @iphone-screen. Thanks for the notice @stephband.

Selenium wait until document is ready

You can have the thread sleep till the page is reloaded. This is not the best solution, because you need to have an estimate of how long does the page take to load.

driver.get(homeUrl); 
Thread.sleep(5000);
driver.findElement(By.xpath("Your_Xpath_here")).sendKeys(userName);
driver.findElement(By.xpath("Your_Xpath_here")).sendKeys(passWord);
driver.findElement(By.xpath("Your_Xpath_here")).click();

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

can simply use style inside element

<p style="text-transform: lowercase;">HI I AM NEW HERE</p>

install apt-get on linux Red Hat server

I think you're running into problems because RedHat uses RPM for managing packages. Debian based systems use DEBs, which are managed with tools like apt.

Java ResultSet how to check if there are any results

Best to use ResultSet.next() along with the do {...} while() syntax for this.

The "check for any results" call ResultSet.next() moves the cursor to the first row, so use the do {...} while() syntax to process that row while continuing to process remaining rows returned by the loop.

This way you get to check for any results, while at the same time also processing any results returned.

if(resultSet.next()) { // Checks for any results and moves cursor to first row,
    do { // Use 'do...while' to process the first row, while continuing to process remaining rows

    } while (resultSet.next());
}

How do I concatenate multiple C++ strings on one line?

If you are willing to use c++11 you can utilize user-defined string literals and define two function templates that overload the plus operator for a std::string object and any other object. The only pitfall is not to overload the plus operators of std::string, otherwise the compiler doesn't know which operator to use. You can do this by using the template std::enable_if from type_traits. After that strings behave just like in Java or C#. See my example implementation for details.

Main code

#include <iostream>
#include "c_sharp_strings.hpp"

using namespace std;

int main()
{
    int i = 0;
    float f = 0.4;
    double d = 1.3e-2;
    string s;
    s += "Hello world, "_ + "nice to see you. "_ + i
            + " "_ + 47 + " "_ + f + ',' + d;
    cout << s << endl;
    return 0;
}

File c_sharp_strings.hpp

Include this header file in all all places where you want to have these strings.

#ifndef C_SHARP_STRING_H_INCLUDED
#define C_SHARP_STRING_H_INCLUDED

#include <type_traits>
#include <string>

inline std::string operator "" _(const char a[], long unsigned int i)
{
    return std::string(a);
}

template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
                        !std::is_same<char, T>::value &&
                        !std::is_same<const char*, T>::value, std::string>::type
operator+ (std::string s, T i)
{
    return s + std::to_string(i);
}

template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
                        !std::is_same<char, T>::value &&
                        !std::is_same<const char*, T>::value, std::string>::type
operator+ (T i, std::string s)
{
    return std::to_string(i) + s;
}

#endif // C_SHARP_STRING_H_INCLUDED

Looping through rows in a DataView

You can iterate DefaultView as the following code by Indexer:

DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
    DataRow oRow = dt.DefaultView[i].Row;
    // Do your stuff with oRow
    // ...
}

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }

PHP isset() with multiple parameters

The parameters of isset() should be separated by a comma sign (,) and not a dot sign (.). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.

So the original code evaluates the variables as a unified string value:

isset($_POST['search_term'] . $_POST['postcode']) // Incorrect

While the correct form evaluates them separately as variables:

isset($_POST['search_term'], $_POST['postcode']) // Correct

Unique device identification

You can use this javascript plugin

https://github.com/biggora/device-uuid

It can get a large list of information for you about mobiles and desktop machines including the uuid for example

var uuid = new DeviceUUID().get();

e9dc90ac-d03d-4f01-a7bb-873e14556d8e

var dua = [
    du.language,
    du.platform,
    du.os,
    du.cpuCores,
    du.isAuthoritative,
    du.silkAccelerated,
    du.isKindleFire,
    du.isDesktop,
    du.isMobile,
    du.isTablet,
    du.isWindows,
    du.isLinux,
    du.isLinux64,
    du.isMac,
    du.isiPad,
    du.isiPhone,
    du.isiPod,
    du.isSmartTV,
    du.pixelDepth,
    du.isTouchScreen
];

How to POST the data from a modal form of Bootstrap?

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action

Laravel Eloquent groupBy() AND also return count of each group

Thanks Antonio,

I've just added the lists command at the end so it will only return one array with key and count:

Laravel 4

$user_info = DB::table('usermetas')
             ->select('browser', DB::raw('count(*) as total'))
             ->groupBy('browser')
             ->lists('total','browser');

Laravel 5.1

$user_info = DB::table('usermetas')
             ->select('browser', DB::raw('count(*) as total'))
             ->groupBy('browser')
             ->lists('total','browser')->all();

Laravel 5.2+

$user_info = DB::table('usermetas')
             ->select('browser', DB::raw('count(*) as total'))
             ->groupBy('browser')
             ->pluck('total','browser')->all();

Vue.js toggle class on click

1.

@click="$event.target.classList.toggle('active')"

2.

:class="{ active }"
@click="active = !active"

3.

:class="'initial ' + (active ? 'active' : '')"  
@click="active = !active"

4.

:class="['initial', { active }]"  
@click="active = !active"

Reference link: https://vuejs.org/v2/guide/class-and-style.html

Demo:

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app1'_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
  el: '#app2',_x000D_
  data: { active: false }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
  el: '#app3',_x000D_
  data: { active: false }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
  el: '#app4',_x000D_
  data: { active: false }_x000D_
});
_x000D_
.initial {_x000D_
  width: 300px;_x000D_
  height: 100px;_x000D_
  background: gray;_x000D_
}_x000D_
_x000D_
.active {_x000D_
  background: red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<!-- directly manipulation: not recommended -->_x000D_
<div id="app1">_x000D_
    <button _x000D_
      class="initial"  _x000D_
      @click="$event.target.classList.toggle('active')"_x000D_
    >$event.target.classList.toggle('active')</button>_x000D_
</div>_x000D_
_x000D_
<!-- binding by object -->_x000D_
<div id="app2">_x000D_
    <button _x000D_
      class="initial"  _x000D_
      :class="{ active }"_x000D_
      @click="active = !active"_x000D_
    >class="initial" :class="{ active }"</button>_x000D_
</div>_x000D_
_x000D_
<!-- binding by expression -->_x000D_
<div id="app3">_x000D_
    <button _x000D_
      :class="'initial ' + (active ? 'active' : '')"  _x000D_
      @click="active = !active"_x000D_
    >'initial ' + (active ? 'active' : '')</button>_x000D_
</div>_x000D_
_x000D_
<!-- binding with object combined array -->_x000D_
<div id="app4">_x000D_
    <button _x000D_
      :class="['initial', { active }]"  _x000D_
      @click="active = !active"_x000D_
    >['initial', { active }]</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

do { ... } while (0) — what is it good for?

It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {
  if (n)
     FOO(n);
}

then this expands to:

void foobar(int n) {
  if (n)
     foo(n);bar(n);
}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.

SQL Server: the maximum number of rows in table

You can populate the table until you have enough disk space. For better performance you can try migration to SQL Server 2005 and then partition the table and put parts on different disks(if you have RAID configuration that could really help you). Partitioning is possible only in enterprise version of SQL Server 2005. You can look partitioning example at this link: http://technet.microsoft.com/en-us/magazine/cc162478.aspx

Also you can try to create views for most used data portion, that is also one of the solutions.

Hope this helped...

How do I change an HTML selected option using JavaScript?

It's an old post, but if anyone is still looking for solution to this kind of problem, here is what I came up with:

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.forms['AddAndEdit'].elements['list'].value = 11;
  });
</script>

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

Batch - Echo or Variable Not Working

Try the following (note that there should not be a space between the VAR, =, and GREG).

SET VAR=GREG
ECHO %VAR%
PAUSE

JavaScript listener, "keypress" doesn't detect backspace?

Try keydown instead of keypress.

The keyboard events occur in this order: keydown, keyup, keypress

The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

C# int to enum conversion

You don't need the inheritance. You can do:

(Foo)1 

it will work ;)

CSS submit button weird rendering on iPad/iPhone

oops! just found myself: just add this line on any element you need

   -webkit-appearance: none;

Excel data validation with suggestions/autocomplete

I adapted the answer by ChrisB. Like in his example a temporary combobox is made visible when a cell is clicked. Additionally:

  1. List of Combobox items is updated as user types, only matching items are displayed
  2. if any item from combobox is selected, filtering is skipped as it makes sense and because of this error

_x000D_
_x000D_
Option Explicit_x000D_
_x000D_
Private Const DATA_RANGE = "A1:A16"_x000D_
Private Const DROPDOWN_RANGE = "F2:F10"_x000D_
Private Const HELP_COLUMN = "$G"_x000D_
_x000D_
_x000D_
Private Sub Worksheet_SelectionChange(ByVal target As Range)_x000D_
    Dim xWs As Worksheet_x000D_
    Set xWs = Application.ActiveSheet_x000D_
    _x000D_
    On Error Resume Next_x000D_
    _x000D_
    With Me.TempCombo_x000D_
        .LinkedCell = vbNullString_x000D_
        .Visible = False_x000D_
    End With_x000D_
    _x000D_
    If target.Cells.count > 1 Then_x000D_
        Exit Sub_x000D_
    End If_x000D_
    _x000D_
    Dim isect As Range_x000D_
    Set isect = Application.Intersect(target, Range(DROPDOWN_RANGE))_x000D_
    If isect Is Nothing Then_x000D_
       Exit Sub_x000D_
    End If_x000D_
       _x000D_
    With Me.TempCombo_x000D_
        .Visible = True_x000D_
        .Left = target.Left - 1_x000D_
        .Top = target.Top - 1_x000D_
        .Width = target.Width + 5_x000D_
        .Height = target.Height + 5_x000D_
        .LinkedCell = target.Address_x000D_
_x000D_
    End With_x000D_
_x000D_
    Me.TempCombo.Activate_x000D_
    Me.TempCombo.DropDown_x000D_
End Sub_x000D_
_x000D_
Private Sub TempCombo_Change()_x000D_
    If Me.TempCombo.Visible = False Then_x000D_
        Exit Sub_x000D_
    End If_x000D_
    _x000D_
    Dim currentValue As String_x000D_
    currentValue = Range(Me.TempCombo.LinkedCell).Value_x000D_
    _x000D_
    If Trim(currentValue & vbNullString) = vbNullString Then_x000D_
        Me.TempCombo.ListFillRange = "=" & DATA_RANGE_x000D_
    Else_x000D_
        If Me.TempCombo.ListIndex = -1 Then_x000D_
             Dim listCount As Integer_x000D_
             listCount = write_matching_items(currentValue)_x000D_
             Me.TempCombo.ListFillRange = "=" & HELP_COLUMN & "1:" & HELP_COLUMN & listCount_x000D_
             Me.TempCombo.DropDown_x000D_
        End If_x000D_
_x000D_
    End If_x000D_
End Sub_x000D_
_x000D_
_x000D_
Private Function write_matching_items(currentValue As String) As Integer_x000D_
    Dim xWs As Worksheet_x000D_
    Set xWs = Application.ActiveSheet_x000D_
_x000D_
    Dim cell As Range_x000D_
    Dim c As Range_x000D_
    Dim firstAddress As Variant_x000D_
    Dim count As Integer_x000D_
    count = 0_x000D_
    xWs.Range(HELP_COLUMN & ":" & HELP_COLUMN).Delete_x000D_
    With xWs.Range(DATA_RANGE)_x000D_
        Set c = .Find(currentValue, LookIn:=xlValues)_x000D_
        If Not c Is Nothing Then_x000D_
            firstAddress = c.Address_x000D_
            Do_x000D_
              Set cell = xWs.Range(HELP_COLUMN & "$" & (count + 1))_x000D_
              cell.Value = c.Value_x000D_
              count = count + 1_x000D_
             _x000D_
              Set c = .FindNext(c)_x000D_
              If c Is Nothing Then_x000D_
                GoTo DoneFinding_x000D_
              End If_x000D_
           Loop While c.Address <> firstAddress_x000D_
        End If_x000D_
DoneFinding:_x000D_
    End With_x000D_
    _x000D_
    write_matching_items = count_x000D_
_x000D_
End Function_x000D_
_x000D_
Private Sub TempCombo_KeyDown( __x000D_
                ByVal KeyCode As MSForms.ReturnInteger, __x000D_
                ByVal Shift As Integer)_x000D_
_x000D_
    Select Case KeyCode_x000D_
        Case 9  ' Tab key_x000D_
            Application.ActiveCell.Offset(0, 1).Activate_x000D_
        Case 13 ' Pause key_x000D_
            Application.ActiveCell.Offset(1, 0).Activate_x000D_
    End Select_x000D_
End Sub
_x000D_
_x000D_
_x000D_

Notes:

  1. ComboBoxe's MatchEntry must be set to 2 - fmMatchEntryNone. Don't forget to set ComboBox name to TempCombo
  2. I am using listFillRange to set ComboBox options. The range must be continuous, so, matching items are stored in a help column.
  3. I have tried accomplishing the same with ComboBox.addItem, but it turned out to be hard to repaint list box as user types

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

use session_start() at the top of the page.

for more details please read the link session_start

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

I believe DataFrame.fillna() will do this for you.

Link to Docs for a dataframe and for a Series.

Example:

In [7]: df
Out[7]: 
          0         1
0       NaN       NaN
1 -0.494375  0.570994
2       NaN       NaN
3  1.876360 -0.229738
4       NaN       NaN

In [8]: df.fillna(0)
Out[8]: 
          0         1
0  0.000000  0.000000
1 -0.494375  0.570994
2  0.000000  0.000000
3  1.876360 -0.229738
4  0.000000  0.000000

To fill the NaNs in only one column, select just that column. in this case I'm using inplace=True to actually change the contents of df.

In [12]: df[1].fillna(0, inplace=True)
Out[12]: 
0    0.000000
1    0.570994
2    0.000000
3   -0.229738
4    0.000000
Name: 1

In [13]: df
Out[13]: 
          0         1
0       NaN  0.000000
1 -0.494375  0.570994
2       NaN  0.000000
3  1.876360 -0.229738
4       NaN  0.000000

EDIT:

To avoid a SettingWithCopyWarning, use the built in column-specific functionality:

df.fillna({1:0}, inplace=True)

Converting Stream to String and back...what are we missing?

a UTF8 MemoryStream to String conversion:

var res = Encoding.UTF8.GetString(stream.GetBuffer(), 0 , (int)stream.Length)

How to split and modify a string in NodeJS?

If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:

_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));

It's surprisingly robust thanks to lodash's powerful parsing capabilities.

If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):

_.chain('123, 124, 234,252, n301')
   .replace(/[^\d,]/g, '')
   .words()
   .map(_.partial(_.add, 1))
   .value();

2017 edit:

I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:

const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);

My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.

Case-insensitive string comparison in C++

I'm trying to cobble together a good answer from all the posts, so help me edit this:

Here is a method of doing this, although it does transforming the strings, and is not Unicode friendly, it should be portable which is a plus:

bool caseInsensitiveStringCompare( const std::string& str1, const std::string& str2 ) {
    std::string str1Cpy( str1 );
    std::string str2Cpy( str2 );
    std::transform( str1Cpy.begin(), str1Cpy.end(), str1Cpy.begin(), ::tolower );
    std::transform( str2Cpy.begin(), str2Cpy.end(), str2Cpy.begin(), ::tolower );
    return ( str1Cpy == str2Cpy );
}

From what I have read this is more portable than stricmp() because stricmp() is not in fact part of the std library, but only implemented by most compiler vendors.

To get a truly Unicode friendly implementation it appears you must go outside the std library. One good 3rd party library is the IBM ICU (International Components for Unicode)

Also boost::iequals provides a fairly good utility for doing this sort of comparison.

Rolling or sliding window iterator?

here is a one liner. I timed it and it's comprable to the performance of the top answer and gets progressively better with larger seq from 20% slower with len(seq) = 20 and 7% slower with len(seq) = 10000

zip(*[seq[i:(len(seq) - n - 1 + i)] for i in range(n)])

How to solve error: "Clock skew detected"?

I am going to answer my own question.

I added the following lines of code to my Makefile and it fixed the "clock skew" problem:

clean:  
    find . -type f | xargs touch
    rm -rf $(OBJS)

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

For IntelliJ IDEA users

After struggling for a couple of days, the only way to make it work in IntelliJ IDEA 13 was to import the library. Here are all the steps:

  1. Update Android SDK so the latest Play Service is installed.
  2. Go to the android-sdk-root/extras/google/google_play_services/libproject directory.
  3. Copy google-play-services_lib and paste it next to your IntelliJ IDEA project (some recommend using this directory directly, but I advise to keep this code clean!).
  4. Open IntelliJ IDEA project properties and add new Module google-play-services_lib.
  5. Check if it's marked as a Library.
  6. Add google-play-services_lib library project as a dependency to the main project.
  7. Add google-play-services library as a dependency library as well.

On the link I provided below, you can see an image of how it looks in my IntelliJ IDEA 13. It would not work without adding only one of these two.

PS. I asked a question, Why does IntelliJ IDEA 13 require both lib project and lib itself (google-play-service) to be added as a dependency?, why is it a must in IntelliJ IDEA 13, and why we cannot import either the library or project only.

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

Changing an AIX password via script?

If you can use ansible, and set the sudo rights in it, then you can easily use this script. If you're wanting to script something like this, it means you need to do it on more than one system. Therefore, you should try to automate that as well.

Converting JSON data to Java object

If, by any change, you are in an application which already uses http://restfb.com/ then you can do:

import com.restfb.json.JsonObject;

...

JsonObject json = new JsonObject(jsonString);
json.get("title");

etc.

__FILE__, __LINE__, and __FUNCTION__ usage in C++

C++20 std::source_location

C++ has finally added a non-macro option, and it will likely dominate at some point in the future when C++20 becomes widespread:

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>

void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}

int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

__PRETTY_FUNCTION__ vs __FUNCTION__ vs __func__ vs std::source_location::function_name

Answered at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

Running code after Spring Boot starts

You can extend a class using ApplicationRunner , override the run() method and add the code there.

import org.springframework.boot.ApplicationRunner;

@Component
public class ServerInitializer implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        //code goes here

    }
}

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

Apple lifted the restrictions on non-Objective C/C/C++ apps -- you just can't load code that isn't in the app bundle.

MonoTouch lets you use .NET languages -- C# is directly supported, but if you have Windows, you can make assemblies in any .NET language and use it.

There are rumors that Apple is going to support other languages directly -- I keep hearing ruby, but they are just rumors.

I think Lua is being used for game logic on a lot of apps.

EDIT (in 2018): Generally you can use any language that you can get to compile for iOS or even install language interpreters. The main thing you cannot do is load code from the Internet that wasn't in the app bundle.

People do this all of the time anyway (see React Native apps loading JavaScript from servers), but, technically, it's not allowed. The main thing that will get you attention from Apple if you make some kind of App Store that loads whole App-like things.

EDIT (in 2020): from @Pylot in comments: I know this is a long time ago, but now at least technically you can load code that isn’t embedded in the app, as you can write with JavaScript using the webview. Not staying your answer is wrong or anything, I definitely agree with you. but I was looking for something and found this post on the way. Figured if anyone sees this it might help them out.

Convert unix time stamp to date in java

You need to convert it to milliseconds by multiplying the timestamp by 1000:

java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

Read Content from Files which are inside Zip file

My way of achieving this is by creating ZipInputStream wrapping class that would handle that would provide only the stream of current entry:

The wrapper class:

public class ZippedFileInputStream extends InputStream {

    private ZipInputStream is;

    public ZippedFileInputStream(ZipInputStream is){
        this.is = is;
    }

    @Override
    public int read() throws IOException {
        return is.read();
    }

    @Override
    public void close() throws IOException {
        is.closeEntry();
    }

}

The use of it:

    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("SomeFile.zip"));

    while((entry = zipInputStream.getNextEntry())!= null) {

     ZippedFileInputStream archivedFileInputStream = new ZippedFileInputStream(zipInputStream);

     //... perform whatever logic you want here with ZippedFileInputStream 

     // note that this will only close the current entry stream and not the ZipInputStream
     archivedFileInputStream.close();

    }
    zipInputStream.close();

One advantage of this approach: InputStreams are passed as an arguments to methods that process them and those methods have a tendency to immediately close the input stream after they are done with it.

Convert from java.util.date to JodaTime

java.util.Date date = ...
DateTime dateTime = new DateTime(date);

Make sure date isn't null, though, otherwise it acts like new DateTime() - I really don't like that.

Enable binary mode while restoring a Database from an SQL dump

If you don't have enough space or don't want to waste time in decompressing it, Try this command.

gunzip < compressed-sqlfile.gz | mysql -u root -p

Don't forget to replace compressed-sqlfile.gz with your compressed file name.

.gz restore will not work without command I provided above.