Programs & Examples On #Httpfilecollection

Cursor inside cursor

You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.

declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int  identity(1,1), clientid int, whatever int)

insert into @outer (id, type) 
Select id, type from sometable

select @rows = count(1) from @outer
while (@rows > 0)
Begin
    select top 1 @rowid = rowid, @id  = id, @type = type
    from @outer
    insert into @innner (clientid, whatever ) 
    select clientid whatever from contacts where contactid = @id
    select @rows2 = count(1) from @inner
    while (@rows2 > 0)
    Begin
        select top 1 /* stuff you want into some variables */
        /* Other statements you want to execute */
        delete from @inner where rowid = @rowid2
        select @rows2 = count(1) from @inner
    End  
    delete from @outer where rowid = @rowid
    select @rows = count(1) from @outer
End

How to make join queries using Sequelize on Node.js

User.hasMany(Post, {foreignKey: 'user_id'})
Post.belongsTo(User, {foreignKey: 'user_id'})

Post.find({ where: { ...}, include: [User]})

Which will give you

SELECT
  `posts`.*,
  `users`.`username` AS `users.username`, `users`.`email` AS `users.email`,
  `users`.`password` AS `users.password`, `users`.`sex` AS `users.sex`,
  `users`.`day_birth` AS `users.day_birth`,
  `users`.`month_birth` AS `users.month_birth`,
  `users`.`year_birth` AS `users.year_birth`, `users`.`id` AS `users.id`,
  `users`.`createdAt` AS `users.createdAt`,
  `users`.`updatedAt` AS `users.updatedAt`
FROM `posts`
  LEFT OUTER JOIN `users` AS `users` ON `users`.`id` = `posts`.`user_id`;

The query above might look a bit complicated compared to what you posted, but what it does is basically just aliasing all columns of the users table to make sure they are placed into the correct model when returned and not mixed up with the posts model

Other than that you'll notice that it does a JOIN instead of selecting from two tables, but the result should be the same

Further reading:

How can I create an error 404 in PHP?

What you're doing will work, and the browser will receive a 404 code. What it won't do is display the "not found" page that you might be expecting, e.g.:

Not Found

The requested URL /test.php was not found on this server.

That's because the web server doesn't send that page when PHP returns a 404 code (at least Apache doesn't). PHP is responsible for sending all its own output. So if you want a similar page, you'll have to send the HTML yourself, e.g.:

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>

You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:

ErrorDocument 404 /notFound.php

Eclipse: How to build an executable jar with external jar?

You can do this by writing a manifest for your jar. Have a look at the Class-Path header. Eclipse has an option for choosing your own manifest on export.

The alternative is to add the dependency to the classpath at the time you invoke the application:

win32: java.exe -cp app.jar;dependency.jar foo.MyMainClass
*nix:  java -cp app.jar:dependency.jar foo.MyMainClass

Add Twitter Bootstrap icon to Input box

Since the glyphicons image is a sprite, you really can't do that: fundamentally what you want is to limit the size of the background, but there's no way to specify how big the background is. Either you cut out the icon you want, size it down and use it, or use something like the input field prepend/append option (http://twitter.github.io/bootstrap/base-css.html#forms and then search for prepended inputs).

Merge 2 DataTables and store in a new one

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
{
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table
    dtAllCountries.Merge(dtCountry);
}

AFNetworking Post Request

// For Image with parameter /// AFMultipartFormData

NSDictionary *dictParam =@{@"user_id":strGlobalUserId,@"name":[dictParameter objectForKey:@"Name"],@"contact":[dictParameter objectForKey:@"Contact Number"]};

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    if (Imagedata.length>0) {
        [formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    }
} progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {
     NSLog(@"update_profile %@", responseObject);

     if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
             [self.navigationController popViewControllerAnimated:YES];

         }] animated:YES completion:nil];


     }
     else
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
         }] animated:YES completion:nil];

     }
     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     [SVProgressHUD dismiss];
 }];

Java String to SHA1

This is a simple solution that can be used when converting a string to a hex format:

private static String encryptPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {

    MessageDigest crypt = MessageDigest.getInstance("SHA-1");
    crypt.reset();
    crypt.update(password.getBytes("UTF-8"));

    return new BigInteger(1, crypt.digest()).toString(16);
}

How to implement my very own URI scheme on Android

This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data> element. You setup an intent filter with the <data> element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)

Here's a short example:

<activity android:name=".MyUriActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="myapp" android:host="path" />
    </intent-filter>
</activity>

As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).

get UTC time in PHP

As previously answered here, since PHP 5.2.0 you can use the DateTime class and specify the UTC timezone with an instance of DateTimeZone.

The DateTime __construct() documentation suggests passing "now" as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.

$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));

echo $date_utc->format(\DateTime::RFC850); # Saturday, 18-Apr-15 03:23:46 UTC

Using Mysql in the command line in osx - command not found?

You can just modified the .bash_profile by adding the MySQL $PATH as the following:
export PATH=$PATH:/usr/local/mysql/bin.

I did the following:

1- Open Terminal then $ nano .bash_profile or $ vim .bash_profile

2- Add the following PATH code to the .bash_profile

# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc 

3- Save the file.

4- Refresh Terminal using $ source ~/.bash_profile

5- To verify, type in Terminal $ mysql --version

6- It should print the output something like this:

$ mysql Ver 14.14 Distrib 5.7.17, for macos10.12 (x86_64)

The Terminal is now configured to read the MySQL commands from $PATH which is placed in the .bash_profile .

Bootstrap table striped: How do I change the stripe background colour?

Add the following CSS style after loading Bootstrap:

.table-striped>tbody>tr:nth-child(odd)>td, 
.table-striped>tbody>tr:nth-child(odd)>th {
   background-color: red; // Choose your own color here
 }

Add the loading screen in starting of the android application

Write the code:

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        Thread welcomeThread = new Thread() {

            @Override
            public void run() {
                try {
                    super.run();
                    sleep(10000)  //Delay of 10 seconds
                } catch (Exception e) {

                } finally {

                    Intent i = new Intent(SplashActivity.this,
                            MainActivity.class);
                    startActivity(i);
                    finish();
                }
            }
        };
        welcomeThread.start();
    }

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

After adding php directory in User Settings,

{
    "php.validate.executablePath": "C:/phpdirectory/php7.1.8/php.exe",
    "php.executablePath": "C:/phpdirectory/php7.1.8/php.exe"
}

If you still have this error, please verify you have installed :

To test if you PHP exe is ok, open cmd.exe :

c:/prog/php-7.1.8-Win32-VC14-x64/php.exe --version

If PHP fails, a message will be prompted with the error (missing dll for example).

How to give a Blob uploaded as FormData a file name?

Since you're getting the data pasted to clipboard, there is no reliable way of knowing the origin of the file and its properties (including name).

Your best bet is to come up with a file naming scheme of your own and send along with the blob.

form.append("filename",getFileName());
form.append("blob",blob);

function getFileName() {
 // logic to generate file names
}

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

For me an update solved the problem:

On Ubuntu:

sudo apt-get update
sudo apt-get upgrade

On CentOS:

sudo yum update

Run exe file with parameters in a batch file

Unless it's just a simplified example for the question, my advice is that drop the batch wrapper and schedule PHP directly, more specifically the php-win.exe program, which won't open unnecessary windows.

Program: c:\program files\php\php-win.exe
Arguments: D:\mydocs\mp\index.php param1 param2

Otherwise, just quote stuff as Andrew points out.


In older versions of Windows, you should be able to put everything in the single "Run" text box (as long as you quote everything that has spaces):

"c:\program files\php\php-win.exe" D:\mydocs\mp\index.php param1 param2

Is an entity body allowed for an HTTP DELETE request?

This is not defined.

A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.
https://tools.ietf.org/html/rfc7231#page-29

Regarding C++ Include another class

C++ (and C for that matter) split the "declaration" and the "implementation" of types, functions and classes. You should "declare" the classes you need in a header-file (.h or .hpp), and put the corresponding implementation in a .cpp-file. Then, when you wish to use (access) a class somewhere, you #include the corresponding headerfile.

Example

ClassOne.hpp:

class ClassOne
{
public:
  ClassOne(); // note, no function body        
  int method(); // no body here either
private:
  int member;
};

ClassOne.cpp:

#include "ClassOne.hpp"

// implementation of constructor
ClassOne::ClassOne()
 :member(0)
{}

// implementation of "method"
int ClassOne::method()
{
  return member++;
}

main.cpp:

#include "ClassOne.hpp" // Bring the ClassOne declaration into "view" of the compiler

int main(int argc, char* argv[])
{
  ClassOne c1;
  c1.method();

  return 0;
}

Switch case with conditions

What you are doing is to look for (0) or (1) results.

(cnt >= 10 && cnt <= 20) returns either true or false.

--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--

Undo a merge by pull request?

To undo a github pull request with commits throughout that you do not want to delete, you have to run a:

git reset --hard --merge <commit hash>

with the commit hash being the commit PRIOR to merging the pull request. This will remove all commits from the pull request without influencing any commits within the history.

A good way to find this is to go to the now closed pull request and finding this field:

Pull Request Image Pull Request Image

After you run the git reset, run a:

git push origin --force <branch name>

This should revert the branch back before the pull request WITHOUT affecting any commits in the branch peppered into the commit history between commits from the pull request.

EDIT:

If you were to click the revert button on the pull request, this creates an additional commit on the branch. It DOES NOT uncommit or unmerge. This means that if you were to hit the revert button, you cannot open a new pull request to re-add all of this code.

How do I do a simple 'Find and Replace" in MsSQL?

like so:

BEGIN TRANSACTION; 
UPDATE table_name
  SET column_name=REPLACE(column_name,'text_to_find','replace_with_this'); 
COMMIT TRANSACTION;

Example: Replaces <script... with <a ... to eliminate javascript vulnerabilities

BEGIN TRANSACTION; UPDATE testdb
SET title=REPLACE(title,'script','a'); COMMIT TRANSACTION;

MatPlotLib: Multiple datasets on the same scatter plot

I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes

import matplotlib.pyplot as plt

plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()

Do the parentheses after the type name make a difference with new?

No, they are the same. But there is a difference between:

Test t;      // create a Test called t

and

Test t();   // declare a function called t which returns a Test

This is because of the basic C++ (and C) rule: If something can possibly be a declaration, then it is a declaration.

Edit: Re the initialisation issues regarding POD and non-POD data, while I agree with everything that has been said, I would just like to point out that these issues only apply if the thing being new'd or otherwise constructed does not have a user-defined constructor. If there is such a constructor it will be used. For 99.99% of sensibly designed classes there will be such a constructor, and so the issues can be ignored.

jQuery Selector: Id Ends With?

It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:

$("element[id$=_txtTitle]")

(where element is the type of element you're trying to find - eg div, input etc.

(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).

Calling javascript function in iframe

If you can not use it directly and if you encounter this error: Blocked a frame with origin "http://www..com" from accessing a cross-origin frame. You can use postMessage() instead of using the function directly.

Modulo operator with negative values

From ISO14882:2011(e) 5.6-4:

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.

The rest is basic math:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

Note that

If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

from ISO14882:2003(e) is no longer present in ISO14882:2011(e)

phpMyAdmin allow remote users

Try this

Replace

<Directory /usr/share/phpMyAdmin/>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        <RequireAny>
            Require ip 127.0.0.1
            Require ip ::1
        </RequireAny>
    </IfModule>
    <IfModule !mod_authz_core.c>
        # Apache 2.2
        Order Deny,Allow
        Deny from All
        Allow from 127.0.0.1
        Allow from ::1
    </IfModule>
</Directory>

With this:

<Directory "/usr/share/phpMyAdmin/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Allow,Deny 
    Allow from all
</Directory>

Add the following line for ease of access:

Alias /phpmyadmin /usr/share/phpMyAdmin

Getting a link to go to a specific section on another page

To link from a page to another section of the page, I navigate through the page depending on the page's location to the other, at the URL bar, and add the #id. So what I mean;

<a href = "../#the_part_that_you_want">This takes you #the_part_that_you_want at the page before</a>

How to safely open/close files in python 2.4

Here is example given which so how to use open and "python close

from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()

It's necessary to how many times you opened file have to close that times.

Launch Pycharm from command line (terminal)

You can launch Pycharm from Mac terminal using the open command. Just type open /path/to/App

Applications$ ls -lrt PyCharm\ CE.app/
total 8
drwxr-xr-x@ 71 amit  admin  2414 Sep 24 11:08 lib
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 help
drwxr-xr-x@ 12 amit  admin   408 Sep 24 11:08 plugins
drwxr-xr-x@ 29 amit  admin   986 Sep 24 11:08 license
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 skeletons
-rw-r--r--@  1 amit  admin    10 Sep 24 11:08 build.txt
drwxr-xr-x@  6 amit  admin   204 Sep 24 11:12 Contents
drwxr-xr-x@ 14 amit  admin   476 Sep 24 11:12 bin
drwxr-xr-x@ 31 amit  admin  1054 Sep 25 21:43 helpers
/Applications$
/Applications$ open PyCharm\ CE.app/

Vertically aligning text next to a radio button

You may try something like;

<p><input type="radio" id="oddsPref" name="oddsPref" value="decimal" /><span>Decimal</span></p>

and give the span a margin top like;

span{
    margin-top: 4px;
    position:absolute;
}

here is the fiddle http://jsfiddle.net/UnA6j/11/

Best way to parseDouble with comma as decimal separator?

If you don't know the correct Locale and the string can have a thousand separator this could be a last resort:

    doubleStrIn = doubleStrIn.replaceAll("[^\\d,\\.]++", "");
    if (doubleStrIn.matches(".+\\.\\d+,\\d+$"))
        return Double.parseDouble(doubleStrIn.replaceAll("\\.", "").replaceAll(",", "."));
    if (doubleStrIn.matches(".+,\\d+\\.\\d+$"))
        return Double.parseDouble(doubleStrIn.replaceAll(",", ""));
    return Double.parseDouble(doubleStrIn.replaceAll(",", "."));

Be aware: this will happily parse strings like "R 1 52.43,2" to "15243.2".

Unable to specify the compiler with CMake

Using with FILEPATH option might work:

set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)

Safest way to run BAT file from Powershell script

What about invoke-item script.bat.

Given two directory trees, how can I find out which files differ by content?

Channel compatriot 'billings' (of freenode/#centos fame) shared his method with me:

diff -Naur dir1/ dir2

Including the final directory forward slash doesn't matter.

Also, it appears the -u option is not available on some older/server versions of diff.

The difference in diffs:

# diff -Nar /tmp/dir1 /tmp/dir2/
diff -Nar /tmp/dir1/file /tmp/dir2/file
28a29
> TEST

# diff -qr /tmp/dir1/ /tmp/dir2/
Files /tmp/dir1/file and /tmp/dir2/file differ

make: *** [ ] Error 1 error

I got the same thing. Running "make" and it fails with just this message.

% make
make: *** [all] Error 1

This was caused by a command in a rule terminates with non-zero exit status. E.g. imagine the following (stupid) Makefile:

all:
       @false
       echo "hello"

This would fail (without printing "hello") with the above message since false terminates with exit status 1.

In my case, I was trying to be clever and make a backup of a file before processing it (so that I could compare the newly generated file with my previous one). I did this by having a in my Make rule that looked like this:

@[ -e $@ ] && mv $@ [email protected]

...not realizing that if the target file does not exist, then the above construction will exit (without running the mv command) with exit status 1, and thus any subsequent commands in that rule failed to run. Rewriting my faulty line to:

@if [ -e $@ ]; then mv $@ [email protected]; fi

Solved my problem.

Setting Custom ActionBar Title from Fragment

At least for me, there was an easy answer (after much digging around) to changing a tab title at runtime:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText("My New Text");

Possible reason for NGINX 499 error codes

Client closed the connection doesn't mean it's a browser issue!? Not at all!

You can find 499 errors in a log file if you have a LB (load balancer) in front of your webserver (nginx) either AWS or haproxy (custom). That said the LB will act as a client to nginx.

If you run haproxy default values for:

    timeout client  60000
    timeout server  60000

That would mean that LB will time out after 60000ms if there is no respond from nginx. Time outs might happen for busy websites or scripts that need more time for execution. You'll need to find timeout that will work for you. For example extend it to:

    timeout client  180s
    timeout server  180s

And you will be probably set.

Depending on your setup you might see a 504 gateway timeout error in your browser which indicates that something is wrong with php-fpm but that will not be the case with 499 errors in your log files.

How can I adjust DIV width to contents

EDIT2- Yea auto fills the DOM SOZ!

#img_box{        
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

 min-height: 400px;

What uses are there for "placement new"?

I have an idea too. C++ does have zero-overhead principle. But exceptions do not follow this principle, so sometimes they are turned off with compiler switch.

Let's look to this example:

#include <new>
#include <cstdio>
#include <cstdlib>

int main() {
    struct A {
        A() {
            printf("A()\n");
        }
        ~A() {
            printf("~A()\n");
        }
        char data[1000000000000000000] = {}; // some very big number
    };

    try {
        A *result = new A();
        printf("new passed: %p\n", result);
        delete result;
    } catch (std::bad_alloc) {
        printf("new failed\n");
    }
}

We allocate a big struct here, and check if allocation is successful, and delete it.

But if we have exceptions turned off, we can't use try block, and unable to handle new[] failure.

So how we can do that? Here is how:

#include <new>
#include <cstdio>
#include <cstdlib>

int main() {
    struct A {
        A() {
            printf("A()\n");
        }
        ~A() {
            printf("~A()\n");
        }
        char data[1000000000000000000] = {}; // some very big number
    };

    void *buf = malloc(sizeof(A));
    if (buf != nullptr) {
        A *result = new(buf) A();
        printf("new passed: %p\n", result);
        result->~A();
        free(result);
    } else {
        printf("new failed\n");
    }
}
  • Use simple malloc
  • Check if it is failed in a C way
  • If it successful, we use placement new
  • Manually call the destructor (we can't just call delete)
  • call free, due we called malloc

UPD @Useless wrote a comment which opened to my view the existence of new(nothrow), which should be used in this case, but not the method I wrote before. Please don't use the code I wrote before. Sorry.

MySQL - Make an existing Field Unique

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

is the right answer

the insert part

INSERT IGNORE INTO mytable ....

How to use gitignore command in git

So based on what you said, these files are libraries/documentation you don't want to delete but also don't want to push to github. Let say you have your project in folder your_project and a doc directory: your_project/doc.

  1. Remove it from the project directory (without actually deleting it): git rm --cached doc/*
  2. If you don't already have a .gitignore, you can make one right inside of your project folder: project/.gitignore.
  3. Put doc/* in the .gitignore
  4. Stage the file to commit: git add project/.gitignore
  5. Commit: git commit -m "message".
  6. Push your change to github.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Why is the GETDATE() an invalid identifier

SYSDATE and GETDATE perform identically.

SYSDATE is compatible with Oracle syntax, and GETDATE is compatible with Microsoft SQL Server syntax.

System.Net.WebException HTTP status code

(I do realise the question is old, but it's among the top hits on Google.)

A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:

catch (WebException ex) when (ex.Response is HttpWebResponse response)
{
     doSomething(response.StatusCode)
}

This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.

Sort an array in Java

If you want to build the Quick sort algorithm yourself and have more understanding of how it works check the below code :

1- Create sort class

class QuickSort {
    private int input[];
    private int length;

    public void sort(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return;
        }
        this.input = numbers;
        length = numbers.length;
        quickSort(0, length - 1);
    }
    /*
     * This method implements in-place quicksort algorithm recursively.
     */

    private void quickSort(int low, int high) {
        int i = low;
        int j = high;

        // pivot is middle index
        int pivot = input[low + (high - low) / 2];

        // Divide into two arrays
        while (i <= j) {
            /**
             * As shown in above image, In each iteration, we will identify a
             * number from left side which is greater then the pivot value, and
             * a number from right side which is less then the pivot value. Once
             * search is complete, we can swap both numbers.
             */
            while (input[i] < pivot) {
                i++;
            }
            while (input[j] > pivot) {
                j--;
            }
            if (i <= j) {
                swap(i, j);
                // move index to next position on both sides
                i++;
                j--;
            }
        }

        // calls quickSort() method recursively
        if (low < j) {
            quickSort(low, j);
        }

        if (i < high) {
            quickSort(i, high);
        }
    }

    private void swap(int i, int j) {
        int temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }
}

2- Send your unsorted array to Quicksort class

import java.util.Arrays;


public class QuickSortDemo {

    public static void main(String args[]) {
        // unsorted integer array
        int[] unsorted = {6, 5, 3, 1, 8, 7, 2, 4};
        System.out.println("Unsorted array :" + Arrays.toString(unsorted));
        QuickSort algorithm = new QuickSort();
        // sorting integer array using quicksort algorithm
        algorithm.sort(unsorted);
        // printing sorted array
        System.out.println("Sorted array :" + Arrays.toString(unsorted));
    }
}

3- Output

Unsorted array :[6, 5, 3, 1, 8, 7, 2, 4] 
Sorted array :[1, 2, 3, 4, 5, 6, 7, 8]

In a URL, should spaces be encoded using %20 or +?

This confusion is because URL is still 'broken' to this day

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+   
|      Part     |      Data         |   
+---------------+-------------------+   
|  Scheme       | http              |   
|  Host address | www.google.com    |   
+---------------+-------------------+  

If we look at a more complex URL such as "https://bob:[email protected]:8080/file;p=1?q=2#third" we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host address     | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file               |
|  Path parameters  | p=1                 |
|  Query parameters | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

The reserved characters are different for each part

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts: "http://example.com/blue+light%20blue?blue%2Blight+blue". From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

What this boils down to is

you should have %20 before the ? and + after

Source

How to get PID by process name?

You can get the pid of processes by name using pidof through subprocess.check_output:

from subprocess import check_output
def get_pid(name):
    return check_output(["pidof",name])


In [5]: get_pid("java")
Out[5]: '23366\n'

check_output(["pidof",name]) will run the command as "pidof process_name", If the return code was non-zero it raises a CalledProcessError.

To handle multiple entries and cast to ints:

from subprocess import check_output
def get_pid(name):
    return map(int,check_output(["pidof",name]).split())

In [21]: get_pid("chrome")

Out[21]: 
[27698, 27678, 27665, 27649, 27540, 27530, 27517, 14884, 14719, 13849, 13708, 7713, 7310, 7291, 7217, 7208, 7204, 7189, 7180, 7175, 7166, 7151, 7138, 7127, 7117, 7114, 7107, 7095, 7091, 7087, 7083, 7073, 7065, 7056, 7048, 7028, 7011, 6997]

Or pas the -s flag to get a single pid:

def get_pid(name):
    return int(check_output(["pidof","-s",name]))

In [25]: get_pid("chrome")
Out[25]: 27698

Permanently Set Postgresql Schema Path

You can set the default search_path at the database level:

ALTER DATABASE <database_name> SET search_path TO schema1,schema2;

Or at the user or role level:

ALTER ROLE <role_name> SET search_path TO schema1,schema2;

Or if you have a common default schema in all your databases you could set the system-wide default in the config file with the search_path option.

When a database is created it is created by default from a hidden "template" database named template1, you could alter that database to specify a new default search path for all databases created in the future. You could also create another template database and use CREATE DATABASE <database_name> TEMPLATE <template_name> to create your databases.

Python: convert string to byte array

for python 3 it worked for what @HYRY posted. I needed it for a returned data in a dbus.array. This is the only way it worked

s = "ABCD"

from array import array

a = array("B", s)

Where is the WPF Numeric UpDown control?

Let's enjoy some hacky things:
Here is a Style of Slider as a NumericUpDown, simple and easy to use, without any hidden code or third party library.

<Style TargetType="{x:Type Slider}">
    <Style.Resources>
        <Style x:Key="RepeatButtonStyle" TargetType="{x:Type RepeatButton}">
            <Setter Property="Focusable" Value="false" />
            <Setter Property="IsTabStop" Value="false" />
            <Setter Property="Padding" Value="0" />
            <Setter Property="Width" Value="20" />
        </Style>
    </Style.Resources>
    <Setter Property="Stylus.IsPressAndHoldEnabled" Value="false" />
    <Setter Property="SmallChange" Value="1" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Slider}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBox Grid.RowSpan="2"
                             Height="Auto"
                             Margin="0" Padding="0" VerticalAlignment="Stretch" VerticalContentAlignment="Center"
                             Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Value}" />
                    <RepeatButton Grid.Row="0" Grid.Column="1" Command="{x:Static Slider.IncreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
                        <Path Data="M4,0 L0,4 8,4 Z" Fill="Black" />
                    </RepeatButton>
                    <RepeatButton Grid.Row="1" Grid.Column="1" Command="{x:Static Slider.DecreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
                        <Path Data="M0,0 L4,4 8,0 Z" Fill="Black" />
                    </RepeatButton>
                    <Border x:Name="TrackBackground" Visibility="Collapsed">
                        <Rectangle x:Name="PART_SelectionRange" Visibility="Collapsed" />
                    </Border>
                    <Thumb x:Name="Thumb" Visibility="Collapsed" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

How to set a value to a file input in HTML?

Not an answer to your question (which others have answered), but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:

  • show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail
  • the <input> tag to upload a new file
  • a checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value

VB.NET Switch Statement GoTo Case

Why don't you just refactor the default case as a method and call it from both places? This should be more readable and will allow you to change the code later in a more efficient manner.

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

You could try this: it's a very good tool, very fast and effective.

http://code.google.com/p/oracle-gui/

How to make the corners of a button round?

If you want change corner radius as well as want a ripple effect in button when pressed use this:-

  1. Put button_background.xml in drawable
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#F7941D">

    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#F7941D" />
            <corners android:radius="10dp" />
        </shape>
    </item>

    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
            <corners android:radius="10dp" />
        </shape>
    </item>

</ripple>
  1. Apply this background to your button
<Button
    android:background="@drawable/button_background"
    android:id="@+id/myBtn"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="My Button" />

What are type hints in Python 3.5?

The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.

Additionally, it is supported in Python 2.7, as explained in this comment:

PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.

How to tag docker image with docker-compose

If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:

build: ./dir
image: webapp:tag

This results in an image named webapp and tagged tag, built from ./dir.

https://docs.docker.com/compose/compose-file/#build

Setting background colour of Android layout element

You can use android:background="#DC143C", or any other RGB values for your color. I have no problem using it this way, as stated here

How to implement debounce in Vue2?

Please note that I posted this answer before the accepted answer. It's not correct. It's just a step forward from the solution in the question. I have edited the accepted question to show both the author's implementation and the final implementation I had used.


Based on comments and the linked migration document, I've made a few changes to the code:

In template:

<input type="text" v-on:input="debounceInput" v-model="searchInput">

In script:

watch: {
  searchInput: function () {
    this.debounceInput();
  }
},

And the method that sets the filter key stays the same:

methods: {
  debounceInput: _.debounce(function () {
    this.filterKey = this.searchInput;
  }, 500)
}

This looks like there is one less call (just the v-model, and not the v-on:input).

SoapFault exception: Could not connect to host

In my case service address in wsdl is wrong.

My wsdl url is.

https://myweb.com:4460/xxx_webservices/services/ABC.ABC?wsdl

But service address in that xml result is.

<soap:address location="http://myweb.com:8080/xxx_webservices/services/ABC.ABC/"/>

I just save that xml to local file and change service address to.

<soap:address location="https://myweb.com:4460/xxx_webservices/services/ABC.ABC/"/>

Good luck.

Best JavaScript compressor

Revisiting this question a few years later, UglifyJS, seems to be the best option as of now.

As stated below, it runs on the NodeJS platform, but can be easily modified to run on any JavaScript engine.

--- Old answer below---

Google released Closure Compiler which seems to be generating the smallest files so far as seen here and here

Previous to that the various options were as follow

Basically Packer does a better job at initial compression , but if you are going to gzip the files before sending on the wire (which you should be doing) YUI Compressor gets the smallest final size.

The tests were done on jQuery code btw.

  • Original jQuery library 62,885 bytes , 19,758 bytes after gzip
  • jQuery minified with JSMin 36,391 bytes , 11,541 bytes after gzip
  • jQuery minified with Packer 21,557 bytes , 11,119 bytes after gzip
  • jQuery minified with the YUI Compressor 31,822 bytes , 10,818 bytes after gzip

@daniel james mentions in the comment compressorrater which shows Packer leading the chart in best compression, so I guess ymmv

How to count the number of true elements in a NumPy bool array

In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])

which can be extended to D dimensions.

The results are:

Prediction:

[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]

Target:

[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
{
    string id;
    DateTime date;
    public string ID
    {
       get { return id; }
       set { id = value; }
    }
    public DateTime Date
    {
       get { return date; }
       set { date = value; }
    }
}

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList
{
     get...
     set...
}

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
   <DataGrid.Columns>                
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

How to clear Route Caching on server: Laravel 5.2.37

For your case solution is :

php artisan cache:clear
php artisan route:cache

Optimizing Route Loading is a must on production :

If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:

php artisan route:cache

This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.

Laravel 5 clear cache from route, view, config and all cache data from application

I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.

Reoptimized class loader:

php artisan optimize

Clear Cache facade value:

php artisan cache:clear

Clear Route cache:

php artisan route:cache

Clear View cache:

php artisan view:clear

Clear Config cache:

php artisan config:cache

How to run docker-compose up -d at system start up?

As an addition to user39544's answer, one more type of syntax for crontab -e:

@reboot sleep 60 && /usr/local/bin/docker-compose -f /path_to_your_project/docker-compose.yml up -d

Java: Local variable mi defined in an enclosing scope must be final or effectively final

As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.

Below is the code snippet for it :

     //WorkAround 
    for (String color : colors ){

String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));

Jmi.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JMenuItem item = (JMenuItem) e.getSource();
            IconA icon = (IconA) item.getIcon();
            // HERE YOU USE THE String color variable and no errors!!!
            Color kolorIkony = getColour(color); 
            textArea.setForeground(kolorIkony);
        }
    });

    mnForeground.add(Jmi);
}

}

What are .NET Assemblies?

In .NET, when we compile our source code then assembly gets generated in Visual Studio. Assembly consists of two parts Manifest and IL(Intermediate Language). Manifest contains assembly metadata means assembly's version requirements, security identity, names and hashes of all files that make up the assembly. IL contains information about classes, constructors, main method etc.

Remove all elements contained in another array

The filter method should do the trick:

const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = ['b', 'c', 'g'];

// ES5 syntax
const filteredArray = myArray.filter(function(x) { 
  return toRemove.indexOf(x) < 0;
});

If your toRemove array is large, this sort of lookup pattern can be inefficient. It would be more performant to create a map so that lookups are O(1) rather than O(n).

const toRemoveMap = toRemove.reduce(
  function(memo, item) {
    memo[item] = memo[item] || true;
    return memo;
  },
  {} // initialize an empty object
);

const filteredArray = myArray.filter(function (x) {
  return toRemoveMap[x];
});

// or, if you want to use ES6-style arrow syntax:
const toRemoveMap = toRemove.reduce((memo, item) => ({
  ...memo,
  [item]: true
}), {});

const filteredArray = myArray.filter(x => toRemoveMap[x]);

Controlling execution order of unit tests in Visual Studio

I dont see anyone mentioning the ClassInitialize attribute method. The attributes are pretty straight forward.

Create methods that are marked with either the [ClassInitialize()] or [TestInitialize()] attribute to prepare aspects of the environment in which your unit test will run. The purpose of this is to establish a known state for running your unit test. For example, you may use the [ClassInitialize()] or the [TestInitialize()] method to copy, alter, or create certain data files that your test will use.

Create methods that are marked with either the [ClassCleanup()] or [TestCleanUp{}] attribute to return the environment to a known state after a test has run. This might mean the deletion of files in folders or the return of a database to a known state. An example of this is to reset an inventory database to an initial state after testing a method that is used in an order-entry application.

  • [ClassInitialize()] Use ClassInitialize to run code before you run the first test in the class.

  • [ClassCleanUp()] Use ClassCleanup to run code after all tests in a class have run.

  • [TestInitialize()] Use TestInitialize to run code before you run each test.

  • [TestCleanUp()] Use TestCleanup to run code after each test has run.

How can I search sub-folders using glob.glob module?

The command rglob will do an infinite recursion down the deepest sub-level of your directory structure. If you only want one level deep, then do not use it, however.

I realize the OP was talking about using glob.glob. I believe this answers the intent, however, which is to search all subfolders recursively.

The rglob function recently produced a 100x increase in speed for a data processing algorithm which was using the folder structure as a fixed assumption for the order of data reading. However, with rglob we were able to do a single scan once through all files at or below a specified parent directory, save their names to a list (over a million files), then use that list to determine which files we needed to open at any point in the future based on the file naming conventions only vs. which folder they were in.

/usr/bin/codesign failed with exit code 1

One possible cause is that you doesn't have permission to write on the build directory.

Solution: Delete all build directory on your project folder and rebuild your application.

How do I get the name of the current executable in C#?

This should suffice:

Environment.GetCommandLineArgs()[0];

How to set up Android emulator proxy settings

The simplest and the best way is to do the following: This has been done for Android Emulator 2.2

  1. Click on Menu
  2. Click on Settings
  3. Click on Wireless & Networks
  4. Go to Mobile Networks
  5. Go to Access Point Names
  6. Here you will Telkila Internet, click on it.
  7. In the Edit access point section, input the "proxy" and "port"
  8. Also provide the Username and Password, rest of the fields leave them blank.

"Eliminate render-blocking CSS in above-the-fold content"

Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.

SQL Server IF EXISTS THEN 1 ELSE 2

In SQL without SELECT you cannot result anything. Instead of IF-ELSE block I prefer to use CASE statement for this

SELECT CASE
         WHEN EXISTS (SELECT 1
                      FROM   tblGLUserAccess
                      WHERE  GLUserName = 'xxxxxxxx') THEN 1
         ELSE 2
       END 

jQuery ajax success callback function definition

In your component i.e angular JS code:

function getData(){
    window.location.href = 'http://localhost:1036/api/Employee/GetExcelData';
}

Extracting text from a PDF file using PDFMiner in python?

terrific answer from DuckPuncher, for Python3 make sure you install pdfminer2 and do:

import io

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = io.StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos = set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,
                                  password=password,
                                  caching=caching,
                                  check_extractable=True):
        interpreter.process_page(page)



    fp.close()
    device.close()
    text = retstr.getvalue()
    retstr.close()
    return text

Finding the max value of an attribute in an array of objects

To find the maximum y value of the objects in array:

Math.max.apply(Math, array.map(function(o) { return o.y; }))

Apply CSS Style to child elements

This code can do the trick as well, using the SCSS syntax

.parent {
  & > * {
    margin-right: 15px;
    &:last-child {
      margin-right: 0;
    }
  }
}

What's the difference between primitive and reference types?

As many have stated more or less correctly what reference and primitive types are, one might be interested that we have some more relevant types in Java. Here is the complete lists of types in java (as far as I am aware of (JDK 11)).

Primitive Type

Describes a value (and not a type).

11

Reference Type

Describes a concrete type which instances extend Object (interface, class, enum, array). Furthermore TypeParameter is actually a reference type!

Integer

Note: The difference between primitive and reference type makes it necessary to rely on boxing to convert primitives in Object instances and vise versa.

Note2: A type parameter describes a type having an optional lower or upper bound and can be referenced by name within its context (in contrast to the wild card type). A type parameter typically can be applied to parameterized types (classes/interfaces) and methods. The parameter type defines a type identifier.

Wildcard Type

Expresses an unknown type (like any in TypeScript) that can have a lower or upper bound by using super or extend.

? extends List<String>
? super ArrayList<String>

Void Type

Nothingness. No value/instance possible.

void method();

Null Type

The only representation is 'null'. It is used especially during type interference computations. Null is a special case logically belonging to any type (can be assigned to any variable of any type) but is actual not considered an instance of any type (e.g. (null instanceof Object) == false).

null

Union Type

A union type is a type that is actual a set of alternative types. Sadly in Java it only exists for the multi catch statement.

catch(IllegalStateException | IOException e) {}

Interference Type

A type that is compatibile to multiple types. Since in Java a class has at most one super class (Object has none), interference types allow only the first type to be a class and every other type must be an interface type.

void method(List<? extends List<?> & Comparable> comparableList) {}

Unknown Type

The type is unknown. That is the case for certain Lambda definitions (not enclosed in brackets, single parameter).

list.forEach(element -> System.out.println(element.toString)); //element is of unknown type

Var Type

Unknown type introduced by a variable declaration spotting the 'var' keyword.

var variable = list.get(0);

jQuery Validation plugin: disable validation for specified submit buttons

You can add a CSS class of cancel to a submit button to suppress the validation

e.g

<input class="cancel" type="submit" value="Save" />

See the jQuery Validator documentation of this feature here: Skipping validation on submit


EDIT:

The above technique has been deprecated and replaced with the formnovalidate attribute.

<input formnovalidate="formnovalidate" type="submit" value="Save" />

.trim() in JavaScript not working in IE

var res = function(str){
    var ob; var oe;
    for(var i = 0; i < str.length; i++){
        if(str.charAt(i) != " " && ob == undefined){ob = i;}
        if(str.charAt(i) != " "){oe = i;}
    }
    return str.substring(ob,oe+1);
}

How to pass ArrayList of Objects from one to another activity using Intent in android?

Your intent creation seems correct if your Question implements Parcelable.

In the next activity you can retrieve your list of questions like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}

How do I declare a two dimensional array?

You can try this, but second dimension values will be equals to indexes:

$array = array_fill_keys(range(0,5), range(0,5));

a little more complicated for empty array:

$array = array_fill_keys(range(0, 5), array_fill_keys(range(0, 5), null));

How to do a Jquery Callback after form submit?

You'll have to do things manually with an AJAX call to the server. This will require you to override the form as well.

But don't worry, it's a piece of cake. Here's an overview on how you'll go about working with your form:

  • override the default submit action (thanks to the passed in event object, that has a preventDefault method)
  • grab all necessary values from the form
  • fire off an HTTP request
  • handle the response to the request

First, you'll have to cancel the form submit action like so:

$("#myform").submit(function(event) {
    // Cancels the form's submit action.
    event.preventDefault();
});

And then, grab the value of the data. Let's just assume you have one text box.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();
});

And then fire off a request. Let's just assume it's a POST request.

$("#myform").submit(function(event) {
    event.preventDefault();
    var val = $(this).find('input[type="text"]').val();

    // I like to use defers :)
    deferred = $.post("http://somewhere.com", { val: val });

    deferred.success(function () {
        // Do your stuff.
    });

    deferred.error(function () {
        // Handle any errors here.
    });
});

And this should about do it.

Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.

Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.

$.post("http://somewhere.com", { val: val }, function () {
    // Start partying here.
}, function () {
    // Handle the bad news here.
});

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

In year of 2020, these code seems to return exception as

System.Net.Mail.SmtpStatusCode.MustIssueStartTlsFirst or The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM

This code is working for me.

            using (SmtpClient client = new SmtpClient()
            {
                Host = "smtp.office365.com",
                Port = 587,
                UseDefaultCredentials = false, // This require to be before setting Credentials property
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential("[email protected]", "password"), // you must give a full email address for authentication 
                TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
                EnableSsl = true // Set to avoid secure connection exception
            })
            {

                MailMessage message = new MailMessage()
                {
                    From = new MailAddress("[email protected]"), // sender must be a full email address
                    Subject = subject,
                    IsBodyHtml = true,
                    Body = "<h1>Hello World</h1>",
                    BodyEncoding = System.Text.Encoding.UTF8,
                    SubjectEncoding = System.Text.Encoding.UTF8,

                };
                var toAddresses = recipients.Split(',');
                foreach (var to in toAddresses)
                {
                    message.To.Add(to.Trim());
                }

                try
                {
                    client.Send(message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

exception in initializer error in java when using Netbeans

You get an ExceptionInInitializerError if something goes wrong in the static initializer block.

class C
{
  static
  {
     // if something does wrong -> ExceptionInInitializerError
  }
}

Because static variables are initialized in static blocks there are a source of these errors too. An example:

class C
{
  static int v = D.foo();
}

=>

class C
{
  static int v;

  static
  {
    v = D.foo();
  }
}

So if foo() goes wild, you get a ExceptionInInitializerError.

Initial bytes incorrect after Java AES/CBC decryption

Online Editor Runnable version:-

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
//import org.apache.commons.codec.binary.Base64;
import java.util.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));

            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());

            //System.out.println("encrypted string: "
              //      + Base64.encodeBase64String(encrypted));

            //return Base64.encodeBase64String(encrypted);
            String s = new String(Base64.getEncoder().encode(encrypted));
            return s;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(encrypt(key, initVector, "Hello World"));
        System.out.println(decrypt(key, initVector, encrypt(key, initVector, "Hello World")));
    }
}

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How do I allow HTTPS for Apache on localhost?

This should be work Ubuntu, Mint similar with Apache2

It is a nice guide, so following this

https://www.digitalocean.com/community/tutorials/how-to-create-a-ssl-certificate-on-apache-for-ubuntu-14-04

and leaving your ssl.conf like this or similar similar

<VirtualHost _default_:443>
        ServerAdmin [email protected]
        ServerName localhost
        ServerAlias www.localhost.com

        DocumentRoot /var/www


    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

you can get it.

Hope this help for linuxer

Controlling mouse with Python

If you want to move the mouse, use this:

import pyautogui
pyautogui.moveTo(x,y)

If you want to click, use this:

import pyautogui
pyautogui.click(x,y)

If you don't have pyautogui installed, you must have python attached to CMD. Go to CMD and write: pip install pyautogui

This will install pyautogui for Python 2.x.

For Python 3.x, you will probably have to use pip3 install pyautogui or python3 -m pip install pyautogui.

Android, Java: HTTP POST Request

You can reuse the implementation I added to ACRA: http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236

(See the doPost(Map, Url) method, working over http and https even with self signed certs)

PHP Using RegEx to get substring of a string

Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.

There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.

Code (Demo)

$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';

Output:

736375493

What is a clean, Pythonic way to have multiple constructors in Python?

Why do you think your solution is "clunky"? Personally I would prefer one constructor with default values over multiple overloaded constructors in situations like yours (Python does not support method overloading anyway):

def __init__(self, num_holes=None):
    if num_holes is None:
        # Construct a gouda
    else:
        # custom cheese
    # common initialization

For really complex cases with lots of different constructors, it might be cleaner to use different factory functions instead:

@classmethod
def create_gouda(cls):
    c = Cheese()
    # ...
    return c

@classmethod
def create_cheddar(cls):
    # ...

In your cheese example you might want to use a Gouda subclass of Cheese though...

iPhone App Minus App Store?

Yes, once you have joined the iPhone Developer Program, and paid Apple $99, you can provision your applications on up to 100 iOS devices.

Calculate date from week number

Week 1 is defined as being the week that starts on a Monday and contains the first Thursday of the year.

HTML 5 Geo Location Prompt in Chrome

The easiest way is to click on the area left to the address bar and change location settings there. It allows to set location options even for file:///

enter image description here

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

Restful API service

I know @Martyn does not want full code, but I think this annotation its good for this question:

10 Open Source Android Apps which every Android developer must look into

Foursquared for Android is open-source, and have an interesting code pattern interacting with the foursquare REST API.

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

jQuery issue in Internet Explorer 8

The solution in my case was to take any special characters out of the URL you're trying to access. I had a tilde (~) and a percentage symbol in there, and the $.get() call failed silently.

String comparison using '==' vs. 'strcmp()'

if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".

How can I debug a Perl script?

perl -d your_script.pl args

is how you debug Perl. It launches you into an interactive gdb-style command line debugger.

How do I get the currently-logged username from a Windows service in .NET?

Try WindowsIdentity.GetCurrent(). You need to add reference to System.Security.Principal

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Executing <script> injected by innerHTML after AJAX call

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.

Removing App ID from Developer Connection

App IDs cannot be removed because once allocated they need to stay alive so that another App ID doesn't accidentally collide with a previously existing App ID.

Apple should however support hiding unwanted App IDs (instead of completely deleting them) to reduce clutter.

How to remove elements/nodes from angular.js array

My solution was quite straight forward

app.controller('TaskController', function($scope) {
 $scope.items = tasks;

    $scope.addTask = function(task) {
        task.created = Date.now();
        $scope.items.push(task);
        console.log($scope.items);
    };

    $scope.removeItem = function(item) {
        // item is the index value which is obtained using $index in ng-repeat
        $scope.items.splice(item, 1);
    }
});

Resize image proportionally with MaxHeight and MaxWidth constraints

Working Solution :

For Resize image with size lower then 100Kb

WriteableBitmap bitmap = new WriteableBitmap(140,140);
bitmap.SetSource(dlg.File.OpenRead());
image1.Source = bitmap;

Image img = new Image();
img.Source = bitmap;
WriteableBitmap i;

do
{
    ScaleTransform st = new ScaleTransform();
    st.ScaleX = 0.3;
    st.ScaleY = 0.3;
    i = new WriteableBitmap(img, st);
    img.Source = i;
} while (i.Pixels.Length / 1024 > 100);

More Reference at http://net4attack.blogspot.com/

JavaScript: filter() for Objects

Solution in Vanilla JS from year 2020.


let romNumbers={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}

You can filter romNumbers object by key:

const filteredByKey = Object.fromEntries(
    Object.entries(romNumbers).filter(([key, value]) => key === 'I') )
// filteredByKey = {I: 1} 

Or filter romNumbers object by value:

 const filteredByValue = Object.fromEntries(
    Object.entries(romNumbers).filter(([key, value]) => value === 5) )
 // filteredByValue = {V: 5} 

how to change directory using Windows command line

The "cd" command changes the directory, but not what drive you are working with. So when you go "cd d:\temp", you are changing the D drive's directory to temp, but staying in the C drive.

Execute these two commands:

D:
cd temp

That will get you the results you want.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

More based on the feeling, but this is the error you would get if you missed to declare a bean in the context configuration, so try adding

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000"/>
</bean>

understanding private setters

Say for instance, you do not store the actual variable through the property or use the value to calculate something.

In such case you can either create a method to do your calculation

private void Calculate(int value)
{
 //...
}

Or you can do so using

public int MyProperty {get; private set;}

In those cases I would recommend to use the later, as properties refactor each member element intact.

Other than that, if even say you map the property with a Variable. In such a case, within your code you want to write like this :

public int myprop;
public int MyProperty {get { return myprop;}}

... ...

this.myprop = 30;

... ...
if(this.MyProperty > 5)
   this.myprop = 40;

The code above looks horrible as the programmer need always cautious to use MyProperty for Get and myprop for Set.

Rether for consistency you can use a Private setter which makes the Propoerty readonly outside while you can use its setter inside in your code.

Hiding the scroll bar on an HTML page

If you want scrolling to work, before hiding scrollbars, consider styling them. Modern versions of OS X and mobile OS's have scrollbars that, while impractical for grabbing with a mouse, are quite beautiful and neutral.

To hide scrollbars, a technique by John Kurlak works well except for leaving Firefox users who don't have touchpads with no way to scroll unless they have a mouse with a wheel, which they probably do, but even then they can usually only scroll vertically.

John's technique uses three elements:

  • An outer element to mask the scrollbars.
  • A middle element to have the scrollbars.
  • And a content element to both set the size of the middle element and make it have scrollbars.

It must be possible to set the size of the outer and content elements the same which eliminates using percentages, but I can't think of anything else that won't work with the right tweaking.

My biggest concern is whether all versions of browsers set scrollbars to make visible overflowed content visible. I have tested in current browsers, but not older ones.

Pardon my SASS ;P

%size {
    // set width and height
}

.outer {
    // mask scrollbars of child
    overflow: hidden;
    // set mask size
    @extend %size;
    // has absolutely positioned child
    position: relative;
}

.middle {
    // always have scrollbars.
    // don't use auto, it leaves vertical scrollbar showing
    overflow: scroll;
    // without absolute, the vertical scrollbar shows
    position: absolute;
}
// prevent text selection from revealing scrollbar, which it only does on
// some webkit based browsers.
.middle::-webkit-scrollbar {
    display: none;
}

.content {
    // push scrollbars behind mask
    @extend %size;
}

Testing

OS X is 10.6.8. Windows is Windows 7.

  • Firefox 32.0 Scrollbars hidden. Arrow keys don't scroll, even after clicking to focus, but mouse wheel and two fingers on trackpad do. OS X and Windows.
  • Chrome 37.0 Scrollbars hidden. Arrow keys work after clicking to focus. Mouse wheel and trackpad work. OS X and Windows.
  • Internet Explorer 11 Scrollbars hidden. Arrow keys work after clicking to focus. Mouse wheel works. Windows.
  • Safari 5.1.10 Scrollbars hidden. Arrow keys work after clicking to focus. Mouse wheel and trackpad work. OS X.
  • Android 4.4.4 and 4.1.2. Scrollbars hidden. Touch scrolling works. Tried in Chrome 37.0, Firefox 32.0, and HTMLViewer on 4.4.4 (whatever that is). In HTMLViewer, the page is the size of the masked content and can be scrolled too! Scrolling interacts acceptably with page zooming.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Bad: (jsHint will throw a error)

for (var name in item) {
    console.log(item[name]);
}

Good:

for (var name in item) {
  if (item.hasOwnProperty(name)) {
    console.log(item[name]);
  }
}

string.split - by multiple character delimiter

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

how do I get the bullet points of a <ul> to center with the text?

Add list-style-position: inside to the ul element. (example)

The default value for the list-style-position property is outside.

_x000D_
_x000D_
ul {_x000D_
    text-align: center;_x000D_
    list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Another option (which yields slightly different results) would be to center the entire ul element:

_x000D_
_x000D_
.parent {_x000D_
  text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Given a view, how do I get its viewController?

@andrey answer in one line (tested in Swift 4.1):

extension UIResponder {
    public var parentViewController: UIViewController? {
        return next as? UIViewController ?? next?.parentViewController
    }
}

usage:

 let vc: UIViewController = view.parentViewController

What __init__ and self do in Python?

What does self do? What is it meant to be? Is it mandatory?

The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.

Python doesn't force you on using "self". You can give it any name you want. But remember the first argument in a method definition is a reference to the object. Python adds the self argument to the list for you; you do not need to include it when you call the methods. if you didn't provide self in init method then you will get an error

TypeError: __init___() takes no arguments (1 given)

What does the init method do? Why is it necessary? (etc.)

init is short for initialization. It is a constructor which gets called when you make an instance of the class and it is not necessary. But usually it our practice to write init method for setting default state of the object. If you are not willing to set any state of the object initially then you don't need to write this method.

What is the difference between screenX/Y, clientX/Y and pageX/Y?

In JavaScript:

pageX, pageY, screenX, screenY, clientX, and clientY returns a number which indicates the number of physical “CSS pixels” a point is from the reference point. The event point is where the user clicked, the reference point is a point in the upper left. These properties return the horizontal and vertical distance from that reference point.

pageX and pageY:
Relative to the top left of the fully rendered content area in the browser. This reference point is below the URL bar and back button in the upper left. This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

screenX and screenY:
Relative to the top left of the physical screen/monitor, this reference point only moves if you increase or decrease the number of monitors or the monitor resolution.

clientX and clientY:
Relative to the upper left edge of the content area (the viewport) of the browser window. This point does not move even if the user moves a scrollbar from within the browser.

For a visual on which browsers support which properties:

http://www.quirksmode.org/dom/w3c_cssom.html#t03

w3schools has an online Javascript interpreter and editor so you can see what each does

http://www.w3schools.com/jsref/tryit.asp?filename=try_dom_event_clientxy

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script>_x000D_
function show_coords(event)_x000D_
{_x000D_
  var x=event.clientX;_x000D_
  var y=event.clientY;_x000D_
  alert("X coords: " + x + ", Y coords: " + y);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p onmousedown="show_coords(event)">Click this paragraph, _x000D_
and an alert box will alert the x and y coordinates _x000D_
of the mouse pointer.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Vue.js get selected option on @change

Use v-model to bind the value of selected option's value. Here is an example.

<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
   <option value="1">Annual Leave/ Off-Day</option>
   <option value="2">On Demand Leave</option>
</select>
<script>
var vm = new Vue({
    data: {
        key: ""
    },
    methods: {
        onChange(event) {
            console.log(event.target.value)
        }
    }
}
</script>

More reference can been seen from here.

Formatting a double to two decimal places

Well, depending on your needs you can choose any of the following. Out put is written against each method

You can choose the one you need

This will round

decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58

This will ensure that 2 decimal places are written.

d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50

if you want to write commas you can use this

d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54

if you want to return the rounded of decimal value you can do this

d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58

Find the day of a week

start = as.POSIXct("2017-09-01")
end = as.POSIXct("2017-09-06")

dat = data.frame(Date = seq.POSIXt(from = start,
                                   to = end,
                                   by = "DSTday"))

# see ?strptime for details of formats you can extract

# day of the week as numeric (Monday is 1)
dat$weekday1 = as.numeric(format(dat$Date, format = "%u"))

# abbreviated weekday name
dat$weekday2 = format(dat$Date, format = "%a")

# full weekday name
dat$weekday3 = format(dat$Date, format = "%A")

dat
# returns
    Date       weekday1 weekday2  weekday3
1 2017-09-01        5      Fri    Friday
2 2017-09-02        6      Sat    Saturday
3 2017-09-03        7      Sun    Sunday
4 2017-09-04        1      Mon    Monday
5 2017-09-05        2      Tue    Tuesday
6 2017-09-06        3      Wed    Wednesday

lexers vs parsers

When is lexing enough, when do you need EBNF?

EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:

S --> A | B

you can achieve in CNF by just listing each alternative production separately:

S --> A      // `S` can be `A`,
S --> B      // or it can be `B`.

The optional element from EBNF:

S --> X?

you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):

S --> B       // `S` can be `B`,
B --> X       // and `B` can be just `X`,
B -->         // or it can be empty.

A production in a form like the last one B above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).

Zero-or-more repetiton from EBNF:

S --> A*

you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):

S --> S A    // `S` is just itself ended with `A` (which can be done many times),
S -->        // or it can begin with empty-string, which stops the recursion.

Knowing that it generates just an empty string (ultimately) followed by zero or more As, the same string (but not the same language!) can be expressed using right-recursion:

S --> A S    // `S` can be `A` followed by itself (which can be done many times),
S -->        // or it can be just empty-string end, which stops the recursion.

And when it comes to + for one-or-more repetition from EBNF:

S --> A+

it can be done by factoring out one A and using * as before:

S --> A A*

which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):

S --> A S   // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A     // or it could be just one single `A`.

Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:

A -->        // Empty (nullable) production (AKA erasure).
B --> x      // Single terminal symbol.
C --> y D    // Simple state change from `C` to `D` when seeing input `y`.
E --> F z    // Simple state change from `E` to `F` when seeing input `z`.
G --> G u    // Left recursion.
H --> v H    // Right recursion.

That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.

But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:

S --> a S b    // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S -->          // or it could be (ultimately) empty, which ends recursion.

then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S indefinitely, which will always add another as and bs on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many as were there to match them evenly with so many bs. Grammars like this are called context-free grammars (at the very least), and they require a parser.

Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:

A R B --> A S B

You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R into S, but only when it's in between A and B, leaving those A and B themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.

Generating Unique Random Numbers in Java

I feel like this method is worth mentioning.

   private static final Random RANDOM = new Random();    
   /**
     * Pick n numbers between 0 (inclusive) and k (inclusive)
     * While there are very deterministic ways to do this,
     * for large k and small n, this could be easier than creating
     * an large array and sorting, i.e. k = 10,000
     */
    public Set<Integer> pickRandom(int n, int k) {
        final Set<Integer> picked = new HashSet<>();
        while (picked.size() < n) {
            picked.add(RANDOM.nextInt(k + 1));
        }
        return picked;
    }

Styling text input caret

In CSS3, there is now a native way to do this, without any of the hacks suggested in the existing answers: the caret-color property.

There are a lot of things you can do to with the caret, as seen below. It can even be animated.

/* Keyword value */
caret-color: auto;
color: transparent;
color: currentColor;

/* <color> values */
caret-color: red;
caret-color: #5729e9;
caret-color: rgb(0, 200, 0);
caret-color: hsla(228, 4%, 24%, 0.8);

The caret-color property is supported from Firefox 55, and Chrome 60. Support is also available in the Safari Technical Preview and in Opera (but not yet in Edge). You can view the current support tables here.

What is the best way to check for Internet connectivity using .NET?

For my application we also test by download tiny file.

string remoteUri = "https://www.microsoft.com/favicon.ico"

WebClient myWebClient = new WebClient();

try
{
    byte[] myDataBuffer = myWebClient.DownloadData (remoteUri);
    if(myDataBuffer.length > 0) // Or add more validate. eg. checksum
    {
        return true;
    }
}
catch
{
    return false;
}

Also. Some ISP may use middle server to cache file. Add random unused parameter eg. https://www.microsoft.com/favicon.ico?req=random_number Can prevent caching.

CSS: Set Div height to 100% - Pixels

100vh works for me, but at first I had used javascript (actually jQuery, but you can adapt it), to tackle a similar problw.

HTML

<body>
  <div id="wrapper">
    <div id="header">header</div>
    <div id="content">content</div>
  </div>
</body>

js/jQuery

var innerWindowHeight = $(window).height();
var headerHeight = $("#header").height();
var contentHeight = innerWindowHeight - headerHeight;
$(".content").height(contentHeight + "px");

Alternately, you can just use 111px if you don't want to calculate headerHeight.

Also, you may want to put this in a window resize event, to rerun the script if the window height increases for example.

How to spyOn a value property (rather than a method) with Jasmine

I'm using a kendo grid and therefore can't change the implementation to a getter method but I want to test around this (mocking the grid) and not test the grid itself. I was using a spy object but this doesn't support property mocking so I do this:

    this.$scope.ticketsGrid = { 
        showColumn: jasmine.createSpy('showColumn'),
        hideColumn: jasmine.createSpy('hideColumn'),
        select: jasmine.createSpy('select'),
        dataItem: jasmine.createSpy('dataItem'),
        _data: []
    } 

It's a bit long winded but it works a treat

JSON.Net Self referencing loop detected

If using ASP.NET Core MVC, add this to the ConfigureServices method of your startup.cs file:

services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling =            
        Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

Counting the number of non-NaN elements in a numpy ndarray in Python

np.count_nonzero(~np.isnan(data))

~ inverts the boolean matrix returned from np.isnan.

np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero

Testing speed:

In [23]: data = np.random.random((10000,10000))

In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan

In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop

In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop

In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop

data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.

How do you Encrypt and Decrypt a PHP String?

Updated

PHP 7 ready version. It uses openssl_encrypt function from PHP OpenSSL Library.

class Openssl_EncryptDecrypt {
    function encrypt ($pure_string, $encryption_key) {
        $cipher     = 'AES-256-CBC';
        $options    = OPENSSL_RAW_DATA;
        $hash_algo  = 'sha256';
        $sha2len    = 32;
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $ciphertext_raw = openssl_encrypt($pure_string, $cipher, $encryption_key, $options, $iv);
        $hmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
        return $iv.$hmac.$ciphertext_raw;
    }
    function decrypt ($encrypted_string, $encryption_key) {
        $cipher     = 'AES-256-CBC';
        $options    = OPENSSL_RAW_DATA;
        $hash_algo  = 'sha256';
        $sha2len    = 32;
        $ivlen = openssl_cipher_iv_length($cipher);
        $iv = substr($encrypted_string, 0, $ivlen);
        $hmac = substr($encrypted_string, $ivlen, $sha2len);
        $ciphertext_raw = substr($encrypted_string, $ivlen+$sha2len);
        $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $encryption_key, $options, $iv);
        $calcmac = hash_hmac($hash_algo, $ciphertext_raw, $encryption_key, true);
        if(function_exists('hash_equals')) {
            if (hash_equals($hmac, $calcmac)) return $original_plaintext;
        } else {
            if ($this->hash_equals_custom($hmac, $calcmac)) return $original_plaintext;
        }
    }
    /**
     * (Optional)
     * hash_equals() function polyfilling.
     * PHP 5.6+ timing attack safe comparison
     */
    function hash_equals_custom($knownString, $userString) {
        if (function_exists('mb_strlen')) {
            $kLen = mb_strlen($knownString, '8bit');
            $uLen = mb_strlen($userString, '8bit');
        } else {
            $kLen = strlen($knownString);
            $uLen = strlen($userString);
        }
        if ($kLen !== $uLen) {
            return false;
        }
        $result = 0;
        for ($i = 0; $i < $kLen; $i++) {
            $result |= (ord($knownString[$i]) ^ ord($userString[$i]));
        }
        return 0 === $result;
    }
}

define('ENCRYPTION_KEY', '__^%&Q@$&*!@#$%^&*^__');
$string = "This is the original string!";

$OpensslEncryption = new Openssl_EncryptDecrypt;
$encrypted = $OpensslEncryption->encrypt($string, ENCRYPTION_KEY);
$decrypted = $OpensslEncryption->decrypt($encrypted, ENCRYPTION_KEY);

Browser Caching of CSS files

It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.

<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />

Some frameworks (e.g. rails) put these in by default.

However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.

All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)

add a string prefix to each value in a string column using Pandas

If you load you table file with dtype=str
or convert column type to string df['a'] = df['a'].astype(str)
then you can use such approach:

df['a']= 'col' + df['a'].str[:]

This approach allows prepend, append, and subset string of df.
Works on Pandas v0.23.4, v0.24.1. Don't know about earlier versions.

Invalid default value for 'create_date' timestamp field

To avoid this issue, you need to remove NO_ZERO_DATE from the mysql mode configuration.

  1. Go to 'phpmyadmin'.
  2. Once phpmyadmin is loaded up, click on the 'variables' tab.
  3. Search for 'sql mode'.
  4. Click on the Edit option and remove NO_ZERO_DATE (and its trailing comma) from the configuration.

This is a very common issue in the local environment with wamp or xamp.

How to send multiple data fields via Ajax?

You can send data through JSON or via normal POST, here is an example for JSON.

 var value1 = 1;
 var value2 = 2;
 var value3 = 3;   
 $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "yoururlhere",
      data: { data1: value1, data2: value2, data3: value3 },
      success: function (result) {
           // do something here
      }
 });

If you want to use it via normal post try this

 $.ajax({
      type: "POST",
      url: $('form').attr("action"),   
      data: $('#form0').serialize(),
      success: function (result) {
         // do something here
      }
 });

Connect to docker container as user other than root

Execute command as www-data user: docker exec -t --user www-data container bash -c "ls -la"

How to simulate POST request?

Postman is the best application to test your APIs !

You can import or export your routes and let him remember all your body requests ! :)

EDIT : This comment is 5 yea's old and deprecated :D

Here's the new Postman App : https://www.postman.com/

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

How can I convert string to datetime with format specification in JavaScript?

//Here pdate is the string date time
var date1=GetDate(pdate);
    function GetDate(a){
        var dateString = a.substr(6);
        var currentTime = new Date(parseInt(dateString ));
        var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
        var day =("0"+ currentTime.getDate()).slice(-2);
        var year = currentTime.getFullYear();
        var date = day + "/" + month + "/" + year;
        return date;
    }

Warn user before leaving web page with unsaved changes

Short answer:

let pageModified = true

window.addEventListener("beforeunload", 
  () => pageModified ? 'Close page without saving data?' : null
)

Edit seaborn legend

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()

enter image description here

Moreover you may combine both situations and use this code:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)

sns.plt.show()

This code works for any seaborn plot which is based on Grid class.

How do I check whether a file exists without exceptions?

Prefer the try statement. It's considered better style and avoids race conditions.

Don't take my word for it. There's plenty of support for this theory. Here's a couple:

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

python dict to numpy structured array

I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.

But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()

But my favorite is this (simpler):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

arrays = {'names': np.array(result.keys(), dtype=float),
          'values': np.array(result.values(), dtype=float)}

What is the "-->" operator in C/C++?

Actually, x is post-decrementing and with that condition is being checked. It's not -->, it's (x--) > 0

Note: value of x is changed after the condition is checked, because it post-decrementing. Some similar cases can also occur, for example:

-->    x-->0
++>    x++>0
-->=   x-->=0
++>=   x++>=0

How to check iOS version?

Starting Xcode 9, in Objective-C:

if (@available(iOS 11, *)) {
    // iOS 11 (or newer) ObjC code
} else {
    // iOS 10 or older code
}

Starting Xcode 7, in Swift:

if #available(iOS 11, *) {
    // iOS 11 (or newer) Swift code
} else {
    // iOS 10 or older code
}

For the version, you can specify the MAJOR, the MINOR or the PATCH (see http://semver.org/ for definitions). Examples:

  • iOS 11 and iOS 11.0 are the same minimal version
  • iOS 10, iOS 10.3, iOS 10.3.1 are different minimal versions

You can input values for any of those systems:

  • iOS, macOS, watchOS, tvOS

Real case example taken from one of my pods:

if #available(iOS 10.0, tvOS 10.0, *) {
    // iOS 10+ and tvOS 10+ Swift code
} else {
    // iOS 9 and tvOS 9 older code
}

documentation

Timer for Python game

For a StopWatch helper class, here is my solution which gives you precision on output and also access to the raw start time:

class StopWatch:
    def __init__(self):
        self.start()
    def start(self):
        self._startTime = time.time()
    def getStartTime(self):
        return self._startTime
    def elapsed(self, prec=3):
        prec = 3 if prec is None or not isinstance(prec, (int, long)) else prec
        diff= time.time() - self._startTime
        return round(diff, prec)
def round(n, p=0):
    m = 10 ** p
    return math.floor(n * m + 0.5) / m

VBA copy rows that meet criteria to another sheet

After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter to a separate sheet.

With .Range("A1:A" & LastRow)
    .Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
    .Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
    Sheets("Sheet2").activate
    DestinationRange.PasteSpecial
End With

In this block, the AutoFilter finds all of the rows that contain the value of strSearch and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.

Select first 10 distinct rows in mysql

Try this SELECT DISTINCT 10 * ...

Allow 2 decimal places in <input type="number">

just write

<input type="number" step="0.1" lang="nb">

lang='nb" let you write your decimal numbers with comma or period

sql query with multiple where statements

You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row.

And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted.

According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start:

SELECT items.* FROM items i, meta_data m1, meta_data m2
    WHERE i.item_id = m1.item_id and i.item_id = m2.item_id
    AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65
    AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30

How to use Elasticsearch with MongoDB?

Using river can present issues when your operation scales up. River will use a ton of memory when under heavy operation. I recommend implementing your own elasticsearch models, or if you're using mongoose you can build your elasticsearch models right into that or use mongoosastic which essentially does this for you.

Another disadvantage to Mongodb River is that you'll be stuck using mongodb 2.4.x branch, and ElasticSearch 0.90.x. You'll start to find that you're missing out on a lot of really nice features, and the mongodb river project just doesn't produce a usable product fast enough to keep stable. That said Mongodb River is definitely not something I'd go into production with. It's posed more problems than its worth. It will randomly drop write under heavy load, it will consume lots of memory, and there's no setting to cap that. Additionally, river doesn't update in realtime, it reads oplogs from mongodb, and this can delay updates for as long as 5 minutes in my experience.

We recently had to rewrite a large portion of our project, because its a weekly occurrence that something goes wrong with ElasticSearch. We had even gone as far as to hire a Dev Ops consultant, who also agrees that its best to move away from River.

UPDATE: Elasticsearch-mongodb-river now supports ES v1.4.0 and mongodb v2.6.x. However, you'll still likely run into performance problems on heavy insert/update operations as this plugin will try to read mongodb's oplogs to sync. If there are a lot of operations since the lock(or latch rather) unlocks, you'll notice extremely high memory usage on your elasticsearch server. If you plan on having a large operation, river is not a good option. The developers of ElasticSearch still recommend you to manage your own indexes by communicating directly with their API using the client library for your language, rather than using river. This isn't really the purpose of river. Twitter-river is a great example of how river should be used. Its essentially a great way to source data from outside sources, but not very reliable for high traffic or internal use.

Also consider that mongodb-river falls behind in version, as its not maintained by ElasticSearch Organization, its maintained by a thirdparty. Development was stuck on v0.90 branch for a long time after the release of v1.0, and when a version for v1.0 was released it wasn't stable until elasticsearch released v1.3.0. Mongodb versions also fall behind. You may find yourself in a tight spot when you're looking to move to a later version of each, especially with ElasticSearch under such heavy development, with many very anticipated features on the way. Staying up on the latest ElasticSearch has been very important as we rely heavily on constantly improving our search functionality as its a core part of our product.

All in all you'll likely get a better product if you do it yourself. Its not that difficult. Its just another database to manage in your code, and it can easily be dropped in to your existing models without major refactoring.

What is the use of the JavaScript 'bind' method?

Simple example

function lol(second, third) {
    console.log(this.first, second, third);
}

lol(); // undefined, undefined, undefined
lol('1'); // undefined, "1", undefined
lol('1', '2'); // undefined, "1", "2"

lol.call({first: '1'}); // "1", undefined, undefined
lol.call({first: '1'}, '2'); // "1", "2", undefined
lol.call({first: '1'}, '2', '3'); // "1", "2", "3"

lol.apply({first: '1'}); // "1", undefined, undefined
lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"

const newLol = lol.bind({first: '1'}); 
newLol(); // "1", undefined, undefined
newLol('2'); // "1", "2", undefined
newLol('2', '3'); // "1", "2", "3"

const newOmg = lol.bind({first: '1'}, '2');
newOmg(); // "1", "2", undefined
newOmg('3'); // "1", "2", "3"

const newWtf = lol.bind({first: '1'}, '2', '3');
newWtf(); // "1", "2", "3"

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

Try to give the full path to your csv file

open('/users/gcameron/Desktop/map/data.csv')

The python process is looking for file in the directory it is running from.

Is there a developers api for craigslist.org

Good news everybody! Craigslist has actually released a bulk posting api now!

Enjoy

Underscore prefix for property and method names in JavaScript

import/export is now doing the job with ES6. I still tend to prefix not exported functions with _ if most of my functions are exported.

If you export only a class (like in angular projects), it's not needed at all.

export class MyOpenClass{

    open(){
         doStuff()
         this._privateStuff()
         return close();
    }

    _privateStuff() { /* _ only as a convention */} 

}

function close(){ /*... this is really private... */ }

What is the regex for "Any positive integer, excluding 0"

Try this one, this one works best to suffice the requiremnt.

[1-9][0-9]*

Here is the sample output

String 0 matches regex: false
String 1 matches regex: true
String 2 matches regex: true
String 3 matches regex: true
String 4 matches regex: true
String 5 matches regex: true
String 6 matches regex: true
String 7 matches regex: true
String 8 matches regex: true
String 9 matches regex: true
String 10 matches regex: true
String 11 matches regex: true
String 12 matches regex: true
String 13 matches regex: true
String 14 matches regex: true
String 15 matches regex: true
String 16 matches regex: true
String 999 matches regex: true
String 2654 matches regex: true
String 25633 matches regex: true
String 254444 matches regex: true
String 0.1 matches regex: false
String 0.2 matches regex: false
String 0.3 matches regex: false
String -1 matches regex: false
String -2 matches regex: false
String -5 matches regex: false
String -6 matches regex: false
String -6.8 matches regex: false
String -9 matches regex: false
String -54 matches regex: false
String -29 matches regex: false
String 1000 matches regex: true
String 100000 matches regex: true

Nginx: Job for nginx.service failed because the control process exited

I'm using RHEL 7.4 with NGINX 1.13.8 and if I do the same with sudo, it works Ok:

sudo systemctl status nginx.service

Just make sure whoever wants to use nginx.service has execute permissions to it.

How to find minimum value from vector?

std::min_element(vec.begin(), vec.end()) - for std::vector
std::min_element(v, v+n) - for array
std::min_element( std::begin(v), std::end(v) ) - added C++11 version from comment by @JamesKanze

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

If you want to check syntax error for any nginx files, you can use the -c option.

[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]# 

Serialize an object to XML

my work code. Returns utf8 xml enable empty namespace.

// override StringWriter
public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

private string GenerateXmlResponse(Object obj)
{    
    Type t = obj.GetType();

    var xml = "";

    using (StringWriter sww = new Utf8StringWriter())
    {
        using (XmlWriter writer = XmlWriter.Create(sww))
        {
            var ns = new XmlSerializerNamespaces();
            // add empty namespace
            ns.Add("", "");
            XmlSerializer xsSubmit = new XmlSerializer(t);
            xsSubmit.Serialize(writer, obj, ns);
            xml = sww.ToString(); // Your XML
        }
    }
    return xml;
}

Example returns response Yandex api payment Aviso url:

<?xml version="1.0" encoding="utf-8"?><paymentAvisoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" performedDatetime="2017-09-01T16:22:08.9747654+07:00" code="0" shopId="54321" invoiceId="12345" orderSumAmount="10643" />

Get index of array element faster than O(n)

Taking a combination of @sawa's answer and the comment listed there you could implement a "quick" index and rindex on the array class.

class Array
  def quick_index el
    hash = Hash[self.map.with_index.to_a]
    hash[el]
  end

  def quick_rindex el
    hash = Hash[self.reverse.map.with_index.to_a]
    array.length - 1 - hash[el]
  end
end

Trying to merge 2 dataframes but get ValueError

this simple solution works for me

    final = pd.concat([df, rankingdf], axis=1, sort=False)

but you may need to drop some duplicate column first.

What causes HttpHostConnectException?

A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.

If this is happening intermittently, then the most likely explanations are (IMO):

  • the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
  • there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.

Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.

It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.


1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.

Using HTML5/JavaScript to generate and save a file

You can use localStorage. This is the Html5 equivalent of cookies. It appears to work on Chrome and Firefox BUT on Firefox, I needed to upload it to a server. That is, testing directly on my home computer didn't work.

I'm working up HTML5 examples. Go to http://faculty.purchase.edu/jeanine.meyer/html5/html5explain.html and scroll to the maze one. The information to re-build the maze is stored using localStorage.

I came to this article looking for HTML5 JavaScript for loading and working with xml files. Is it the same as older html and JavaScript????

Nginx reverse proxy causing 504 Gateway Timeout

If you want to increase or add time limit to all sites then you can add below lines to the nginx.conf file.

Add below lines to the http section of /usr/local/etc/nginx/nginx.conf or /etc/nginx/nginx.conf file.

fastcgi_read_timeout 600;
proxy_read_timeout 600;

If the above lines doesn't exist in conf file then add them, otherwise increase fastcgi_read_timeout and proxy_read_timeout to make sure that nginx and php-fpm did not timeout.

To increase time limit for only one site then you can edit in vim /etc/nginx/sites-available/example.com

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
        fastcgi_pass  unix:/var/run/php5-fpm.sock;
    fastcgi_read_timeout 300; 
}

and after adding these lines in nginx.conf, then don't forget to restart nginx.

service php7-fpm reload 
service nginx reload

or, if you're using valet then simply type valet restart.

How can I get the application's path in a .NET console application?

I have used this code and get the solution.

AppDomain.CurrentDomain.BaseDirectory

Python memory leaks

Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.

How do I change data-type of pandas data frame to string with a defined format?

I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:

s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])

Prevent scroll-bar from adding-up to the Width of page on Chrome

For containers with a fixed width a pure CSS cross browser solution can be accomplished by wrapping the container into another div and applying the same width to both divs.

#outer {
  overflow-y: auto;
  overflow-x: hidden;
  /*
   * width must be an absolute value otherwise the inner divs width must be set via
   * javascript to the computed width of the parent container
   */
  width: 200px;
}

#inner {
  width: inherit;
}

Click here to see an example on Codepen

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

async await return Task

Adding the async keyword is just syntactic sugar to simplify the creation of a state machine. In essence, the compiler takes your code;

public async Task MethodName()
{
     return null;
}

And turns it into;

public Task MethodName()
{
     return Task.FromResult<object>(null);
}

If your code has any await keywords, the compiler must take your method and turn it into a class to represent the state machine required to execute it. At each await keyword, the state of variables and the stack will be preserved in the fields of the class, the class will add itself as a completion hook to the task you are waiting on, then return.

When that task completes, your task will be executed again. So some extra code is added to the top of the method to restore the state of variables and jump into the next slab of your code.

See What does async & await generate? for a gory example.

This process has a lot in common with the way the compiler handles iterator methods with yield statements.

Binary search (bisection) in Python

bisect_left finds the first position p at which an element could be inserted in a given sorted range while maintaining the sorted order. That will be the position of x if x exists in the range. If p is the past-the-end position, x wasn't found. Otherwise, we can test to see if x is there to see if x was found.

from bisect import bisect_left

def binary_search(a, x, lo=0, hi=None):
    if hi is None: hi = len(a)
    pos = bisect_left(a, x, lo, hi)                  # find insertion position
    return pos if pos != hi and a[pos] == x else -1  # don't walk off the end

How to get the width of a react element

    class MyComponent extends Component {
      constructor(props){
        super(props)
        this.myInput = React.createRef()
      }

      componentDidMount () {
        console.log(this.myInput.current.offsetWidth)
      }

      render () {
        return (
        // new way - as of [email protected]
        <div ref={this.myInput}>some elem</div>
        // legacy way
        // <div ref={(ref) => this.myInput = ref}>some elem</div>
        )
      }
    }

Global constants file in Swift

According to the swift docs global variables are declared in file scope.

Global variables are variables that are defined outside of any function, method, closure, or type context

Just create a swift file (E.g: Constnats.swift) and declare your constants there:

// Constants.swift

let SOME_NOTIF = "aaaaNotification"

and call it from anywhere in your project without the need to mention struct,enum or class name.

// MyViewController.swift

NotificationCenter.default.post(name: SOME_NOTIF, object: nil)

I think this is much better for code readability.

Convert Xml to DataTable

DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);

Javascript variable access in HTML

The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph). Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.

Example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <body>_x000D_
        <!--\|/id here-->_x000D_
        <p id="myText"></p>_x000D_
        <p id="myTextTag"></p>_x000D_
        <script>_x000D_
            <!--Here we retrieve the text and show what we want to write..._x000D_
            var text = document.getElementById("myText");_x000D_
            var tag = document.getElementById("myTextTag");_x000D_
            var toWrite = "Hello"_x000D_
            var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"_x000D_
            <!--...and here we are actually affecting the text.-->_x000D_
            text.innerHTML = toWrite_x000D_
            tag.innerHTML = toWriteTag_x000D_
        </script>_x000D_
    <body>_x000D_
<html>
_x000D_
_x000D_
_x000D_

.attr("disabled", "disabled") issue

To add disabled attribute

$('#id').attr("disabled", "true");

To remove Disabled Attribute

$('#id').removeAttr('disabled');

Setting PATH environment variable in OSX permanently

If you are using zsh do the following.

  1. Open .zshrc file nano $HOME/.zshrc

  2. You will see the commented $PATH variable here

    # If you come from bash you might have to change your $PATH.
    # export PATH=$HOME/bin:/usr/local/...

  3. Remove the comment symbol(#) and append your new path using a separator(:) like this.

export PATH=$HOME/bin:/usr/local/bin:/Users/ebin/Documents/Softwares/mongoDB/bin:$PATH

  1. Activate the change source $HOME/.zshrc

You're done !!!

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

To help newbies navigate through the manual fog, it might be helpful to see the [[ ... ]] notation as a collapsing function - in other words, it is when you just want to 'get the data' from a named vector, list or data frame. It is good to do this if you want to use data from these objects for calculations. These simple examples will illustrate.

(x <- c(x=1, y=2)); x[1]; x[[1]]
(x <- list(x=1, y=2, z=3)); x[1]; x[[1]]
(x <- data.frame(x=1, y=2, z=3)); x[1]; x[[1]]

So from the third example:

> 2 * x[1]
  x
1 2
> 2 * x[[1]]
[1] 2

How to filter (key, value) with ng-repeat in AngularJs?

Or simply use

ng-show="v.hasOwnProperty('secId')"

See updated solution here:

http://jsfiddle.net/RFontana/WA2BE/93/

Style the first <td> column of a table differently

This should help. Its CSS3 :first-child where you should say that the first tr of the table you would like to style. http://reference.sitepoint.com/css/pseudoclass-firstchild

C# LINQ find duplicates in List

You can do this:

var list = new[] {1,2,3,1,4,2};
var duplicateItems = list.Duplicates();

With these extension methods:

public static class Extensions
{
    public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
    {
        var grouped = source.GroupBy(selector);
        var moreThan1 = grouped.Where(i => i.IsMultiple());
        return moreThan1.SelectMany(i => i);
    }

    public static IEnumerable<TSource> Duplicates<TSource, TKey>(this IEnumerable<TSource> source)
    {
        return source.Duplicates(i => i);
    }

    public static bool IsMultiple<T>(this IEnumerable<T> source)
    {
        var enumerator = source.GetEnumerator();
        return enumerator.MoveNext() && enumerator.MoveNext();
    }
}

Using IsMultiple() in the Duplicates method is faster than Count() because this does not iterate the whole collection.

Error 1022 - Can't write; duplicate key in table

From the two linksResolved Successfully and Naming Convention, I easily solved this same problem which I faced. i.e., for the foreign key name, give as fk_colName_TableName. This naming convention is non-ambiguous and also makes every ForeignKey in your DB Model unique and you will never get this error.

Error 1022: Can't write; duplicate key in table

How do I install imagemagick with homebrew?

brew install imagemagick

Don't forget to install also gs which is a dependency if you want to convert pdf to images for example :

brew install ghostscript

Extracting jar to specified directory

This worked for me.

I created a folder then changed into the folder using CD option from command prompt.

Then executed the jar from there.

d:\LS\afterchange>jar xvf ..\mywar.war

Giving UIView rounded corners

Try this

#import <QuartzCore/QuartzCore.h> // not necessary for 10 years now  :)

...

view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;

Note: If you are trying to apply rounded corners to a UIViewController's view, it should not be applied in the view controller's constructor, but rather in -viewDidLoad, after view is actually instantiated.

Best practice: PHP Magic Methods __set and __get

I have been exactly in your case in the past. And I went for magic methods.

This was a mistake, the last part of your question says it all :

  • this is slower (than getters/setters)
  • there is no auto-completion (and this is a major problem actually), and type management by the IDE for refactoring and code-browsing (under Zend Studio/PhpStorm this can be handled with the @property phpdoc annotation but that requires to maintain them: quite a pain)
  • the documentation (phpdoc) doesn't match how your code is supposed to be used, and looking at your class doesn't bring much answers as well. This is confusing.
  • added after edit: having getters for properties is more consistent with "real" methods where getXXX() is not only returning a private property but doing real logic. You have the same naming. For example you have $user->getName() (returns private property) and $user->getToken($key) (computed). The day your getter gets more than a getter and needs to do some logic, everything is still consistent.

Finally, and this is the biggest problem IMO : this is magic. And magic is very very bad, because you have to know how the magic works to use it properly. That's a problem I've met in a team: everybody has to understand the magic, not just you.

Getters and setters are a pain to write (I hate them) but they are worth it.

Simulating ENTER keypress in bash script

You can just use yes.

# yes "" | someCommand

Mac OS X and multiple Java versions

Here's a more DRY version for bash (Based on Vegard's answer)

Replace 1.7 and 1.8 with whatever versions you are interested with and you'll get an alias called 'javaX'; where 'X' is the java version (7 / 8 in the snippet below) that will allow you to easily switch versions

for version in 1.7 1.8; do
    v="${version: -1}"
    h=JAVA_"$v"_HOME

    export "$h"=$(/usr/libexec/java_home -v $version)

    alias "java$v"="export JAVA_HOME=\$$h"
done

Why is there no ForEach extension method on IEnumerable?

You could use the (chainable, but lazily evaluated) Select, first doing your operation, and then returning identity (or something else if you prefer)

IEnumerable<string> people = new List<string>(){"alica", "bob", "john", "pete"};
people.Select(p => { Console.WriteLine(p); return p; });

You will need to make sure it is still evaluated, either with Count() (the cheapest operation to enumerate afaik) or another operation you needed anyway.

I would love to see it brought in to the standard library though:

static IEnumerable<T> WithLazySideEffect(this IEnumerable<T> src, Action<T> action) {
  return src.Select(i => { action(i); return i; } );
}

The above code then becomes people.WithLazySideEffect(p => Console.WriteLine(p)) which is effectively equivalent to foreach, but lazy and chainable.

Importing PNG files into Numpy?

This can also be done with the Image class of the PIL library:

from PIL import Image
import numpy as np

im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())

Note: The .getdata() might not be needed - np.array(im_frame) should also work

Remove unused imports in Android Studio

Press Alt + Enter with the cursor on top of the import. The Optimize imports menu will show. Press Enter again. Your unused imports will be removed.

enter image description here

JavaScript variable number of arguments to function

As mentioned already, you can use the arguments object to retrieve a variable number of function parameters.

If you want to call another function with the same arguments, use apply. You can even add or remove arguments by converting arguments to an array. For example, this function inserts some text before logging to console:

log() {
    let args = Array.prototype.slice.call(arguments);
    args = ['MyObjectName', this.id_].concat(args);
    console.log.apply(console, args);
}

jQuery UI Sortable, then write order into a database

I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.