Programs & Examples On #Saf

The Swing Application Framework (JSR 296) is a Java specification for providing a simple application framework for Swing applications. It defines infrastructure common to most desktop applications, making Swing applications easier to create.

Method Call Chaining; returning a pointer vs a reference?

Very interesting question.

I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.

But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I encountered this because the http2 server closed the connection when sending a big response to the Chrome.

Why? Because it is just a setting of the http2 server, named WriteTimeout.

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

new Buffer(number)            // Old
Buffer.alloc(number)          // New

new Buffer(string)            // Old
Buffer.from(string)           // New

new Buffer(string, encoding)  // Old
Buffer.from(string, encoding) // New

new Buffer(...arguments)      // Old
Buffer.from(...arguments)     // New

Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

For React Native applications while running in debug add the xml block mentioned by @Xenolion to react_native_config.xml located in <project>/android/app/src/debug/res/xml

Similar to the following snippet:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="false">localhost</domain>
        <domain includeSubdomains="false">10.0.2.2</domain>
        <domain includeSubdomains="false">10.0.3.2</domain>
    </domain-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

Gulp 4.0 has changed the way that tasks should be defined if the task depends on another task to execute. The list parameter has been deprecated.

An example from your gulpfile.js would be:

// Starts a BrowerSync instance
gulp.task('server', ['build'], function(){
  browser.init({server: './_site', port: port});
});

Instead of the list parameter they have introduced gulp.series() and gulp.parallel().

This task should be changed to something like this:

// Starts a BrowerSync instance
gulp.task('server', gulp.series('build', function(){
  browser.init({server: './_site', port: port});
}));

I'm not an expert in this. You can see a more robust example in the gulp documentation for running tasks in series or these following excellent blog posts by Jhey Thompkins and Stefan Baumgartner

https://codeburst.io/switching-to-gulp-4-0-271ae63530c0

https://fettblog.eu/gulp-4-parallel-and-series/

installation app blocked by play protect

it is due to expired of debug certificate simply delete the debug.keystore located at

C:\Users\.android\

after that build your project the build tools will regenerate a new key and it will work fine. here is a reference:

https://developer.android.com/studio/publish/app-signing

Entity Framework Core: A second operation started on this context before a previous operation completed

I had the same error. It happened because I called a method that was constructed as public async void ... instead of public async Task ....

startForeground fail after upgrade to Android 8.1

After some tinkering for a while with different solutions i found out that one must create a notification channel in Android 8.1 and above.

private fun startForeground() {
    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel("my_service", "My Background Service")
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                ""
            }

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()
    startForeground(101, notification)
}

@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_NONE)
    chan.lightColor = Color.BLUE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

From my understanding background services are now displayed as normal notifications that the user then can select to not show by deselecting the notification channel.

Update: Also don't forget to add the foreground permission as required Android P:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Get safe area inset top and bottom heights

Try this :

In Objective C

if (@available(iOS 11.0, *)) {
    UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
    CGFloat topPadding = window.safeAreaInsets.top;
    CGFloat bottomPadding = window.safeAreaInsets.bottom;
}

In Swift

if #available(iOS 11.0, *) {
    let window = UIApplication.shared.keyWindow
    let topPadding = window?.safeAreaInsets.top
    let bottomPadding = window?.safeAreaInsets.bottom
}

In Swift - iOS 13.0 and above

// Use the first element from windows array as KeyWindow deprecated

if #available(iOS 13.0, *) {
    let window = UIApplication.shared.windows[0]
    let topPadding = window.safeAreaInsets.top
    let bottomPadding = window.safeAreaInsets.bottom
}

Is it safe to clean docker/overlay2/

I found this worked best for me:

docker image prune --all

By default Docker will not remove named images, even if they are unused. This command will remove unused images.

Note each layer in an image is a folder inside the /usr/lib/docker/overlay2/ folder.

How do I use Safe Area Layout programmatically?

I'm using this instead of add leading and trailing margin constraints to the layoutMarginsGuide:

UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
yourView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
                                           [safe.trailingAnchor constraintEqualToAnchor:yourView.trailingAnchor],
                                           [yourView.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor],
                                           [yourView.topAnchor constraintEqualToAnchor:safe.topAnchor],
                                           [safe.bottomAnchor constraintEqualToAnchor:yourView.bottomAnchor]
                                          ]];

Please also check the option for lower version of ios 11 from Krunal's answer.

iPhone X / 8 / 8 Plus CSS media queries

Here are some of the following media queries for iPhones. Here is the ref link https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

        /* iphone 3 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 1) { }
        
        /* iphone 4 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 5 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 6, 6s, 7, 8 */
        @media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (-webkit-device-pixel-ratio: 2) { }
            
        /* iphone 6+, 6s+, 7+, 8+ */
        @media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (-webkit-device-pixel-ratio: 3) { }
        
        /* iphone X , XS, 11 Pro, 12 Mini */
        @media only screen and (min-device-width: 375px) and (max-device-height: 812px) and (-webkit-device-pixel-ratio: 3) { }

        /* iphone 12, 12 Pro */
        @media only screen and (min-device-width: 390px) and (max-device-height: 844px) and (-webkit-device-pixel-ratio: 3) { }
       
        /* iphone XR, 11 */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 2) { }
            
        /* iphone XS Max, 11 Pro Max */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 3) { }

        /* iphone 12 Pro Max */
        @media only screen and (min-device-width : 428px) and (max-device-height : 926px) and (-webkit-device-pixel-ratio : 3) { }

How to downgrade tensorflow, multiple versions possible?

Click to green checkbox on installed tensorflow and choose needed versionscreenshot Anaconda navigator

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Some version working

<div class="hidden-xs">Only Mobile hidden</div>
<div class="visible-xs">Only Mobile visible</div>

Specifying onClick event type with Typescript and React.Konva

React.MouseEvent works for me:

private onClick = (e: React.MouseEvent<HTMLInputElement>) => {
  let button = e.target as HTMLInputElement;
}

Input type number "only numeric value" validation

I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.

Sample use: <input type="number" formControlName="num" placeholder="0" ntvFormValidity>

Directive definition:

import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';

@Directive({
  selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {

  constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }

  /* 
  - Angular doesn't fire "change" events for invalid <input type="number">
  - We have to check the DOM object for browser native invalid state
  - Add custom validator that checks native invalidity
  */
  ngAfterViewInit() {
    var control: FormControl = this.cn.control;

    // Bridge native invalid to ng-invalid via Validators
    const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
    const v_fn = control.validator;

    control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
    setTimeout(()=>control.updateValueAndValidity(), 0);
  }
}

The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.

On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".

I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.

Something like this:

<my-input-number formControlName="num" placeholder="0">

PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers on the declaration, please let me know so I can update my Directive (and this answer).

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

I follow all recommendations and all requirements. I install my self signed root CA on my iPhone. I make it trusted. I put certificate signed with this root CA on my local development server and I still get certificated error on safari iOS. Working on all other platforms.

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Another trap of note is making sure you're not decorating controllers with the Consume Attribute as below:

[Produces("application/json")]
[Consumes("application/json")]
public class MyController : Controller

This will fail with a 415 Unsupported Media Type if the upload is NOT JSON.

A "friend of mine" was recently caught out by this like so:

public class MyFileUploadController : MyCustomController {

}

[Produces("application/json")]
[Consumes("application/json")]
public class MyCustomController : ControllerBase {

}

Safe Area of Xcode 9

I want to mention something that caught me first when I was trying to adapt a SpriteKit-based app to avoid the round edges and "notch" of the new iPhone X, as suggested by the latest Human Interface Guidelines: The new property safeAreaLayoutGuide of UIView needs to be queried after the view has been added to the hierarchy (for example, on -viewDidAppear:) in order to report a meaningful layout frame (otherwise, it just returns the full screen size).

From the property's documentation:

The layout guide representing the portion of your view that is unobscured by bars and other content. When the view is visible onscreen, this guide reflects the portion of the view that is not covered by navigation bars, tab bars, toolbars, and other ancestor views. (In tvOS, the safe area reflects the area not covered the screen's bezel.) If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide edges are equal to the edges of the view.

(emphasis mine)

If you read it as early as -viewDidLoad:, the layoutFrame of the guide will be {{0, 0}, {375, 812}} instead of the expected {{0, 44}, {375, 734}}

Cannot find control with name: formControlName in angular reactive form

You should specify formGroupName for nested controls

<div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>

Plunker Example

Is it safe to store a JWT in localStorage with ReactJS?

A way to look at this is to consider the level of risk or harm.

Are you building an app with no users, POC/MVP? Are you a startup who needs to get to market and test your app quickly? If yes, I would probably just implement the simplest solution and maintain focus on finding product-market-fit. Use localStorage as its often easier to implement.

Are you building a v2 of an app with many daily active users or an app that people/businesses are heavily dependent on. Would getting hacked mean little or no room for recovery? If so, I would take a long hard look at your dependencies and consider storing token information in an http-only cookie.

Using both localStorage and cookie/session storage have their own pros and cons.

As stated by first answer: If your application has an XSS vulnerability, neither will protect your user. Since most modern applications have a dozen or more different dependencies, it becomes increasingly difficult to guarantee that one of your application's dependencies is not XSS vulnerable.

If your application does have an XSS vulnerability and a hacker has been able to exploit it, the hacker will be able to perform actions on behalf of your user. The hacker can perform GET/POST requests by retrieving token from localStorage or can perform POST requests if token is stored in a http-only cookie.

The only down-side of the storing your token in local storage is the hacker will be able to read your token.

How to enable Google Play App Signing

When you use Fabric for public beta releases (signed with prod config), DON'T USE Google Play App Signing. You will must after build two signed apks!

When you distribute to more play stores (samsung, amazon, xiaomi, ...) you will must again build two signed apks.

So be really carefull with Google Play App Signing.

It's not possible to revert it :/ and Google Play did not after accept apks signed with production key. After enable Google Play App Signing only upload key is accepted...

It really complicate CI distribution...

Next issues with upgrade: https://issuetracker.google.com/issues/69285256

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

In my case, updating com.android.tools.build:gradle to last version and rebuild the project in online mode of Gradle was solved the problem.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Hello React Developers,

Instead of doing this disableHostCheck: true, in webpackDevServer.config.js. You can easily solve 'invalid host headers' error by adding a .env file to you project, add the variables HOST=0.0.0.0 and DANGEROUSLY_DISABLE_HOST_CHECK=true in .env file. If you want to make changes in webpackDevServer.config.js, you need to extract the react-scripts by using 'npm run eject' which is not recommended to do it. So the better solution is adding above mentioned variables in .env file of your project.

Happy Coding :)

Disable button in angular with two conditions?

In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.

Your problem started like this:

enabled  = A and B
disabled = not ( A and B )

So far so good, but you went one step further and tried to remove the braces. And that's a little tricky, because you have to replace the and/&& with an or/||.

not ( A and B ) = not(A) OR not(B)

Or in a more mathematical notation:

enter image description here

I always keep this law in mind whenever I simplify conditions or work with probabilities.

Error: the entity type requires a primary key

I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...

Wrong PK name

public class Client
{
  public int SomeFieldName { get; set; }  // It is the ID
  ...
}

Correct PK name

public class Client
{
  public int Id { get; set; }  // It is the ID
  ...
}

public class Client
{
  public int ClientId { get; set; }  // It is the ID
  ...
}

It still posible to use wrong PK name but we have to use [Key] attribute like

public class Client
{
   [Key]
   public int SomeFieldName { get; set; }  // It is the ID
   ...
}

Running Tensorflow in Jupyter Notebook

For Anaconda users in Windows 10 and those who recently updated Anaconda environment, TensorFlow may cause some issues to activate or initiate. Here is the solution which I explored and which worked for me:

  • Uninstall current Anaconda environment and delete all the existing files associated with Anaconda from your C:\Users or where ever you installed it.
  • Download Anaconda (https://www.anaconda.com/download/?lang=en-us#windows)
  • While installing, check the "Add Anaconda to my PATH environment variable"
  • After installing, open the Anaconda command prompt to install TensorFlow using these steps:
  • Create a conda environment named tensorflow by invoking the following command:

    conda create -n tensorflow python=3.5 (Use this command even if you are using python 3.6 because TensorFlow will get upgraded in the following steps)

  • Activate the conda environment by issuing the following command:

    activate tensorflow After this step, the command prompt will change to (tensorflow)

  • After activating, upgrade tensorflow using this command:

    pip install --ignore-installed --upgrade Now you have successfully installed the CPU version of TensorFlow.

  • Close the Anaconda command prompt and open it again and activate the tensorflow environment using 'activate tensorflow' command.
  • Inside the tensorflow environment, install the following libraries using the commands: pip install jupyter pip install keras pip install pandas pip install pandas-datareader pip install matplotlib pip install scipy pip install sklearn
  • Now your tensorflow environment contains all the common libraries used in deep learning.
  • Congrats, these libraries will make you ready to build deep neural nets. If you need more libraries install using the same command 'pip install libraryname'

How to update-alternatives to Python 3 without breaking apt?

As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :

$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.7   2         auto mode
  1            /usr/bin/python3.6   1         manual mode
  2            /usr/bin/python3.7   2         manual mode

Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3 
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Comment by @Niagaradad helped me. I was entering the wrong password the whole time.

Notice the error message

ERROR 1045 (28000): Access denied for user 'ayaz'@'localhost' (using password: YES)

It says, Password: Yes. That means I am sending the password to SQL and that is wrong.

Usually root account doesn't have password if you haven't set one. If you have installed mysql via homebrew then root account won't have a password.

Here is the comment.

so, not exactly the same then. NO means you are not sending a password to MySQL. YES means you are sending a password to MySQL but the incorrect one. Did you specifically set a password for the mysql root user when you installed MySQL? By default there is no password so you can use mysql -u root -p and hit enter.

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

not finding android sdk (Unity)

I solved the problem by uninstalling JDK 9.

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

Worked by adding this in pom.xml:

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
</properties>

Even you have SDK 13 or 14.

Job for mysqld.service failed See "systemctl status mysqld.service"

In my particular case, the error was appearing due to missing /var/log/mysql with mysql-server package 5.7.21-1 on Debian-based Linux distro. Having ran strace and sudo /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid ( which is what the systemd service actually runs), it became apparent that the issue was due to this:

2019-01-01T09:09:22.102568Z 0 [ERROR] Could not open file '/var/log/mysql/error.log' for error logging: No such file or directory

I've recently removed contents of several directories in /var/log so it was no surprise. The solution was to create the directory and make it owned by mysql user as in

$ sudo mkdir /var/log/mysql
$ sudo chown -R mysql:mysql /var/log/mysql

Having done that I've happily logged in via sudo mysql -u root and greeted with the old and familiar mysql> prompt

How to solve npm error "npm ERR! code ELIFECYCLE"

Resolved like this:

# chown -R <user>: node_modules

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

When I used the code mysqld_safe --skip-grant-tables & but I get the error:

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.

$ systemctl stop  mysql.service
$ ps -eaf|grep mysql
$ mysqld_safe --skip-grant-tables &

I solved:

$ mkdir -p /var/run/mysqld
$ chown mysql:mysql /var/run/mysqld

Now I use the same code mysqld_safe --skip-grant-tables & and get

mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

If I use $ mysql -u root I'll get :

Server version: 5.7.18-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Now time to change password:

mysql> use mysql
mysql> describe user;

Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A

Database changed

mysql> FLUSH PRIVILEGES;
mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('newpwd');

or If you have a mysql root account that can connect from everywhere, you should also do:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

Alternate Method:

   USE mysql
   UPDATE user SET Password = PASSWORD('newpwd')
   WHERE Host = 'localhost' AND User = 'root';

And if you have a root account that can access from everywhere:

 USE mysql
 UPDATE user SET Password = PASSWORD('newpwd')
 WHERE Host = '%' AND User = 'root';`enter code here

now need to quit from mysql and stop/start

FLUSH PRIVILEGES;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

now again ` mysql -u root -p' and use the new password to get

mysql>

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

Webpack's configuration file has changed over the years (likely with each major release). The answer to the question:

Why do I get this error

Invalid configuration object. Webpack has been initialised using a 
configuration object that does not match the API schema

is because the configuration file doesn't match the version of webpack being used.

The accepted answer doesn't state this and other answers allude to this but don't state it clearly npm install [email protected], Just change from "loaders" to "rules" in "webpack.config.js", and this. So I decide to provide my answer to this question.

Uninstalling and re-installing webpack, or using the global version of webpack will not fix this problem. Using the correct version of webpack for the configuration file being used is what is important.

If this problem was fixed when using a global version it likely means that your global version was "old" and the webpack.config.js file format your using is "old" so they match and viola things now work. I'm all for things working, but want readers to know why they worked.

Whenever you get a webpack configuration that you hope is going to solve your problem ... ask yourself what version of webpack the configuration is for.

There are a lot of good resources for learning webpack. Some are:

There are a lot more good resources for learning webpack4 by example, please add comments if you know of others. Hopefully, future webpack articles will state the versions being used/explained.

Moving all files from one directory to another using Python

import shutil 
import os 
import logging

source = '/var/spools/asterisk/monitor' 
dest1 = '/tmp/'


files = os.listdir(source)

for f in files:
        shutil.move(source+f, dest1)

logging.basicConfig(filename='app.log', filemode='w', format='%(name)s
- %(levelname)s - %(message)s')

logging.info('directories moved')

A little bit cooked code with log feature. You can also configure this to run at some period of time using crontab.

* */1 * * * python /home/yourprogram.py > /dev/null 2>&1

runs every hour! cheers

Easy way to make a confirmation dialog in Angular?

you can use window.confirm inside your function combined with if condition

 delete(whatever:any){
    if(window.confirm('Are sure you want to delete this item ?')){
    //put your delete method logic here
   }
}

when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

If you are like me, and are staring at this thread thinking "But I'm not trying to add a component, I am trying to add a guard/service/pipe, etc." then the issue is likely that you have added the wrong type to a routing path. That is what I did. I accidentally added a guard to the component: section of a path instead of the canActivate: section. I love IDE autocomplete but you have to slow down a bit and pay attention. If you absolutely can't find it, do a global search for the name it is complaining about and look at every usage to make sure you didn't slip-up with a name.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

As a generic answer, not specifically directed at this task: In many cases, you can significantly speed up any program by making improvements at a high level. Like calculating data once instead of multiple times, avoiding unnecessary work completely, using caches in the best way, and so on. These things are much easier to do in a high level language.

Writing assembler code, it is possible to improve on what an optimising compiler does, but it is hard work. And once it's done, your code is much harder to modify, so it is much more difficult to add algorithmic improvements. Sometimes the processor has functionality that you cannot use from a high level language, inline assembly is often useful in these cases and still lets you use a high level language.

In the Euler problems, most of the time you succeed by building something, finding why it is slow, building something better, finding why it is slow, and so on and so on. That is very, very hard using assembler. A better algorithm at half the possible speed will usually beat a worse algorithm at full speed, and getting the full speed in assembler isn't trivial.

Safe navigation operator (?.) or (!.) and null property paths

Since TypeScript 3.7 was released you can use optional chaining now.

Property example:

let x = foo?.bar.baz();

This is equvalent to:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

Moreover you can call:

Optional Call

function(otherFn: (par: string) => void) {
   otherFn?.("some value");
}

otherFn will be called only if otherFn won't be equal to null or undefined

Usage optional chaining in IF statement

This:

if (someObj && someObj.someProperty) {
    // ...
}

can be replaced now with this

if (someObj?.someProperty) {
    // ...
}

Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

How to Inspect Element using Safari Browser

Press CMD + , than click in show develop menu in menu bar. After that click Option + CMD + i to open and close the inspector

enter image description here

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

You can declare the books (on line 2) as an array:

title: any = 'List of books are represted in the bookstore';
books: any = []; 
constructor(private service:  AppService){
}

ngOnInit(){
  this.getBookDetails();
}

getBookDetails() {
    this.service.getBooks().subscribe(books => {
        this.books = books.json();
        console.log(this.books);
    });
}

http post - how to send Authorization header?

I believe you need to map the result before you subscribe to it. You configure it like this:

  updateProfileInformation(user: User) {
    var headers = new Headers();
    headers.append('Content-Type', this.constants.jsonContentType);

    var t = localStorage.getItem("accessToken");
    headers.append("Authorization", "Bearer " + t;
    var body = JSON.stringify(user);

    return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
      .map((response: Response) => {
        var result = response.json();
        return result;
      })
      .catch(this.handleError)
      .subscribe(
      status => this.statusMessage = status,
      error => this.errorMessage = error,
      () => this.completeUpdateUser()
      );
  }

How do I install PIL/Pillow for Python 3.6?

For python version 2.x you can simply use

  • pip install pillow

But for python version 3.X you need to specify

  • (sudo) pip3 install pillow

when you enter pip in bash hit tab and you will see what options you have

Pandas: convert dtype 'object' to int

Documenting the answer that worked for me based on the comment by @piRSquared.

I needed to convert to a string first, then an integer.

>>> df['purchase'].astype(str).astype(int)

Make the size of a heatmap bigger with seaborn

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

WARNING: sanitizing unsafe style value url

For anyone who is already doing what the warning suggests you do, before the upgrade to Angular 5, I had to map my SafeStyle types to string before using them in the templates. After Angular 5, this is no longer the case. I had to change my models to have an image: SafeStyle instead of image: string. I was already using the [style.background-image] property binding and bypassing security on the whole url.

Hope this helps someone.

Numpy: Checking if a value is NaT

INTRO: This answer was written in a time when Numpy was version 1.11 and behaviour of NAT comparison was supposed to change since version 1.12. Clearly that wasn't the case and the second part of answer became wrong. The first part of answer may be not applicable for new versions of numpy. Be sure you've checked MSeifert's answers below.


When you make a comparison at the first time, you always have a warning. But meanwhile returned result of comparison is correct:

import numpy as np    
nat = np.datetime64('NaT')

def nat_check(nat):
    return nat == np.datetime64('NaT')    

nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
True

nat_check(nat)
Out[5]: True

If you want to suppress the warning you can use the catch_warnings context manager:

import numpy as np
import warnings

nat = np.datetime64('NaT')

def nat_check(nat):
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return nat == np.datetime64('NaT')    

nat_check(nat)
Out[5]: True


EDIT: For some reason behavior of NAT comparison in Numpy version 1.12 wasn't change, so the next code turned out to be inconsistent.

And finally you might check numpy version to handle changed behavior since version 1.12.0:

def nat_check(nat):
    if [int(x) for x in np.__version__.split('.')[:-1]] > [1, 11]:
        return nat != nat
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        return nat == np.datetime64('NaT')


EDIT: As MSeifert mentioned, Numpy contains isnat function since version 1.13.

Moment.js - How to convert date string into date?

if you have a string of date, then you should try this.

const FORMAT = "YYYY ddd MMM DD HH:mm";

const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300

const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019

or try this :

const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);

How to set <iframe src="..."> without causing `unsafe value` exception?

This one works for me.

import { Component,Input,OnInit} from '@angular/core';
import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser';

@Component({
    moduleId: module.id,
    selector: 'player',
    templateUrl: './player.component.html',
    styleUrls:['./player.component.scss'],
    
})
export class PlayerComponent implements OnInit{
    @Input()
    id:string; 
    url: SafeResourceUrl;
    constructor (public sanitizer:DomSanitizer) {
    }
    ngOnInit() {
        this.url = this.sanitizer.bypassSecurityTrustResourceUrl(this.id);      
    }
}

How to install and run Typescript locally in npm?

You can now use ts-node, which makes your life as simple as

npm install -D ts-node
npm install -D typescript

ts-node script.ts

<img>: Unsafe value used in a resource URL context

import {DomSanitizationService} from '@angular/platform-browser';
@Component({
 templateUrl: 'build/pages/veeu/veeu.html'
 })
  export class VeeUPage {
     trustedURL:any;
      static get parameters() {
               return [NavController, App, MenuController, 
              DomSanitizationService];
        }
      constructor(nav, app, menu, sanitizer) {
        this.app = app;
        this.nav = nav;
        this.menu = menu;
        this.sanitizer = sanitizer;  
        this.trustedURL  = sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
        } 
 }



 <iframe [src]='trustedURL' width="640" height="360" frameborder="0"
   webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>


User property binding instead of function.

disable viewport zooming iOS 10+ safari?

I spent about an hour looking for a more robust javascript option, and did not find one. It just so happens that in the past few days I've been fiddling with hammer.js (Hammer.js is a library that lets you manipulate all sorts of touch events easily) and mostly failing at what I was trying to do.

With that caveat, and understanding I am by no means a javascript expert, this is a solution I came up with that basically leverages hammer.js to capture the pinch-zoom and double-tap events and then log and discard them.

Make sure you include hammer.js in your page and then try sticking this javascript in the head somewhere:

_x000D_
_x000D_
< script type = "text/javascript" src="http://hammerjs.github.io/dist/hammer.min.js"> < /script >_x000D_
< script type = "text/javascript" >_x000D_
_x000D_
  // SPORK - block pinch-zoom to force use of tooltip zoom_x000D_
  $(document).ready(function() {_x000D_
_x000D_
    // the element you want to attach to, probably a wrapper for the page_x000D_
    var myElement = document.getElementById('yourwrapperelement');_x000D_
    // create a new hammer object, setting "touchAction" ensures the user can still scroll/pan_x000D_
    var hammertime = new Hammer(myElement, {_x000D_
      prevent_default: false,_x000D_
      touchAction: "pan"_x000D_
    });_x000D_
_x000D_
    // pinch is not enabled by default in hammer_x000D_
    hammertime.get('pinch').set({_x000D_
      enable: true_x000D_
    });_x000D_
_x000D_
    // name the events you want to capture, then call some function if you want and most importantly, add the preventDefault to block the normal pinch action_x000D_
    hammertime.on('pinch pinchend pinchstart doubletap', function(e) {_x000D_
      console.log('captured event:', e.type);_x000D_
      e.preventDefault();_x000D_
    })_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

the steps I followed are:

  1. close Android Studio (or IntelliJ IDEA)
  2. in your project's directory:
    1. delete .idea directory
    2. delete .gradle directory
    3. delete all .iml files
      • find . | grep -e .iml$ | xargs rm
  3. use Android Studio to re-open the directory as a project

Terminal commands:

# close Android Studio
cd "your project's directory"
rm -rf ./.idea
rm -rf ./.gradle
find . | grep -e .iml$ | xargs rm
# use Android Studio to re-open the directory as a project

Is it safe to expose Firebase apiKey to the public?

Building on the answers of prufrofro and Frank van Puffelen here, I put together this setup that doesn't prevent scraping, but can make it slightly harder to use your API key.

Warning: To get your data, even with this method, one can for example simply open the JS console in Chrome and type:

firebase.database().ref("/get/all/the/data").once("value", function (data) {
    console.log(data.val());
});

Only the database security rules can protect your data.

Nevertheless, I restricted my production API key use to my domain name like this:

  1. https://console.developers.google.com/apis
  2. Select your Firebase project
  3. Credentials
  4. Under API keys, pick your Browser key. It should look like this: "Browser key (auto created by Google Service)"
  5. In "Accept requests from these HTTP referrers (web sites)", add the URL of your app (exemple: projectname.firebaseapp.com/* )

Now the app will only work on this specific domain name. So I created another API Key that will be private for localhost developement.

  1. Click Create credentials > API Key

By default, as mentioned by Emmanuel Campos, Firebase only whitelists localhost and your Firebase hosting domain.


In order to make sure I don't publish the wrong API key by mistake, I use one of the following methods to automatically use the more restricted one in production.

Setup for Create-React-App

In /env.development:

REACT_APP_API_KEY=###dev-key###

In /env.production:

REACT_APP_API_KEY=###public-key###

In /src/index.js

const firebaseConfig = {
  apiKey: process.env.REACT_APP_API_KEY,
  // ... 
};

How to hide a mobile browser's address bar?

I know this is old, but I have to add this in here..

And while this is not a full answer, it is an 'IN ADDITION TO'

The address bar will not disappear if you're NOT using https.

ALSO

If you are using https and the address bar still won't hide, you might have some https errors in your webpage (such as certain images being served from a non-https location.)

Hope this helps..

net::ERR_INSECURE_RESPONSE in Chrome

A missing intermediate certificate might be the problem.

You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.

No idea why Chrome (possibly) sometimes has problems validating these certs.

Content Security Policy: The page's settings blocked the loading of a resource

You have said you can only load scripts from your own site (self). You have then tried to load a script from another site (www.google.com) and, because you've restricted this, you can't. That's the whole point of Content Security Policy (CSP).

You can change your first line to:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://www.google.com">

Or, alternatively, it may be worth removing that line completely until you find out more about CSP. Your current CSP is pretty lax anyway (allowing unsafe-inline, unsafe-eval and a default-src of *), so it is probably not adding too much value, to be honest.

#1292 - Incorrect date value: '0000-00-00'

You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.

Add jars to a Spark Job - spark-submit

While we submit spark jobs using spark-submit utility, there is an option --jars . Using this option, we can pass jar file to spark applications.

The number of method references in a .dex file cannot exceed 64k API 17

This error can also occur when you load all google play services apis when you only using afew.

As stated by google:"In versions of Google Play services prior to 6.5, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit.

From version 6.5, you can instead selectively compile Google Play service APIs into your app."

For example when your app needs play-services-maps ,play-services-location .You need to add only the two apis in your build.gradle file at app level as show below:

compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'

Instead of:

compile 'com.google.android.gms:play-services:10.2.1'

For full documentation and list of google play services apis click here

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

np.isnan can be applied to NumPy arrays of native dtype (such as np.float64):

In [99]: np.isnan(np.array([np.nan, 0], dtype=np.float64))
Out[99]: array([ True, False], dtype=bool)

but raises TypeError when applied to object arrays:

In [96]: np.isnan(np.array([np.nan, 0], dtype=object))
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Since you have Pandas, you could use pd.isnull instead -- it can accept NumPy arrays of object or native dtypes:

In [97]: pd.isnull(np.array([np.nan, 0], dtype=float))
Out[97]: array([ True, False], dtype=bool)

In [98]: pd.isnull(np.array([np.nan, 0], dtype=object))
Out[98]: array([ True, False], dtype=bool)

Note that None is also considered a null value in object arrays.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

  1. Remove the jar files in your gradle
  2. Sync it
  3. Copy that jar and sync it

This worked for me.

Create list of object from another using Java 8 Streams

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    // Getter & Setter
}

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.

The steps are :

  1. In the address bar, type "chrome://net-internals/#hsts".
  2. Type the domain name in the text field below "Delete domain".
  3. Click the "Delete" button.
  4. Type the domain name in the text field below "Query domain".
  5. Click the "Query" button.
  6. Your response should be "Not found".

You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers

Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.

Edit : you have to repeat the steps every time you will go on the production site.

Docker is in volume in use, but there aren't any Docker containers

Volume can be in use by one of stopped containers. You can remove such containers by command:

docker container prune

then you can remove not used volumes

docker volume prune

Angular2 QuickStart npm start is not working correctly

Uninstall all existing node packages. Update node and npm.As it is given in documentation as at least node v5.x.x and npm 3.x.x else it will cause errors .

Do npm clean. Then do npm install, npm start.

This solved the issue for me.

Webpack "OTS parsing error" loading fonts

The limit was the clue for my code, but I had to specify it like this:

use: [
  {
    loader: 'url-loader',
    options: {
      limit: 8192,
    },
  },
],

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

How to send push notification to web browser?

As of now GCM only works for chrome and android. similarly firefox and other browsers has their own api.

Now coming to the question how to implement push notification so that it will work for all common browsers with own back end.

  1. You need client side script code i.e service worker,refer( Google push notification). Though this remains same for other browsers.

2.after getting endpoint using Ajax save it along with browser name.

3.You need to create back end which has fields for title,message, icon,click URL as per your requirements. now after click on send notification, call a function say send_push(). In this write code for different browsers for example

3.1. for chrome

 $headers = array(
          'Authorization: key='.$api_key(your gcm key),
          'Content-Type: application/json',
     );
   $msg = array('to'=>'register id saved to your server');
   $url = 'https://android.googleapis.com/gcm/send';
   $ch = curl_init();

      // Set the url, number of POST vars, POST data
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));

      $result = curl_exec($ch);

3.2. for mozilla

$headers = array(            
              'Content-Type: application/json',
              'TTL':6000
            );

       $url = 'https://updates.push.services.mozilla.com/wpush/v1/REGISTER_ID_TO SEND NOTIFICATION_ON';

      $ch = curl_init();

      // Set the url, number of POST vars, POST data
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);


      $result = curl_exec($ch);

for other browsers please google...

Chrome / Safari not filling 100% height of flex parent

I have had a similar issue in iOS 8, 9 and 10 and the info above couldn't fix it, however I did discover a solution after a day of working on this. Granted it won't work for everyone but in my case my items were stacked in a column and had 0 height when it should have been content height. Switching the css to be row and wrap fixed the issue. This only works if you have a single item and they are stacked but since it took me a day to find this out I thought I should share my fix!

.wrapper {
    flex-direction: column; // <-- Remove this line
    flex-direction: row; // <-- replace it with
    flex-wrap: wrap; // <-- Add wrapping
}

.item {
    width: 100%;
}

How to change the MySQL root account password on CentOS7?

Use the below Steps to reset the password.

$ sudo systemctl start mysqld

Reset the MySql server root password.

$sudo grep 'temporary password' /var/log/mysqld.log

Output Something like-:

 10.744785Z 1 [Note] A temporary password is generated for root@localhost: o!5y,oJGALQa

Use the above password during reset mysql_secure_installation process.

<pre>
    $ sudo mysql_secure_installation
</pre>
   Securing the MySQL server deployment.

   Enter password for user root: 

You have successfully reset the root password of MySql Server. Use the below command to check the mysql server connecting or not.

$ mysql -u root -p

http://gotechnies.com/install-latest-mysql-5-7-rhelcentos-7/

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Just use this command and it will handle this error npm install --unsafe-perm --allow-root

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

typesafe select onChange event using reactjs and typescript

I tried using React.FormEvent<HTMLSelectElement> but it led to an error in the editor, even though there is no EventTarget visible in the code:

The property 'value' does not exist on value of type 'EventTarget'

Then I changed React.FormEvent to React.ChangeEvent and it helped:

private changeName(event: React.ChangeEvent<HTMLSelectElement>) {
    event.preventDefault();
    this.props.actions.changeName(event.target.value);
}

Difference between `Optional.orElse()` and `Optional.orElseGet()`

I reached here for the problem Kudo mentioned.

I'm sharing my experience for others.

orElse, or orElseGet, that is the question:

static String B() {
    System.out.println("B()...");
    return "B";
}

public static void main(final String... args) {
    System.out.println(Optional.of("A").orElse(B()));
    System.out.println(Optional.of("A").orElseGet(() -> B()));
}

prints

B()...
A
A

orElse evaluates the value of B() interdependently of the value of the optional. Thus, orElseGet is lazy.

How to remove old and unused Docker images

I usually do docker rm -f $(docker ps -a -q) and docker system prune to purge all dangling containers.

Generating random numbers with Swift

My implementation as an Int extension. Will generate random numbers in range from..<to

public extension Int {
    static func random(from: Int, to: Int) -> Int {
        guard to > from else {
            assertionFailure("Can not generate negative random numbers")
            return 0
        }
        return Int(arc4random_uniform(UInt32(to - from)) + UInt32(from))
    }
}

Python: Importing urllib.quote

Use six:

from six.moves.urllib.parse import quote

six will simplify compatibility problems between Python 2 and Python 3, such as different import paths.

How to upgrade safely php version in wamp server

To add to the above answer (do steps 1-5).

  1. Click on WAMP -> Select PHP -> Versions: Select the new version installed
  2. Check that your PATH folder is updated to new path to PHP so your OS has same PHP version of WAMP.

Why use Optional.of over Optional.ofNullable?

In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .orElseThrow(NullPointerException::new);
                   // .orElseThrow(CustomException::new);

Server unable to read htaccess file, denying access to be safe

Just my solution. I had extracted a file, had some minor changes, and got the error above. Deleted everything, uploaded and extracted again, and normal business.

Refused to load the script because it violates the following Content Security Policy directive

Full permission string

The previous answers did not fix my issue, because they don't include blob: data: gap: keywords at the same time; so here is a string that does:

<meta http-equiv="Content-Security-Policy" content="default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;">

Warning: This exposes the document to many exploits. Be sure to prevent users from executing code in the console or to be in a closed environment like a Cordova application.

How to use confirm using sweet alert?

_x000D_
_x000D_
document.querySelector('#from1').onsubmit = function(e){_x000D_
_x000D_
 swal({_x000D_
    title: "Are you sure?",_x000D_
    text: "You will not be able to recover this imaginary file!",_x000D_
    type: "warning",_x000D_
    showCancelButton: true,_x000D_
    confirmButtonColor: '#DD6B55',_x000D_
    confirmButtonText: 'Yes, I am sure!',_x000D_
    cancelButtonText: "No, cancel it!",_x000D_
    closeOnConfirm: false,_x000D_
    closeOnCancel: false_x000D_
 },_x000D_
 function(isConfirm){_x000D_
_x000D_
   if (isConfirm.value){_x000D_
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");_x000D_
_x000D_
    } else {_x000D_
      swal("Cancelled", "Your imaginary file is safe :)", "error");_x000D_
         e.preventDefault();_x000D_
    }_x000D_
 });_x000D_
};
_x000D_
_x000D_
_x000D_

PHP 7: Missing VCRUNTIME140.dll

If you've followed Adam's instructions and you're still getting this error make sure you've installed the right variants (x86 or x64).

I had VC14x64 with PHP7x86 and I still got this error. Changing PHP7 to x64 fixed it. It's easy to miss you accidentally installed the wrong version.

Check for internet connection with Swift

As of iOS 12, NWPathMonitor replaced Reachability. Use this:

import Network


struct Internet {
 
 private static let monitor = NWPathMonitor()
 
 static var active = false
 static var expensive = false
 
 /// Monitors internet connectivity changes. Updates with every change in connectivity.
 /// Updates variables for availability and if it's expensive (cellular).
 static func start() {
  guard monitor.pathUpdateHandler == nil else { return }
  
  monitor.pathUpdateHandler = { update in
   Internet.active = update.status == .satisfied ? true : false
   Internet.expensive = update.isExpensive ? true : false
  }
  
  monitor.start(queue: DispatchQueue(label: "InternetMonitor"))
 }
 
}

In use:

Internet.start()

if Internet.active {
 // do something
}
  
if Internet.expensive {
 // device is using Cellular data or WiFi hotspot
}

MySQL user DB does not have password columns - Installing MySQL on OSX

Thank you for your help. Just in case if people are still having problems, try this.

For MySQL version 5.6 and under

Have you forgotten your Mac OS X 'ROOT' password  and need to reset it?  Follow these 4 simple steps:

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:      sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q
  4.  Stop the mysqld server again and restart it in normal mode.

For MySQL version 5.7 and up

  1.  Stop the mysqld server.  Typically this can be done by from 'System Prefrences' > MySQL > 'Stop MySQL Server'
  2.  Start the server in safe mode with privilege bypass      From a terminal:      sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3.  In a new terminal window:            sudo /usr/local/mysql/bin/mysql -u root      UPDATE mysql.user SET authentication_string=PASSWORD('NewPassword') WHERE User='root';      FLUSH PRIVILEGES;      \q      
  4.  Stop the mysqld server again and restart it in normal mode.

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

database_password: password would between quotes: " or '.

like so:

database_password: "password"

error C4996: 'scanf': This function or variable may be unsafe in c programming

Another way to suppress the error: Add this line at the top in C/C++ file:

#define _CRT_SECURE_NO_WARNINGS

Check if argparse optional argument is set or not

If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:

parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()

if args.filename is not None:
    print('The file name is {}'.format(args.filename))
else:
    print('Oh well ; No args, no problems')

"No Content-Security-Policy meta tag found." error in my phonegap application

For me it was enough to reinstall whitelist plugin:

cordova plugin remove cordova-plugin-whitelist

and then

cordova plugin add cordova-plugin-whitelist

It looks like updating from previous versions of Cordova was not succesful.

TLS 1.2 not working in cURL

Replace following

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');

With

curl_setopt ($ch, CURLOPT_SSLVERSION, 6);

Should work flawlessly.

Uncaught TypeError: Cannot read property 'appendChild' of null

You can load your External JS files in Angular and you can load them directly instead of defining in index.html file.

component.ts:

ngOnInit() {
    this.loadScripts();
}


  loadScripts() {
    const dynamicScripts = [
      //scripts to be loaded
      "assets/lib/js/hand-1.3.8.js",
      "assets/lib/js/modernizr.jr.js",
      "assets/lib/js/jquery-2.2.3.js",
      "assets/lib/js/jquery-migrate-1.4.1.js",
      "assets/js/jr.utils.js"
    ];
    for (let i = 0; i < dynamicScripts.length; i++) {
      const node = document.createElement('script');
      node.src = dynamicScripts[i];
      node.type = 'text/javascript';
      node.async = false;
      document.getElementById('scripts').appendChild(node);
    }
  }

component.html:

<div id="scripts">
</div>

You can also load styles similarly.

component.ts:

ngOnInit() {
    this.loadStyles();
}


  loadStyles() {
    const dynamicStyles = [
      //styles to be loaded
      "assets/lib/css/ui.css",
      "assets/lib/css/material-theme.css",
      "assets/lib/css/custom-style.css"
    ];
    for (let i = 0; i < dynamicStyles.length; i++) {
      const node = document.createElement('link');
      node.href = dynamicStyles[i];
      node.rel = 'stylesheet';
      document.getElementById('styles').appendChild(node);
    }
  }

component.html:

<div id="styles">
</div>

Show datalist labels but submit the actual value

Using PHP i've found a quite simple way to do this. Guys, Just Use something like this

<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
            <datalist id="customers">
                <?php 
    $querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
    $resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());

                while ($row_this = mysqli_fetch_array($resultSnamex)) {
                    echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
                    <input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
                }

                 ?>
            </datalist>

The Code Above lets the form carry the id of the option also selected.

How to uninstall mini conda? python

If you are using windows, just search for miniconda and you'll find the folder. Go into the folder and you'll find a miniconda uninstall exe file. Run it.

How to compare only date in moment.js

For checking one date is after another by using isAfter() method.

moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true

For checking one date is before another by using isBefore() method.

moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false

For checking one date is same as another by using isSame() method.

moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true

pandas loc vs. iloc vs. at vs. iat?

Let's start with this small df:

import pandas as pd
import time as tm
import numpy as np
n=10
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))

We'll so have

df
Out[25]: 
        0   1   2   3   4   5   6   7   8   9
    0   0   1   2   3   4   5   6   7   8   9
    1  10  11  12  13  14  15  16  17  18  19
    2  20  21  22  23  24  25  26  27  28  29
    3  30  31  32  33  34  35  36  37  38  39
    4  40  41  42  43  44  45  46  47  48  49
    5  50  51  52  53  54  55  56  57  58  59
    6  60  61  62  63  64  65  66  67  68  69
    7  70  71  72  73  74  75  76  77  78  79
    8  80  81  82  83  84  85  86  87  88  89
    9  90  91  92  93  94  95  96  97  98  99

With this we have:

df.iloc[3,3]
Out[33]: 33

df.iat[3,3]
Out[34]: 33

df.iloc[:3,:3]
Out[35]: 
    0   1   2   3
0   0   1   2   3
1  10  11  12  13
2  20  21  22  23
3  30  31  32  33



df.iat[:3,:3]
Traceback (most recent call last):
   ... omissis ...
ValueError: At based indexing on an integer index can only have integer indexers

Thus we cannot use .iat for subset, where we must use .iloc only.

But let's try both to select from a larger df and let's check the speed ...

# -*- coding: utf-8 -*-
"""
Created on Wed Feb  7 09:58:39 2018

@author: Fabio Pomi
"""

import pandas as pd
import time as tm
import numpy as np
n=1000
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
t1=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iloc[j,i]
t2=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iat[j,i]
t3=tm.time()
loc=t2-t1
at=t3-t2
prc = loc/at *100
print('\nloc:%f at:%f prc:%f' %(loc,at,prc))

loc:10.485600 at:7.395423 prc:141.784987

So with .loc we can manage subsets and with .at only a single scalar, but .at is faster than .loc

:-)

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Getting java.nio.file.AccessDeniedException when trying to write to a folder

Unobviously, Comodo antivirus has an "Auto-Containment" setting that can cause this exact error as well. (e.g. the user can write to a location, but the java.exe and javaw.exe processes cannot).

In this edge-case scenario, adding an exception for the process and/or folder should help.

Temporarily disabling the antivirus feature will help understand if Comodo AV is the culprit.

I post this not because I use or prefer Comodo, but because it's a tremendously unobvious symptom to an otherwise functioning Java application and can cost many hours of troubleshooting file permissions that are sane and correct, but being blocked by a 3rd-party application.

Hadoop cluster setup - java.net.ConnectException: Connection refused

I am also facing same issue in Hortonworks

At the time I restart the Ambari agents and servers then the issue has been resolved.

 systemctl stop ambari-agent 

systemctl stop ambari-server

Source :Full Article With Resolution

 systemctl start ambari-agent

systemctl start ambari-server

How can I upgrade NumPy?

I tried doing sudo pip uninstall numpy instead, because the rm didn't work at first.

Hopefully that helps.

Uninstalling then to install it again.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

Failed to execute 'createObjectURL' on 'URL':

This error is caused because the function createObjectURL is deprecated for Google Chrome

I changed this:

video.src=vendorUrl.createObjectURL(stream);
video.play();

to this:

video.srcObject=stream;
video.play();

This worked for me.

An unhandled exception occurred during the execution of the current web request. ASP.NET

I had the same problem and found out that I had forgotten to include the script in the file which I want to include in the live site.

Also, you should try this:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

Correct modification of state arrays in React.js

this.setState({
  arrayvar: [...this.state.arrayvar, ...newelement]
})

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

On Windows 10,

I just solved this issue by doing the following.

  1. Goto my.ini and add these 2 lines under [mysqld]

    skip-log-bin
    log_bin_trust_function_creators = 1
    
  2. restart MySQL service

Swift Open Link in Safari

New with iOS 9 and higher you can present the user with a SFSafariViewController (see documentation here). Basically you get all the benefits of sending the user to Safari without making them leave your app. To use the new SFSafariViewController just:

import SafariServices

and somewhere in an event handler present the user with the safari view controller like this:

let svc = SFSafariViewController(url: url)
present(svc, animated: true, completion: nil)

The safari view will look something like this:

enter image description here

Setting up MySQL and importing dump within Dockerfile

edit: I had misunderstand the question here. My following answer explains how to run sql commands at container creation time, but not at image creation time as desired by OP.

I'm not quite fond of Kuhess's accepted answer as the sleep 5 seems a bit hackish to me as it assumes that the mysql db daemon has correctly loaded within this time frame. That's an assumption, no guarantee. Also if you use a provided mysql docker image, the image itself already takes care about starting up the server; I would not interfer with this with a custom /usr/bin/mysqld_safe.

I followed the other answers around here and copied bash and sql scripts into the folder /docker-entrypoint-initdb.d/ within the docker container as this is clearly the intended way by the mysql image provider. Everything in this folder is executed once the db daemon is ready, hence you should be able rely on it.

As an addition to the others - since no other answer explicitely mentions this: besides sql scripts you can also copy bash scripts into that folder which might give you more control.

This is what I had needed for example as I also needed to import a dump, but the dump alone was not sufficient as it did not provide which database it should import into. So in my case I have a script named db_custom_init.sh with this content:

mysql -u root -p$MYSQL_ROOT_PASSWORD -e 'create database my_database_to_import_into'
mysql -u root -p$MYSQL_ROOT_PASSWORD my_database_to_import_into < /home/db_dump.sql

and this Dockerfile copying that script:

FROM mysql/mysql-server:5.5.62
ENV MYSQL_ROOT_PASSWORD=XXXXX
COPY ./db_dump.sql /home/db_dump.sql
COPY ./db_custom_init.sh /docker-entrypoint-initdb.d/

Python safe method to get value of nested dictionary

A simple class that can wrap a dict, and retrieve based on a key:

class FindKey(dict):
    def get(self, path, default=None):
        keys = path.split(".")
        val = None

        for key in keys:
            if val:
                if isinstance(val, list):
                    val = [v.get(key, default) if v else None for v in val]
                else:
                    val = val.get(key, default)
            else:
                val = dict.get(self, key, default)

            if not val:
                break

        return val

For example:

person = {'person':{'name':{'first':'John'}}}
FindDict(person).get('person.name.first') # == 'John'

If the key doesn't exist, it returns None by default. You can override that using a default= key in the FindDict wrapper -- for example`:

FindDict(person, default='').get('person.name.last') # == doesn't exist, so ''

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

The only thing that has worked for me (probably because I had inconsistencies with www. usage):

Paste this in to your .htaccess file:

<IfModule mod_headers.c>
<FilesMatch "\.(eot|font.css|otf|ttc|ttf|woff)$">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
<IfModule mod_mime.c>
# Web fonts
AddType application/font-woff woff
AddType application/vnd.ms-fontobject eot

# Browsers usually ignore the font MIME types and sniff the content,
# however, Chrome shows a warning if other MIME types are used for the
# following fonts.
AddType application/x-font-ttf ttc ttf
AddType font/opentype otf

# Make SVGZ fonts work on iPad:
# https://twitter.com/FontSquirrel/status/14855840545
AddType     image/svg+xml svg svgz
AddEncoding gzip svgz

</IfModule>

# rewrite www.example.com ? example.com

<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

http://ce3wiki.theturninggate.net/doku.php?id=cross-domain_issues_broken_web_fonts

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

In addition to your CORS issue, the server you are trying to access has HTTP basic authentication enabled. You can include credentials in your cross-domain request by specifying the credentials in the URL you pass to the XHR:

url = 'http://username:[email protected]/testpage'

Google Chrome redirecting localhost to https

Another option would be to use something like https://github.com/rchampourlier/tunnelss

Sure it added another dependency / setup, but it also enables testing of https in dev, which could be nice.

I use RVM however to get tunnelss working I had to use sudo gem install tunnelss and sudo tunnelss

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://192.168.59.103:2376
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3
...

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

Background image jumps when address bar hides iOS/Android/Mobile Chrome

This is the best solution (simplest) above everything I have tried.

...And this does not keep the native experience of the address bar!

You could set the height with CSS to 100% for example, and then set the height to 0.9 * of the window height in px with javascript, when the document is loaded.

For example with jQuery:

$("#element").css("height", 0.9*$(window).height());

)

Unfortunately there isn't anything that works with pure CSS :P but also be minfull that vh and vw are buggy on iPhones - use percentages.

How do I make flex box work in safari?

Try this:

select {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -ms-flexbox;
}

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The root problem here seems that iOS8 safari won't hide the address bar when scrolling down if the content is equal or less than the viewport.

As you found out already, adding some padding at the bottom gets around this issue:

html {
    /* enough space to scroll up to get fullscreen on iOS8 */
    padding-bottom: 80px;
}
// sort of emulate safari's "bounce back to top" scroll
window.addEventListener('scroll', function(ev) {
    // avoids scrolling when the focused element is e.g. an input
    if (
        !document.activeElement
        || document.activeElement === document.body
    ) {
        document.body.scrollIntoViewIfNeeded(true);
    }
});

The above css should be conditionally applied, for example with UA sniffing adding a gt-ios8 class to <html>.

Custom Listview Adapter with filter Android

please check below code it will help you

DrawerActivity.userListview
            .setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    int pos = position;
                    Intent intent = new Intent(getContext(),
                            UserDetail.class);
                    intent.putExtra("model", list.get(position));
                    context.startActivity(intent);
                }
            });
    return convertView;
}

@Override
public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {

            ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
            UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
                    getContext(), getCount(), updatelist);

            if (results.equals(constraint)) {
                updatelist.add(modelobj);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {

                notifyDataSetInvalidated();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults filterResults = new FilterResults();
            list = new ArrayList<UserListModel>();

            if (constraint != null && DrawerActivity.userlist != null) {

                constraint = constraint.toString().toLowerCase();
                int length = DrawerActivity.userlist.size();
                int i = 0;
                while (i < length) {

                    UserListModel modelobj = DrawerActivity.userlist.get(i);
                    String data = modelobj.getFirstName() + " "
                            + modelobj.getLastName();
                    if (data.toLowerCase().contains(constraint.toString())) {
                        list.add(modelobj);
                    }

                    i++;
                }
                filterResults.values = list;
                filterResults.count = list.size();
            }
            return filterResults;
        }
    };
}

@Override
public int getCount() {
    return list.size();
}

@Override
public UserListModel getItem(int position) {

    return list.get(position);
}

MySQL Workbench not displaying query results

MySQL Workbench 6.3.4 fixes this issue. Custom builds are not needed anymore.

http://dev.mysql.com/downloads/workbench/

Chrome refuses to execute an AJAX script due to wrong MIME type

I encountered this error using IIS 7.0 with a custom 404 error page, although I suspect this will happen with any 404 page. The server returned an html 404 response with a text/html mime type which could not (rightly) be executed.

Generate a UUID on iOS from Swift

For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.

Remove all constraints affecting a UIView

In Swift:

import UIKit

extension UIView {

    /**
     Removes all constrains for this view
     */
    func removeConstraints() {

        let constraints = self.superview?.constraints.filter{
            $0.firstItem as? UIView == self || $0.secondItem as? UIView == self
        } ?? []

        self.superview?.removeConstraints(constraints)
        self.removeConstraints(self.constraints)
    }
}

SSL Error: unable to get local issuer certificate

If you are a linux user Update node to a later version by running

sudo apt update

 sudo apt install build-essential checkinstall libssl-dev

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash

nvm --version

nvm ls

nvm ls-remote

nvm install [version.number]

this should solve your problem

Firefox 'Cross-Origin Request Blocked' despite headers

In my case CORS error was happening only in POST requests with file attachments other than small files.

After many wasted hours we found out request was blocked for users who were using Kaspersky Total Control.

It's possible that other antivirus or firewall software may cause similar problems. Kaspersky run some security tests for requests, but omits them for websites with SSL EV certificate, so obtaining such certificate should resolve this issue properly.

Disabling protection for your domain is a bit tricky, so here are required steps (as for December 2020): Settings -> Network Settings -> Manage exclusions -> Add -> your domain -> Save

The good thing is you can detect such blocked request. The error is empty – it doesn't have status and response. This way you can assume it was blocked by third party software and show some info.

Shall we always use [unowned self] inside closure in Swift

Update 11/2016

I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.

Original answer

The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.

The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.

swift weak vs unowned

Scenarios

You can have two possible scenarios:

  1. The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the [unowned self] used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.

  2. The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the [weak delegate] you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.

Actual Usage

So, which will/should you actually use most of the times?

Quoting Joe Groff from twitter:

Unowned is faster and allows for immutability and nonoptionality.

If you don't need weak, don't use it.

You'll find more about unowned* inner workings here.

* Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.

java.lang.Exception: No runnable methods exception in running JUnits

I was able to fix by manually adding the junit jar to my project classpath. The easiest way I found to do this was by adding a /lib directory in the project root. Then i just put the junit.jar inside /lib and junit tests starting working for me.

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I had this error in my DNN application installed on Windows 2012 R2. It's using some 32 bit dll and only Oracle.DataAccess.dll x32 was working. My solution is:

  1. Uninstall old Oracle Client \ ODAC.
  2. Install Oracle 11 Client x32.
  3. Install Oracle ODAC 12 x64.
  4. Check IIS Application Pool (Classic version) has option "Enable 32-Bit Applications" = true.

Swift Beta performance: sorting arrays

From The Swift Programming Language:

The Sort Function Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sort function returns a new array of the same type and size as the old one, with its elements in the correct sorted order.

The sort function has two declarations.

The default declaration which allows you to specify a comparison closure:

func sort<T>(array: T[], pred: (T, T) -> Bool) -> T[]

And a second declaration that only take a single parameter (the array) and is "hardcoded to use the less-than comparator."

func sort<T : Comparable>(array: T[]) -> T[]

Example:
sort( _arrayToSort_ ) { $0 > $1 }

I tested a modified version of your code in a playground with the closure added on so I could monitor the function a little more closely, and I found that with n set to 1000, the closure was being called about 11,000 times.

let n = 1000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
    x[i] = random()
}
let y = sort(x) { $0 > $1 }

It is not an efficient function, an I would recommend using a better sorting function implementation.

EDIT:

I took a look at the Quicksort wikipedia page and wrote a Swift implementation for it. Here is the full program I used (in a playground)

import Foundation

func quickSort(inout array: Int[], begin: Int, end: Int) {
    if (begin < end) {
        let p = partition(&array, begin, end)
        quickSort(&array, begin, p - 1)
        quickSort(&array, p + 1, end)
    }
}

func partition(inout array: Int[], left: Int, right: Int) -> Int {
    let numElements = right - left + 1
    let pivotIndex = left + numElements / 2
    let pivotValue = array[pivotIndex]
    swap(&array[pivotIndex], &array[right])
    var storeIndex = left
    for i in left..right {
        let a = 1 // <- Used to see how many comparisons are made
        if array[i] <= pivotValue {
            swap(&array[i], &array[storeIndex])
            storeIndex++
        }
    }
    swap(&array[storeIndex], &array[right]) // Move pivot to its final place
    return storeIndex
}

let n = 1000
var x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
    x[i] = Int(arc4random())
}

quickSort(&x, 0, x.count - 1) // <- Does the sorting

for i in 0..n {
    x[i] // <- Used by the playground to display the results
}

Using this with n=1000, I found that

  1. quickSort() got called about 650 times,
  2. about 6000 swaps were made,
  3. and there are about 10,000 comparisons

It seems that the built-in sort method is (or is close to) quick sort, and is really slow...

Using a dispatch_once singleton model in Swift

I use the following syntax:

public final class Singleton {    
    private class func sharedInstance() -> Singleton {
        struct Static {
            //Singleton instance.
            static let sharedInstance = Singleton()
        }
        return Static.sharedInstance
    }

    private init() { }

    class var instance: Singleton {
        return sharedInstance()
    }
}

This works from Swift 1.2 up to 4, and has several advantages:

  1. Reminds the user not to subclass implementation
  2. Prevents creation of additional instances
  3. Ensures lazy creation and unique instantiation
  4. Shortens syntax (avoids ()) by allowing to access instance as Singleton.instance

Css Move element from left to right animated

Try this

_x000D_
_x000D_
div_x000D_
{_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:red;_x000D_
  transition: all 1s ease-in-out;_x000D_
  -webkit-transition: all 1s ease-in-out;_x000D_
  -moz-transition: all 1s ease-in-out;_x000D_
  -o-transition: all 1s ease-in-out;_x000D_
  -ms-transition: all 1s ease-in-out;_x000D_
  position:absolute;_x000D_
}_x000D_
div:hover_x000D_
{_x000D_
  transform: translate(3em,0);_x000D_
  -webkit-transform: translate(3em,0);_x000D_
  -moz-transform: translate(3em,0);_x000D_
  -o-transform: translate(3em,0);_x000D_
  -ms-transform: translate(3em,0);_x000D_
}
_x000D_
<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>_x000D_
<div></div>_x000D_
<p>Hover over the div element above, to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

DEMO

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

I solved the simmilar problem, when i tried to push to repo via gitlab ci/cd pipeline by the command "gem install rake && bundle install"

Download and install an ipa from self hosted url on iOS

Yes, safari will detect the *.ipa and will try to install it, but the ipa needs to be correctly signed and only allowed devices would be able to install it.

http://www.diawi.com is a service that will help you with this process.

All of this is for Ad-hoc distribution, not for production apps.

More information on below link : Is there a way to install iPhone App via browser?

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:

install:

sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)

log:

tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:

/etc/redis/redis.conf

Then paste it at <path to conf>, tweak as needed and you're good to go.

How to find what code is run by a button or element in Chrome using Developer Tools

This solution needs the jQuery's data method.

  1. Open Chrome's console (although any browser with jQuery loaded will work)
  2. Run $._data($(".example").get(0), "events")
  3. Drill down the output to find the desired event handler.
  4. Right-click on "handler" and select "Show function definition"
  5. The code will be shown in the Sources tab

$._data() is just accessing jQuery's data method. A more readable alternative could be jQuery._data().

Interesting point by this SO answer:

As of jQuery 1.8, the event data is no longer available from the "public API" for data. Read this jQuery blog post. You should now use this instead:

jQuery._data( elem, "events" ); elem should be an HTML Element, not a jQuery object, or selector.

Please note, that this is an internal, 'private' structure, and shouldn't be modified. Use this for debugging purposes only.

In older versions of jQuery, you might have to use the old method which is:

jQuery( elem ).data( "events" );

A version agnostic jQuery would be: (jQuery._data || jQuery.data)(elem, 'events');

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

How to get an IFrame to be responsive in iOS Safari?

in fact for me just worked in ios disabling the scroll

<iframe src="//www.youraddress.com/" scrolling="no"></iframe>

and treating the OS via script.

How to clear gradle cache?

there seems to be incorrect info posted here. some people report on how to clear the Android builder cache (with task cleanBuildCache) but do not seem to realize that said cache is independent of Gradle's build cache, AFAIK.

my understanding is that Android's cache predates (and inspired) Gradle's, but i could be wrong. whether the Android builder will be/was updated to use Gradle's cache and retire its own, i do not know.

EDIT: the Android builder cache is obsolete and has been eliminated. the Android Gradle plugin now uses Gradle's build cache instead. to control this cache you must now interact with Gradle's generic cache infrastructure.

TIP: search for Gradle's cache help online without mentioning the keyword 'android' to get help for the currently relevant cache.

EDIT 2: due to tir38's question in a comment below, i am testing using an Android Gradle plugin v3.4.2 project. the gradle cache is enabled by org.gradle.caching=true in gradle.properties. i do a couple of clean build and the second time most tasks show FROM-CACHE as their status, showing that the cache is working.

surprisingly, i have a cleanBuildCache gradle task and a <user-home>/.android/build-cache/3.4.2/ directory, both hinting the existence of an Android builder cache.

i execute cleanBuildCache and the 3.4.2/ directory is gone. next i do another clean build:

  • nothing changed: most tasks show FROM-CACHE as their status and the build completed at cache-enabled speeds.
  • the 3.4.2/ directory is recreated.
  • the 3.4.2/ directory is empty (save for 2 hidden, zero length marker files).

conclusions:

  1. caching of all normal Android builder tasks is handled by Gradle.
  2. executing cleanBuildCache does not clear or affect the build cache in any way.
  3. there is still an Android builder cache there. this could be vestigial code that the Android build team forgot to remove, or it could actually cache something strange that for whatever reason has not or cannot be ported to using the Gradle cache. (the 'cannot' option being highly improvable, IMHO.)

next, i disable the Gradle cache by removing org.gradle.caching=true from gradle.properties and i try a couple of clean build:

  • the builds are slow.
  • all tasks show their status as being executed and not cached or up to date.
  • the 3.4.2/ directory continues to be empty.

more conclusions:

  1. there is no Android builder cache fallback for when the Gradle cache fails to hit.
  2. the Android builder cache, at least for common tasks, has indeed been eliminated as i stated before.
  3. the relevant android doc contains outdated info. in particular the cache is not enabled by default as stated there, and the Gradle cache has to be enabled manually.

EDIT 3: user tir38 confirmed that the Android builder cache is obsolete and has been eliminated with this find. tir38 also created this issue. thanks!

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

Fetch first element which matches criteria

I think this is the best way:

this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);

How to resolve this System.IO.FileNotFoundException

I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.

To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.

public MainWindow()
{
    try
    {
        InitializeComponent();
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}

Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.

Added the reference and problem solved.

How to read Data from Excel sheet in selenium webdriver

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

String FilePath = "/home/lahiru/Desktop/Sample.xls";
FileInputStream fs = new FileInputStream(FilePath);
Workbook wb = Workbook.getWorkbook(fs);

String <variable> = sh.getCell("A2").getContents();

Find unused npm packages in package.json

There is also a package called npm-check:

npm-check

Check for outdated, incorrect, and unused dependencies.

enter image description here

It is quite powerful and actively developed. One of it's features it checking for unused dependencies - for this part it uses the depcheck module mentioned in the other answer.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

For me it was tls12:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Various ways to remove local Git changes

It all depends on exactly what you are trying to undo/revert. Start out by reading the post in Ube's link. But to attempt an answer:

Hard reset

git reset --hard [HEAD]

completely remove all staged and unstaged changes to tracked files.

I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.

Clean

git clean [-f]

Remove files that are not tracked.

For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.

The -f (force) option will also remove files, that are not tracked and are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.

Git clean will not touch files, that are already being tracked.

Checkout "dot"

git checkout .

I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:

"undo all changes in my working tree".

I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.

Stashing

Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.

To sum up

Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using git reset --hard HEAD followed by git clean -f will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. It will wipe everything that has not been committed (except untracked files, in which case, use clean).

All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)

I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use git reset --hard was that you had never staged anything. Had you staged a change, neither git checkout . nor git clean -f would have reverted that.

Hope this covers.

Moment js date time comparison

var startDate = moment(startDateVal, "DD.MM.YYYY");//Date format
var endDate = moment(endDateVal, "DD.MM.YYYY");

var isAfter = moment(startDate).isAfter(endDate);

if (isAfter) {
    window.showErrorMessage("Error Message");
    $(elements.endDate).focus();
    return false;
}

Python Anaconda - How to Safely Uninstall

In my case Anaconda3 was not installed in home directory. Instead, it was installed in root. Therefore, I had to do the following to get it uninstalled:

sudo rm -rf /anaconda3/bin/python

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

How to use _CRT_SECURE_NO_WARNINGS

Under "Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions" add _CRT_SECURE_NO_WARNINGS

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

How could I use requests in asyncio?

There is a good case of async/await loops and threading in an article by Pimin Konstantin Kefaloukos Easy parallel HTTP requests with Python and asyncio:

To minimize the total completion time, we could increase the size of the thread pool to match the number of requests we have to make. Luckily, this is easy to do as we will see next. The code listing below is an example of how to make twenty asynchronous HTTP requests with a thread pool of twenty worker threads:

# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures
import requests

async def main():

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor, 
                requests.get, 
                'http://example.org/'
            )
            for i in range(20)
        ]
        for response in await asyncio.gather(*futures):
            pass


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

This is not a problem with XAML. The error message is saying that it tried to create an instance of DVRClientInterface.MainWindow and your constructor threw an exception.

You will need to look at the "Inner Exception" property to determine the underlying cause. It could be quite literally anything, but should provide direction.

example of an inner exception shown in Visual Studio

An example would be that if you are connecting to a database in the constructor for your window, and for some reason that database is unavailable, the inner exception may be a TimeoutException or a SqlException or any other exception thrown by your database code.

If you are throwing exceptions in static constructors, the exception could be generated from any class referenced by the MainWindow. Class initializers are also run, if any MainWindow fields are calling a method which may throw.

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

Uncaught TypeError: Cannot read property 'value' of null

If in your HTML you have an input element with a name or id with a _ like e.g. first_name or more than one _ like e.g. student_first_name and you also have the Javascript code at the bottom of your Web Page and you are sure you are doing everything else right, then those dashes could be what is messing you up.

Having id or name for your input elements resembling the below

<input type="text" id="first_name" name="first_name">

or

<input type="text" id="student_first_name" name="student_first_name">

Then you try make a call like this below in your JavaScript code

var first_name = document.getElementById("first_name").value;

or

var student_first_name = document.getElementById("student_first_name").value;

You are certainly going to have an error like Uncaught TypeError: Cannot read property 'value' of null in Google Chrome and on Internet Explorer too. I did not get to test that with Firefox.

In my case I removed the dashes, in first_name and renamed it to firstname and from student_first_name to studentfirstname

At the end, I was able to resolve that error with my code now looking as follows for HTML and JavaScript.

HTML

<input type="text" id="firstname" name="firstname">

or

<input type="text" id="studentfirstname" name="studentfirstname">

Javascript

var firstname = document.getElementById("firstname").value;

or

var studentfirstname = document.getElementById("studentfirstname").value;

So if it is within your means to rename the HTML and JavaScript code with those dashes, it may help if that is what is ailing your piece of code. In my case that was what was bugging me.

Hope this helps someone stop pulling their hair like I was.

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

mysql delete under safe mode

Turning off safe mode in Mysql workbench 6.3.4.0

Edit menu => Preferences => SQL Editor : Other section: click on "Safe updates" ... to uncheck option

Workbench Preferences

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

Notice Allowed methods in the response

Connection: close
Date: Tue, 11 Feb 2014 15:17:24 GMT 
Content-Length: 34 
Content-Type: text/html 
Allow: GET, DELETE 
X-Powered-By: Servlet/2.5 JSP/2.1

It accepts only GET and DELETE. Hence, you need to tweak the server to enable PUT and POST as well.

Allow: GET, DELETE

Why not inherit from List<T>?

Prefer Interfaces over Classes

Classes should avoid deriving from classes and instead implement the minimal interfaces necessary.

Inheritance breaks Encapsulation

Deriving from classes breaks encapsulation:

  • exposes internal details about how your collection is implemented
  • declares an interface (set of public functions and properties) that may not be appropriate

Among other things this makes it harder to refactor your code.

Classes are an Implementation Detail

Classes are an implementation detail that should be hidden from other parts of your code. In short a System.List is a specific implementation of an abstract data type, that may or may not be appropriate now and in the future.

Conceptually the fact that the System.List data type is called "list" is a bit of a red-herring. A System.List<T> is a mutable ordered collection that supports amortized O(1) operations for adding, inserting, and removing elements, and O(1) operations for retrieving the number of elements or getting and setting element by index.

The Smaller the Interface the more Flexible the Code

When designing a data structure, the simpler the interface is, the more flexible the code is. Just look at how powerful LINQ is for a demonstration of this.

How to Choose Interfaces

When you think "list" you should start by saying to yourself, "I need to represent a collection of baseball players". So let's say you decide to model this with a class. What you should do first is decide what the minimal amount of interfaces that this class will need to expose.

Some questions that can help guide this process:

  • Do I need to have the count? If not consider implementing IEnumerable<T>
  • Is this collection going to change after it has been initialized? If not consider IReadonlyList<T>.
  • Is it important that I can access items by index? Consider ICollection<T>
  • Is the order in which I add items to the collection important? Maybe it is an ISet<T>?
  • If you indeed want these thing then go ahead and implement IList<T>.

This way you will not be coupling other parts of the code to implementation details of your baseball players collection and will be free to change how it is implemented as long as you respect the interface.

By taking this approach you will find that code becomes easier to read, refactor, and reuse.

Notes about Avoiding Boilerplate

Implementing interfaces in a modern IDE should be easy. Right click and choose "Implement Interface". Then forward all of the implementations to a member class if you need to.

That said, if you find you are writing lots of boilerplate, it is potentially because you are exposing more functions than you should be. It is the same reason you shouldn't inherit from a class.

You can also design smaller interfaces that make sense for your application, and maybe just a couple of helper extension functions to map those interfaces to any others that you need. This is the approach I took in my own IArray interface for the LinqArray library.

Autoincrement VersionCode with gradle extra properties

Another option, for incrementing the versionCode and the versionName, is using a timestamp.

defaultConfig {
   versionName "${getVersionNameTimestamp()}"
   versionCode getVersionCodeTimestamp()
}


def getVersionNameTimestamp() {
    return new Date().format('yy.MM.ddHHmm')
}

def getVersionCodeTimestamp() {
    def date = new Date()
    def formattedDate = date.format('yyMMddHHmm')
    def code = formattedDate.toInteger()
    println sprintf("VersionCode: %d", code)
    return code
}

Starting on January,1 2022 formattedDate = date.format('yyMMddHHmm') exceeds the capacity of Integers

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Near the top of the code with the Public Workshop(), I am assumeing this bit,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);

should maybe be,

suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);


denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);

How to Detect Browser Window /Tab Close Event?

This code prevents the checkbox events. It works when user clicks on browser close button but it doesn't work when checkbox clicked. You can modify it for other controls(texbox, radiobutton etc.)

    window.onbeforeunload = function () {
        return "Are you sure?";
    }

    $(function () {
        $('input[type="checkbox"]').click(function () {
            window.onbeforeunload = function () { };
        });
    });

Bootstrap button - remove outline on Chrome OS X

If the above answers still do not work, add this:

button:focus{
    outline: none!important;
    box-shadow:none;
}

Custom thread pool in Java 8 parallel stream

The original solution (setting the ForkJoinPool common parallelism property) no longer works. Looking at the links in the original answer, an update which breaks this has been back ported to Java 8. As mentioned in the linked threads, this solution was not guaranteed to work forever. Based on that, the solution is the forkjoinpool.submit with .get solution discussed in the accepted answer. I think the backport fixes the unreliability of this solution also.

ForkJoinPool fjpool = new ForkJoinPool(10);
System.out.println("stream.parallel");
IntStream range = IntStream.range(0, 20);
fjpool.submit(() -> range.parallel()
        .forEach((int theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();
System.out.println("list.parallelStream");
int [] array = IntStream.range(0, 20).toArray();
List<Integer> list = new ArrayList<>();
for (int theInt: array)
{
    list.add(theInt);
}
fjpool.submit(() -> list.parallelStream()
        .forEach((theInt) ->
        {
            try { Thread.sleep(100); } catch (Exception ignore) {}
            System.out.println(Thread.currentThread().getName() + " -- " + theInt);
        })).get();

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

Ubuntu (Linux)

:- $ sudo gedit /opt/lampp/etc/extra/httpd-xampp.conf

 Comment "Deny from all" in the following section,

Change file

# New XAMPP security concept
# <LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow

   #Deny from all
   #Require local
    Allow from ::1 127.0.0.0/8 \
            fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
            fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var

What is "export default" in JavaScript?

In my opinion, the important thing about the default export is that it can be imported with any name!

If there is a file, foo.js, which exports default:

_x000D_
_x000D_
export default function foo(){}
_x000D_
_x000D_
_x000D_

it can be imported in bar.js using:

_x000D_
_x000D_
import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
_x000D_
_x000D_
_x000D_

How can I remove Nan from list Python/NumPy

I noticed that Pandas for example will return 'nan' for blank values. Since it's not a string you need to convert it to one in order to match it. For example:

ulist = df.column1.unique() #create a list from a column with Pandas which 
for loc in ulist:
    loc = str(loc)   #here 'nan' is converted to a string to compare with if
    if loc != 'nan':
        print(loc)

HTML5 video won't play in Chrome only

To all of you who got here and did not found the right solution, i found out that the mp4 video needs to fit a specific format.

My Problem was that i got an 1920x1080 video which wont load under Chrome (under Firefox it worked like a charm). After hours of searching i finaly managed to get hang of the problem, the first few streams where 1912x1088 so Chrome wont play it ( i got the exact stream size from the tool MediaInfo). So to fix it i just resized it to 1920x1080 and it worked.

Bootstrap 3 - jumbotron background image effect

I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :

background-attachment: fixed;

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I had a same issue. It was working fine on the local machine but it had issues on the server. I have changed the SMTP setting. It works fine for me.

If you're using GoDaddy Plesk Hosting, use the following SMTP details.

Host = relay-hosting.secureserver.net
Port = 25 

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Access-Control-Allow-Origin and Angular.js $http

Try with this:

          $.ajax({
              type: 'POST',
              url: URL,
              defaultHeaders: {
                  'Content-Type': 'application/json',
                  "Access-Control-Allow-Origin": "*",
                  'Accept': 'application/json'
               },

              data: obj,
              dataType: 'json',
              success: function (response) {
            //    BindTableData();
                console.log("success ");
                alert(response);
              },
              error: function (xhr) {
                console.log("error ");
                console.log(xhr);
              }
          });

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

add this code to Your AppKernel Class:

public function init()
{
    date_default_timezone_set('Asia/Tehran');
    parent::init();
}

window.open(url, '_blank'); not working on iMac/Safari

To use window.open() in safari you must put it in an element's onclick event attribute.

For example: <button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

Removing .txt after LICENSE removed my error :

packagingOptions {
    exclude 'META-INF/LICENSE'
}

Safest way to run BAT file from Powershell script

cmd.exe /c '\my-app\my-file.bat'

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

"The system cannot find the file specified"

Considering that a LocalDb instance only intended for use in development. LocalDb is not available for production servers When you deploy the final result.

I think your connection string is pointing to a LocalDb instance and you need to take certain steps to turn it into the SQL Server database. It's not just a matter of copying an mdf file either. It will possibly differ from one hosting company to another, but typically, you need to create a backup of your existing database (a .bak file) and then restore that to the hosting company's SQL Server. You should ask them where you can find instructions on deploying your database into production.

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

Actualy you can do almost everything with dropdown field, and it will looks the same on every browser, take a look at code example

select.custom {
  background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20fill%3D%22%23555555%22%20%0A%09%20width%3D%2224px%22%20height%3D%2224px%22%20viewBox%3D%22-261%20145.2%2024%2024%22%20style%3D%22enable-background%3Anew%20-261%20145.2%2024%2024%3B%22%20xml%3Aspace%3D%22preserve%22%3E%0A%3Cpath%20d%3D%22M-245.3%2C156.1l-3.6-6.5l-3.7%2C6.5%20M-252.7%2C159l3.7%2C6.5l3.6-6.5%22%2F%3E%0A%3C%2Fsvg%3E");
  padding-right: 25px;
  background-repeat: no-repeat;
  background-position: right center;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

select.custom::-ms-expand {
  display: none;
}

https://jsfiddle.net/x76j455z/10/

How to quickly and conveniently create a one element arraylist

The other answers all use Arrays.asList(), which returns an unmodifiable list (an UnsupportedOperationException is thrown if you try to add or remove an element). To get a mutable list you can wrap the returned list in a new ArrayList as a couple of answers point out, but a cleaner solution is to use Guava's Lists.newArrayList() (available since at least Guava 10, released in 2011).

For example:

Lists.newArrayList("Blargle!");

Access denied for user 'test'@'localhost' (using password: YES) except root user

If you are connecting to the MySQL using remote machine(Example workbench) etc., use following steps to eliminate this error on OS where MySQL is installed

mysql -u root -p

CREATE USER '<<username>>'@'%%' IDENTIFIED BY '<<password>>';
GRANT ALL PRIVILEGES ON * . * TO '<<username>>'@'%%';
FLUSH PRIVILEGES;

Try logging into the MYSQL instance.
This worked for me to eliminate this error.

HTML5 Video tag not working in Safari , iPhone and iPad

I had this problem where .mp4 playback in Safari didn't work, but in other browsers it was fine. The error that I was seeing in the console was: error media src not supported. In my case this turned out to be a MIME type issue, but not because it wasn't declared as MIME type in IIS, rather that it was declared twice (once in IIS and also in a web.config file). I found this out by trying to download the .mp4 file locally on the server. I removed the config file from the location of the content I was trying to play and it fixed the issue. I could have just deleted the MIME type from the web.config file, but in this case the web.config file wasn't needed.

Remove blue border from css custom-styled button in Chrome

The fix for Chrome and other browsers

button:focus { outline: none !important; box-shadow: none !important; }

MySQL Daemon Failed to Start - centos 6

RE: MySQL Daemon Failed to Start - centos 6 / RHEL 6

  1. Yum Install MySQL
  2. /etc/init.d/mysqld start MySQL Daemon failed to start. Starting mysqld: [FAILED]

  3. Review The log: /var/log/mysqld.log

  4. You might get this error: [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.

Solution that works for me is running this:

  1. $ mysql_install_db

Please let me know if this won't solve your issue.

What happens if you mount to a non-empty mount point with fuse?

For me the error message goes away if I unmount the old mount before mounting it again:

fusermount -u /mnt/point

If it's not already mounted you get a non-critical error:

$ fusermount -u /mnt/point

fusermount: entry for /mnt/point not found in /etc/mtab

So in my script I just put unmount it before mounting it.

How do I get Flask to run on port 80?

You don't need to change port number for your application, just configure your www server (nginx or apache) to proxy queries to flask port. Pay attantion on uWSGI.

OwinStartup not firing

DEBUGGING TIPS

If debugging does not work try using IIS Express or try the method below for local IIS

Using local IIS

For some reason this method enables debugging of this method:

  1. Request a webpage
  2. Attach to w3wp.exe process
  3. Touch the web.config file
  4. Request a webpage

Extra tip

Maybe doing this will flush a cache:

  1. In web.config add the optimizeCompilations attribute with a false value

    <compilation debug="true" ... optimizeCompilations="false">

  2. Run site

  3. Undo the change in web.config

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;
}

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

Match linebreaks - \n or \r\n?

You have different line endings in the example texts in Debuggex. What is especially interesting is that Debuggex seems to have identified which line ending style you used first, and it converts all additional line endings entered to that style.

I used Notepad++ to paste sample text in Unix and Windows format into Debuggex, and whichever I pasted first is what that session of Debuggex stuck with.

So, you should wash your text through your text editor before pasting it into Debuggex. Ensure that you're pasting the style you want. Debuggex defaults to Unix style (\n).

Also, NEL (\u0085) is something different entirely: https://en.wikipedia.org/wiki/Newline#Unicode

(\r?\n) will cover Unix and Windows. You'll need something more complex, like (\r\n|\r|\n), if you want to match old Mac too.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I had the same problem. mysql -u root -p worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password, if you did not set one. More info here.

Plotting multiple time series on the same plot using ggplot()

An alternative is to bind the dataframes, and assign them the type of variable they represent. This will let you use the full dataset in a tidier way

library(ggplot2)
library(dplyr)

df1 <- data.frame(dates = 1:10,Variable = rnorm(mean = 0.5,10))
df2 <- data.frame(dates = 1:10,Variable = rnorm(mean = -0.5,10))

df3 <- df1 %>%
  mutate(Type = 'a') %>%
  bind_rows(df2 %>%
              mutate(Type = 'b'))


ggplot(df3,aes(y = Variable,x = dates,color = Type)) + 
  geom_line()

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Playing m3u8 Files with HTML Video Tag

In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.

    <video controls>
      <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
      <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
      <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
      <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
    </video>

We can add an external HLS js script in web application.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Your title</title>
      
    
      <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
      <script src="https://unpkg.com/video.js/dist/video.js"></script>
      <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
       
    </head>
    <body>
      <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
      data-setup='{}'>
        <source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
      </video>
      
    <script>
    var player = videojs('my_video_1');
    player.play();
    </script>
      
    </body>
    </html>

Chrome Extension - Get DOM content

For those who tried gkalpak answer and it did not work,

be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes

Console.log not working at all

In my case, all console messages were not showing because I had left a string in the "filter" textbox.

Remove the filter it by clicking the X as shown:

enter image description here

How to tell if UIViewController's view is visible

I found those function in UIViewController.h.

/*
  These four methods can be used in a view controller's appearance callbacks to determine if it is being
  presented, dismissed, or added or removed as a child view controller. For example, a view controller can
  check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
  method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/

- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);

- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);

Maybe the above functions can detect the ViewController is appeared or not.

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

I like to use the following approach for headers on a ComboBox where the CboBx is not loaded from a worksheet (data from sql for example). The reason I specify not from a worksheet is that I think the only way to get RowSource to work is if you load from a worksheet.

This works for me:

  1. Create your ComboBox and create a ListBox with an identical layout but just one row.
  2. Place the ListBox directly on top of the ComboBox.
  3. In your VBA, load ListBox row1 with the desired headers.
  4. In your VBA for the action yourListBoxName_Click, enter the following code:

    yourComboBoxName.Activate`
    yourComboBoxName.DropDown`
    
  5. When you click on the listbox, the combobox will drop down and function normally while the headings (in the listbox) remain above the list.

Access Control Request Headers, is added to header in AJAX request with jQuery

From client side, I cant solve this problem. From nodejs express side, you can use cors module to handle it.

var express       = require('express');
var app           = express();
var bodyParser = require('body-parser');
var cors = require('cors');

var port = 3000; 
var ip = '127.0.0.1';

app.use('*/myapi', 
          cors(), // with this row OPTIONS has handled
          bodyParser.text({type:'text/*'}),
          function( req, res, next ){
    console.log( '\n.----------------' + req.method + '------------------------' );
        console.log( '| prot:'+req.protocol );
        console.log( '| host:'+req.get('host') );
        console.log( '| url:'+req.originalUrl );
        console.log( '| body:',req.body );
        //console.log( '| req:',req );
    console.log( '.----------------' + req.method + '------------------------' );
    next();
    });

app.listen(port, ip, function() {
    console.log('Listening to port:  ' + port );
});
 
console.log(('dir:'+__dirname ));
console.log('The server is up and running at http://'+ip+':'+port+'/');

Without cors() this OPTIONS has appears before POST.

.----------------OPTIONS------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: {}
.----------------OPTIONS------------------------

.----------------POST------------------------
| prot:http
| host:localhost:3000
| url:/myapi
| body: <SOAP-ENV:Envelope .. P-ENV:Envelope>
.----------------POST------------------------

The ajax call:

$.ajax({
    type: 'POST',
    contentType: "text/xml; charset=utf-8",
// these does not works
    //beforeSend: function(request) { 
    //  request.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
    //  request.setRequestHeader('Accept', 'application/vnd.realtime247.sct-giro-v1+cms');
    //  request.setRequestHeader('Access-Control-Allow-Origin', '*');
    //  request.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET');
    //  request.setRequestHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type');
    //},
    //headers: {
    //  'Content-Type': 'text/xml; charset=utf-8',
    //  'Accept': 'application/vnd.realtime247.sct-giro-v1+cms',
    //  'Access-Control-Allow-Origin': '*',
    //  'Access-Control-Allow-Methods': 'POST, GET',
    //  'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type'
    //},
    url: 'http://localhost:3000/myapi',             
    data:       '<SOAP-ENV:Envelope .. P-ENV:Envelope>',                
    success: function( data ) {
      console.log(data.documentElement.innerHTML);
    },
    error: function(jqXHR, textStatus, err) {
      console.log( jqXHR,'\n', textStatus,'\n', err )
    }
  });

Java ArrayList for integers

you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work

Print in one line dynamically

Another answer that I'm using on 2.7 where I'm just printing out a "." every time a loop runs (to indicate to the user that things are still running) is this:

print "\b.",

It prints the "." characters without spaces between each. It looks a little better and works pretty well. The \b is a backspace character for those wondering.

What are the best practices for SQLite on Android?

  • Use a Thread or AsyncTask for long-running operations (50ms+). Test your app to see where that is. Most operations (probably) don't require a thread, because most operations (probably) only involve a few rows. Use a thread for bulk operations.
  • Share one SQLiteDatabase instance for each DB on disk between threads and implement a counting system to keep track of open connections.

Are there any best practices for these scenarios?

Share a static field between all your classes. I used to keep a singleton around for that and other things that need to be shared. A counting scheme (generally using AtomicInteger) also should be used to make sure you never close the database early or leave it open.

My solution:

The old version I wrote is available at https://github.com/Taeluf/dev/tree/main/archived/databasemanager and is not maintained. If you want to understand my solution, look at the code and read my notes. My notes are usually pretty helpful.

  1. copy/paste the code into a new file named DatabaseManager. (or download it from github)
  2. extend DatabaseManager and implement onCreate and onUpgrade like you normally would. You can create multiple subclasses of the one DatabaseManager class in order to have different databases on disk.
  3. Instantiate your subclass and call getDb() to use the SQLiteDatabase class.
  4. Call close() for each subclass you instantiated

The code to copy/paste:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import java.util.concurrent.ConcurrentHashMap;

/** Extend this class and use it as an SQLiteOpenHelper class
 *
 * DO NOT distribute, sell, or present this code as your own. 
 * for any distributing/selling, or whatever, see the info at the link below
 *
 * Distribution, attribution, legal stuff,
 * See https://github.com/JakarCo/databasemanager
 * 
 * If you ever need help with this code, contact me at [email protected] (or [email protected] )
 * 
 * Do not sell this. but use it as much as you want. There are no implied or express warranties with this code. 
 *
 * This is a simple database manager class which makes threading/synchronization super easy.
 *
 * Extend this class and use it like an SQLiteOpenHelper, but use it as follows:
 *  Instantiate this class once in each thread that uses the database. 
 *  Make sure to call {@link #close()} on every opened instance of this class
 *  If it is closed, then call {@link #open()} before using again.
 * 
 * Call {@link #getDb()} to get an instance of the underlying SQLiteDatabse class (which is synchronized)
 *
 * I also implement this system (well, it's very similar) in my <a href="http://androidslitelibrary.com">Android SQLite Libray</a> at http://androidslitelibrary.com
 * 
 *
 */
abstract public class DatabaseManager {
    
    /**See SQLiteOpenHelper documentation
    */
    abstract public void onCreate(SQLiteDatabase db);
    /**See SQLiteOpenHelper documentation
     */
    abstract public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
    /**Optional.
     * *
     */
    public void onOpen(SQLiteDatabase db){}
    /**Optional.
     * 
     */
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
    /**Optional
     * 
     */
    public void onConfigure(SQLiteDatabase db){}



    /** The SQLiteOpenHelper class is not actually used by your application.
     *
     */
    static private class DBSQLiteOpenHelper extends SQLiteOpenHelper {

        DatabaseManager databaseManager;
        private AtomicInteger counter = new AtomicInteger(0);

        public DBSQLiteOpenHelper(Context context, String name, int version, DatabaseManager databaseManager) {
            super(context, name, null, version);
            this.databaseManager = databaseManager;
        }

        public void addConnection(){
            counter.incrementAndGet();
        }
        public void removeConnection(){
            counter.decrementAndGet();
        }
        public int getCounter() {
            return counter.get();
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            databaseManager.onCreate(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            databaseManager.onUpgrade(db, oldVersion, newVersion);
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            databaseManager.onOpen(db);
        }

        @Override
        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            databaseManager.onDowngrade(db, oldVersion, newVersion);
        }

        @Override
        public void onConfigure(SQLiteDatabase db) {
            databaseManager.onConfigure(db);
        }
    }

    private static final ConcurrentHashMap<String,DBSQLiteOpenHelper> dbMap = new ConcurrentHashMap<String, DBSQLiteOpenHelper>();

    private static final Object lockObject = new Object();


    private DBSQLiteOpenHelper sqLiteOpenHelper;
    private SQLiteDatabase db;
    private Context context;

    /** Instantiate a new DB Helper. 
     * <br> SQLiteOpenHelpers are statically cached so they (and their internally cached SQLiteDatabases) will be reused for concurrency
     *
     * @param context Any {@link android.content.Context} belonging to your package.
     * @param name The database name. This may be anything you like. Adding a file extension is not required and any file extension you would like to use is fine.
     * @param version the database version.
     */
    public DatabaseManager(Context context, String name, int version) {
        String dbPath = context.getApplicationContext().getDatabasePath(name).getAbsolutePath();
        synchronized (lockObject) {
            sqLiteOpenHelper = dbMap.get(dbPath);
            if (sqLiteOpenHelper==null) {
                sqLiteOpenHelper = new DBSQLiteOpenHelper(context, name, version, this);
                dbMap.put(dbPath,sqLiteOpenHelper);
            }
            //SQLiteOpenHelper class caches the SQLiteDatabase, so this will be the same SQLiteDatabase object every time
            db = sqLiteOpenHelper.getWritableDatabase();
        }
        this.context = context.getApplicationContext();
    }
    /**Get the writable SQLiteDatabase
     */
    public SQLiteDatabase getDb(){
        return db;
    }

    /** Check if the underlying SQLiteDatabase is open
     *
     * @return whether the DB is open or not
     */
    public boolean isOpen(){
        return (db!=null&&db.isOpen());
    }


    /** Lowers the DB counter by 1 for any {@link DatabaseManager}s referencing the same DB on disk
     *  <br />If the new counter is 0, then the database will be closed.
     *  <br /><br />This needs to be called before application exit.
     * <br />If the counter is 0, then the underlying SQLiteDatabase is <b>null</b> until another DatabaseManager is instantiated or you call {@link #open()}
     *
     * @return true if the underlying {@link android.database.sqlite.SQLiteDatabase} is closed (counter is 0), and false otherwise (counter > 0)
     */
    public boolean close(){
        sqLiteOpenHelper.removeConnection();
        if (sqLiteOpenHelper.getCounter()==0){
            synchronized (lockObject){
                if (db.inTransaction())db.endTransaction();
                if (db.isOpen())db.close();
                db = null;
            }
            return true;
        }
        return false;
    }
    /** Increments the internal db counter by one and opens the db if needed
    *
    */
    public void open(){
        sqLiteOpenHelper.addConnection();
        if (db==null||!db.isOpen()){
                synchronized (lockObject){
                    db = sqLiteOpenHelper.getWritableDatabase();
                }
        } 
    }
}

How to include CSS file in Symfony 2 and Twig?

The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/ folder to store all assets, instead of different bundles.

Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.

Templates also benefit from centralizing your assets, because the links are much more concise[...]

I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.

Outline radius?

Try using padding and a background color for the border, then a border for the outline:

.round_outline {
  padding: 8px;
  background-color: white;
  border-radius: 50%;
  border: 1px solid black;
}

Worked in my case.

How to count the number of rows in excel with data?

Safest option is

Lastrow =  Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
Lastcol =  Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column

Don't use UsedRange or SpecialCells(xlLastCell) or End(xlUp). All these methods may give wrong results if you previously deleted some rows. Excel still counts these invisible cells.

These methods will work again if you delete your cells, save the workbook, close and re-open it.

How to Detect Browser Back Button event - Cross Browser

I had been struggling with this requirement for quite a while and took some of the solutions above to implement it. However, I stumbled upon an observation and it seems to work across Chrome, Firefox and Safari browsers + Android and iPhone

On page load:

window.history.pushState({page: 1}, "", "");

window.onpopstate = function(event) {

  // "event" object seems to contain value only when the back button is clicked
  // and if the pop state event fires due to clicks on a button
  // or a link it comes up as "undefined" 

  if(event){
    // Code to handle back button or prevent from navigation
  }
  else{
    // Continue user action through link or button
  }
}

Let me know if this helps. If am missing something, I will be happy to understand.

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

I was getting this error in websphere 8.5:

java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=com/xxx/Whatever, offset=6

I had my project JDK level set at 1.7 in eclipse and was8 by default runs on JDK 1.6 so there was a clash. I had to install the optional SDK 1.7 to my websphere server and then the problem went away. I guess I could have also set my project level down to 1.6 in eclipse but I wanted to code to 1.7.

How to run (not only install) an android application using .apk file?

if you're looking for the equivalent of "adb run myapp.apk"

you can use the script shown in this answer

(linux and mac only - maybe with cygwin on windows)

linux/mac users can also create a script to run an apk with something like the following:

create a file named "adb-run.sh" with these 3 lines:

pkg=$(aapt dump badging $1|awk -F" " '/package/ {print $2}'|awk -F"'" '/name=/ {print $2}')
act=$(aapt dump badging $1|awk -F" " '/launchable-activity/ {print $2}'|awk -F"'" '/name=/ {print $2}')
adb shell am start -n $pkg/$act

then "chmod +x adb-run.sh" to make it executable.

now you can simply:

adb-run.sh myapp.apk

The benefit here is that you don't need to know the package name or launchable activity name. Similarly, you can create "adb-uninstall.sh myapp.apk"

Note: This requires that you have aapt in your path. You can find it under the new build tools folder in the SDK

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

Unescape HTML entities in Javascript?

Do you need to decode all encoded HTML entities or just &amp; itself?

If you only need to handle &amp; then you can do this:

var decoded = encoded.replace(/&amp;/g, '&');

If you need to decode all HTML entities then you can do it without jQuery:

var elem = document.createElement('textarea');
elem.innerHTML = encoded;
var decoded = elem.value;

Please take note of Mark's comments below which highlight security holes in an earlier version of this answer and recommend using textarea rather than div to mitigate against potential XSS vulnerabilities. These vulnerabilities exist whether you use jQuery or plain JavaScript.

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

Extract every nth element of a vector

To select every nth element from any starting position in the vector

nth_element <- function(vector, starting_position, n) { 
  vector[seq(starting_position, length(vector), n)] 
  }

# E.g.
vec <- 1:12

nth_element(vec, 1, 3)
# [1]  1  4  7 10

nth_element(vec, 2, 3)
# [1]  2  5  8 11

Android TextView Justify Text

Try using < RelativeLayout > (making sure to fill_parent), then just add android:layout_alignParentLeft="true" and

android:layout_alignParentRight="true" to the elements you would like on the outside LEFT & RIGHT.

BLAM, justified!

git returns http error 407 from proxy after CONNECT

Removing "@" from password worked for me and in anyways never keep @ in your password it will give you issue with maven and further installation

What's the difference between git reset --mixed, --soft, and --hard?

When you modify a file in your repository, the change is initially unstaged. In order to commit it, you must stage it—that is, add it to the index—using git add. When you make a commit, the changes that are committed are those that have been added to the index.

git reset changes, at minimum, where the current branch (HEAD) is pointing. The difference between --mixed and --soft is whether or not your index is also modified. So, if we're on branch master with this series of commits:

- A - B - C (master)

HEADpoints to C and the index matches C.

When we run git reset --soft B, master (and thus HEAD) now points to B, but the index still has the changes from C; git status will show them as staged. So if we run git commit at this point, we'll get a new commit with the same changes as C.


Okay, so starting from here again:

- A - B - C (master)

Now let's do git reset --mixed B. (Note: --mixed is the default option). Once again, master and HEAD point to B, but this time the index is also modified to match B. If we run git commit at this point, nothing will happen since the index matches HEAD. We still have the changes in the working directory, but since they're not in the index, git status shows them as unstaged. To commit them, you would git add and then commit as usual.


And finally, --hard is the same as --mixed (it changes your HEAD and index), except that --hard also modifies your working directory. If we're at C and run git reset --hard B, then the changes added in C, as well as any uncommitted changes you have, will be removed, and the files in your working copy will match commit B. Since you can permanently lose changes this way, you should always run git status before doing a hard reset to make sure your working directory is clean or that you're okay with losing your uncommitted changes.


And finally, a visualization: enter image description here

Breaking/exit nested for in vb.net

Unfortunately, there's no exit two levels of for statement, but there are a few workarounds to do what you want:

  • Goto. In general, using goto is considered to be bad practice (and rightfully so), but using goto solely for a forward jump out of structured control statements is usually considered to be OK, especially if the alternative is to have more complicated code.

    For Each item In itemList
        For Each item1 In itemList1
            If item1.Text = "bla bla bla" Then
                Goto end_of_for
            End If
        Next
    Next
    
    end_of_for:
    
  • Dummy outer block

    Do
        For Each item In itemList
            For Each item1 In itemList1
                If item1.Text = "bla bla bla" Then
                    Exit Do
                End If
            Next
        Next
    Loop While False
    

    or

    Try
        For Each item In itemlist
            For Each item1 In itemlist1
                If item1 = "bla bla bla" Then
                    Exit Try
                End If
            Next
        Next
    Finally
    End Try
    
  • Separate function: Put the loops inside a separate function, which can be exited with return. This might require you to pass a lot of parameters, though, depending on how many local variables you use inside the loop. An alternative would be to put the block into a multi-line lambda, since this will create a closure over the local variables.

  • Boolean variable: This might make your code a bit less readable, depending on how many layers of nested loops you have:

    Dim done = False
    
    For Each item In itemList
        For Each item1 In itemList1
            If item1.Text = "bla bla bla" Then
                done = True
                Exit For
            End If
        Next
        If done Then Exit For
    Next
    

How can I create a simple index.html file which lists all files/directories?

There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess The source code is easy to understand and provides a good starting point.

Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/

celeron dude indexer

SQL: Combine Select count(*) from multiple tables

select sum(counts) from (
select count(1) as counts from foo 
union all
select count(1) as counts from bar)

DIV table colspan: how?

<div style="clear:both;"></div> - may do the trick in some cases; not a "colspan" but may help achieve what you are looking for...

<div id="table">
    <div class="table_row">
        <div class="table_cell1"></div>
        <div class="table_cell2"></div>
        <div class="table_cell3"></div>
    </div>
    <div class="table_row">
        <div class="table_cell1"></div>
        <div class="table_cell2"></div>
        <div class="table_cell3"></div>
    </div>

<!-- clear:both will clear any float direction to default, and
prevent the previously defined floats from affecting other elements -->
    <div style="clear:both;"></div>

    <div class="table_row">
<!-- the float is cleared, you could have 4 divs (columns) or
just one with 100% width -->
        <div class="table_cell123"></div>
    </div>
</div>

How do I set up a simple delegate to communicate between two view controllers?

Simple example...

Let's say the child view controller has a UISlider and we want to pass the value of the slider back to the parent via a delegate.

In the child view controller's header file, declare the delegate type and its methods:

ChildViewController.h

#import <UIKit/UIKit.h>

// 1. Forward declaration of ChildViewControllerDelegate - this just declares
// that a ChildViewControllerDelegate type exists so that we can use it
// later.
@protocol ChildViewControllerDelegate;

// 2. Declaration of the view controller class, as usual
@interface ChildViewController : UIViewController

// Delegate properties should always be weak references
// See http://stackoverflow.com/a/4796131/263871 for the rationale
// (Tip: If you're not using ARC, use `assign` instead of `weak`)
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;

// A simple IBAction method that I'll associate with a close button in
// the UI. We'll call the delegate's childViewController:didChooseValue: 
// method inside this handler.
- (IBAction)handleCloseButton:(id)sender;

@end

// 3. Definition of the delegate's interface
@protocol ChildViewControllerDelegate <NSObject>

- (void)childViewController:(ChildViewController*)viewController 
             didChooseValue:(CGFloat)value;

@end

In the child view controller's implementation, call the delegate methods as required.

ChildViewController.m

#import "ChildViewController.h"

@implementation ChildViewController

- (void)handleCloseButton:(id)sender {
    // Xcode will complain if we access a weak property more than 
    // once here, since it could in theory be nilled between accesses
    // leading to unpredictable results. So we'll start by taking
    // a local, strong reference to the delegate.
    id<ChildViewControllerDelegate> strongDelegate = self.delegate;

    // Our delegate method is optional, so we should 
    // check that the delegate implements it
    if ([strongDelegate respondsToSelector:@selector(childViewController:didChooseValue:)]) {
        [strongDelegate childViewController:self didChooseValue:self.slider.value];
    }
}

@end

In the parent view controller's header file, declare that it implements the ChildViewControllerDelegate protocol.

RootViewController.h

#import <UIKit/UIKit.h>
#import "ChildViewController.h"

@interface RootViewController : UITableViewController <ChildViewControllerDelegate>

@end

In the parent view controller's implementation, implement the delegate methods appropriately.

RootViewController.m

#import "RootViewController.h"

@implementation RootViewController

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ChildViewController *detailViewController = [[ChildViewController alloc] init];
    // Assign self as the delegate for the child view controller
    detailViewController.delegate = self;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

// Implement the delegate methods for ChildViewControllerDelegate
- (void)childViewController:(ChildViewController *)viewController didChooseValue:(CGFloat)value {

    // Do something with value...

    // ...then dismiss the child view controller
    [self.navigationController popViewControllerAnimated:YES];
}

@end

Hope this helps!

HTML5 Audio Looping

You could try a setInterval, if you know the exact length of the sound. You could have the setInterval play the sound every x seconds. X would be the length of your sound.

How to manually update datatables table with new JSON data

In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).

My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null, for example).

Then I instantiate my table in the on load method

$(function () {
            //.... some code here
            table = $("#detailReportTable").DataTable();
            .... more code here
        });

and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:

function getOrderDetail() {
            table.clear();
            table.destroy();
            ...
            $.ajax({
             //.....api call here
            });
            ....
            table = $("#detailReportTable").DataTable();
   }

I hope someone finds this useful!

OnItemCLickListener not working in listview

I solved it with the help of this answer

1.Add the following in Linear Layout of list_items.xml android:descendantFocusability="blocksDescendants"

2.Child Views of LinearLayout in list_items.xml

 android:focusable="false" 

How to list all users in a Linux group?

The following command will list all users belonging to <your_group_name>, but only those managed by /etc/group database, not LDAP, NIS, etc. It also works for secondary groups only, it won't list users who have that group set as primary since the primary group is stored as GID (numeric group ID) in the file /etc/passwd.

awk -F: '/^groupname/ {print $4;}' /etc/group

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

Little twist to kirill_igum's answer, and you can easily count the number of columns of any certain row you want, which was why I've come to this question, even though the question is asking for the whole file. (Though if your file has same columns in each line this also still works of course):

head -2 file |tail -1 |tr '\t' '\n' |wc -l

Gives the number of columns of row 2. Replace 2 with 55 for example to get it for row 55.

-bash-4.2$ cat file
1       2       3
1       2       3       4
1       2
1       2       3       4       5

-bash-4.2$ head -1 file |tail -1 |tr '\t' '\n' |wc -l
3
-bash-4.2$ head -4 file |tail -1 |tr '\t' '\n' |wc -l
5

Code above works if your file is separated by tabs, as we define it to "tr". If your file has another separator, say commas, you can still count your "columns" using the same trick by simply changing the separator character "t" to ",":

-bash-4.2$ cat csvfile
1,2,3,4
1,2
1,2,3,4,5
-bash-4.2$ head -2 csvfile |tail -1 |tr '\,' '\n' |wc -l
2

Javascript: Unicode string to hex

Here is a tweak of McDowell's algorithm that doesn't pad the result:

  function toHex(str) {
    var result = '';
    for (var i=0; i<str.length; i++) {
      result += str.charCodeAt(i).toString(16);
    }
    return result;
  }

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

How to convert string representation of list to a list?

Assuming that all your inputs are lists and that the double quotes in the input actually don't matter, this can be done with a simple regexp replace. It is a bit perl-y but works like a charm. Note also that the output is now a list of unicode strings, you didn't specify that you needed that, but it seems to make sense given unicode input.

import re
x = u'[ "A","B","C" , " D"]'
junkers = re.compile('[[" \]]')
result = junkers.sub('', x).split(',')
print result
--->  [u'A', u'B', u'C', u'D']

The junkers variable contains a compiled regexp (for speed) of all characters we don't want, using ] as a character required some backslash trickery. The re.sub replaces all these characters with nothing, and we split the resulting string at the commas.

Note that this also removes spaces from inside entries u'["oh no"]' ---> [u'ohno']. If this is not what you wanted, the regexp needs to be souped up a bit.

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

The solutions posted so far only deal with part of the problem, converting DOS/Windows' CRLF into Unix's LF; the part they're missing is that DOS use CRLF as a line separator, while Unix uses LF as a line terminator. The difference is that a DOS file (usually) won't have anything after the last line in the file, while Unix will. To do the conversion properly, you need to add that final LF (unless the file is zero-length, i.e. has no lines in it at all). My favorite incantation for this (with a little added logic to handle Mac-style CR-separated files, and not molest files that're already in unix format) is a bit of perl:

perl -pe 'if ( s/\r\n?/\n/g ) { $f=1 }; if ( $f || ! $m ) { s/([^\n])\z/$1\n/ }; $m=1' PCfile.txt

Note that this sends the Unixified version of the file to stdout. If you want to replace the file with a Unixified version, add perl's -i flag.

Format an Excel column (or cell) as Text in C#?

Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

Disclaimer: I own SpreadsheetGear LLC

Expression ___ has changed after it was checked

For this I have tried above answers many does not work in latest version of Angular (6 or later)

I am using Material control that required changes after first binding done.

    export class AbcClass implements OnInit, AfterContentChecked{
        constructor(private ref: ChangeDetectorRef) {}
        ngOnInit(){
            // your tasks
        }
        ngAfterContentChecked() {
            this.ref.detectChanges();
        }
    }

Adding my answer so, this helps some solve specific issue.

How can I concatenate a string and a number in Python?

do it like this:

"abc%s" % 9
#or
"abc" + str(9)

List of remotes for a Git repository?

The answers so far tell you how to find existing branches:

git branch -r

Or repositories for the same project [see note below]:

git remote -v

There is another case. You might want to know about other project repositories hosted on the same server.

To discover that information, I use SSH or PuTTY to log into to host and ls to find the directories containing the other repositories. For example, if I cloned a repository by typing:

git clone ssh://git.mycompany.com/git/ABCProject

and want to know what else is available, I log into git.mycompany.com via SSH or PuTTY and type:

ls /git

assuming ls says:

 ABCProject DEFProject

I can use the command

 git clone ssh://git.mycompany.com/git/DEFProject

to gain access to the other project.

NOTE: Usually git remote simply tells me about origin -- the repository from which I cloned the project. git remote would be handy if you were collaborating with two or more people working on the same project and accessing each other's repositories directly rather than passing everything through origin.

What is a PDB file?

A PDB file contains information for the debugger to work with. There's less information in a Release build than in a Debug build anyway. But if you want it to not be generated at all, go to your project's Build properties, select the Release configuration, click on "Advanced..." and under "Debug Info" pick "None".

Add a user control to a wpf window

You probably need to add the namespace:

<Window x:Class="UserControlTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:UserControlTest"
    Title="User Control Test" Height="300" Width="300">
    <local:UserControl1 />
</Window>

How to distinguish mouse "click" and "drag"

Cleaner ES2015

_x000D_
_x000D_
let drag = false;_x000D_
_x000D_
document.addEventListener('mousedown', () => drag = false);_x000D_
document.addEventListener('mousemove', () => drag = true);_x000D_
document.addEventListener('mouseup', () => console.log(drag ? 'drag' : 'click'));
_x000D_
_x000D_
_x000D_

Didn't experience any bugs, as others comment.

What is the difference between Integer and int in Java?

int is a primitive type that represent an integer. whereas Integer is an Object that wraps int. The Integer object gives you more functionality, such as converting to hex, string, etc.

You can also use OOP concepts with Integer. For example, you can use Integer for generics (i.e. Collection<Integer>).

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

I wonder if this question has been answered well: how css margins work and why is it that margin-top:-5; is not the same as margin-bottom:5;?

Margin is distance from the surroundings of the element. margin-top says "... distance from surroundings as we measure from top 'side' of the element's 'box' and margin-bottom being the distance from the bottom 'side' of the 'box'". Then margin-top:5; is concerned with the top 'side' perimeter,-5 in that case; anything approaching from top 'side' can overlap top 'side' of element by 5, and margin-bottom:5; means distance between element bottom 'side' and surrounding is 5.

Basically that but affected by float'ed elements and the like: http://www.w3.org/TR/CSS2/box.html#margin-properties.

http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide-to-using-negative-margins/

I stand to be corrected.

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

Just my two cents for future visitors who have this problem.

This is the correct syntax for PHP 5.3, for example if you call static method from the class name:

MyClassName::getConfig($key);

If you previously assign the ClassName to the $cnf variable, you can call the static method from it (we are talking about PHP 5.3):

$cnf = MyClassName;
$cnf::getConfig($key);

However, this sintax doesn't work on PHP 5.2 or lower, and you need to use the following:

$cnf = MyClassName;
call_user_func(array($cnf, "getConfig", $key, ...otherposibleadditionalparameters... ));

Hope this helps people having this error in 5.2 version (don't know if this was openfrog's version).

HTTP 415 unsupported media type error when calling Web API 2 endpoint

In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto) to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto) and its working.

How to print struct variables in console?

my 2cents would be to use json.MarshalIndent -- surprised this isn't suggested, as it is the most straightforward. for example:

func prettyPrint(i interface{}) string {
    s, _ := json.MarshalIndent(i, "", "\t")
    return string(s)
}

no external deps and results in nicely formatted output.

How do I detect when someone shakes an iPhone?

A swiftease version based on the very first answer!

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
    if ( event?.subtype == .motionShake )
    {
        print("stop shaking me!")
    }
}

Binding an Image in WPF MVVM

@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.

As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..

    public string DisplayedImagePath
    {
        get { return @"~\..\images\osc.png"; }
    }

This was tested, see below my Solution Explorer in VS2015..

example of image binding in VS2015)

Note: if you want a Click event, use the Button tag around the image,

_x000D_
_x000D_
<Button Click="image_Click" Width="128" Height="128"  Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
  <Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
_x000D_
_x000D_

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

It appears that my max ports weren't configured correctly. I ran the following code and it worked...

echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

What this command does is to increase the number of watches allowed for a single user. By the default the number can be low (8192 for example). When nodemon tries to watch large numbers of directories for changes it has to create several watches, which can surpass that limit.

You could also solve this problem by:

sudo sysctl fs.inotify.max_user_watches=582222 && sudo sysctl -p

But the way it was written first will make this change permanent.

React / JSX Dynamic Component Name

There is an official documentation about how to handle such situations is available here: https://facebook.github.io/react/docs/jsx-in-depth.html#choosing-the-type-at-runtime

Basically it says:

Wrong:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
    photo: PhotoStory,
    video: VideoStory
};

function Story(props) {
    // Wrong! JSX type can't be an expression.
    return <components[props.storyType] story={props.story} />;
}

Correct:

import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
    photo: PhotoStory,
    video: VideoStory
};

function Story(props) {
    // Correct! JSX type can be a capitalized variable.
    const SpecificStory = components[props.storyType];
    return <SpecificStory story={props.story} />;
}

Do I really need to encode '&' as '&amp;'?

The link has a fairly good example of when and why you may need to escape & to &amp;

https://jsfiddle.net/vh2h7usk/1/

Interestingly, I had to escape the character in order to represent it properly in my answer here. If I were to use the built-in code sample option (from the answer panel), I can just type in &amp; and it appears as it should. But if I were to manually use the <code></code> element, then I have to escape in order to represent it correctly :)

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

Getting all types that implement an interface

Edit: I've just seen the edit to clarify that the original question was for the reduction of iterations / code and that's all well and good as an exercise, but in real-world situations you're going to want the fastest implementation, regardless of how cool the underlying LINQ looks.

Here's my Utils method for iterating through the loaded types. It handles regular classes as well as interfaces, and the excludeSystemTypes option speeds things up hugely if you are looking for implementations in your own / third-party codebase.

public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {
    List<Type> list = new List<Type>();
    IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();
    while (enumerator.MoveNext()) {
        try {
            Type[] types = ((Assembly) enumerator.Current).GetTypes();
            if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith("System."))) {
                IEnumerator enumerator2 = types.GetEnumerator();
                while (enumerator2.MoveNext()) {
                    Type current = (Type) enumerator2.Current;
                    if (type.IsInterface) {
                        if (current.GetInterface(type.FullName) != null) {
                            list.Add(current);
                        }
                    } else if (current.IsSubclassOf(type)) {
                        list.Add(current);
                    }
                }
            }
        } catch {
        }
    }
    return list;
}

It's not pretty, I'll admit.

How to easily duplicate a Windows Form in Visual Studio?

Secured way without problems is to make Template of your form You can use it in the same project or any other project. and you can add it very easily, such as adding a new form . Here's a way how make Template

1- from File Menu click Export Template

2- Choose Template Type (Choose item template ) and click next

3-Check Form that you want to make a template of it, and click next Twice

4-Rename your template and (put describe , choose icon image ,preview image if you want)

5-click finish

Now you can add new item and choose your template in any project

Mipmap drawables for icons

When building separate apks for different densities, drawable folders for other densities get stripped. This will make the icons appear blurry in devices that use launcher icons of higher density. Since, mipmap folders do not get stripped, it’s always best to use them for including the launcher icons.

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

Good ways to sort a queryset? - Django

Here's a way that allows for ties for the cut-off score.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.

How to make readonly all inputs in some div in Angular2?

If you want to do a whole group, not just one field at a time, you can use the HTML5 <fieldset> tag.

<fieldset [disabled]="killfields ? 'disabled' : null">

    <!-- fields go here -->

</fieldset>

How to find specific lines in a table using Selenium?

(.//*[table-locator])[n]

where n represents the specific line.

How to change maven java home

Even if you install the Oracle JDK, your $JAVA_HOME variable should refer to the path of the JRE that is inside the JDK root. You can refer to my other answer to a similar question for more details.

Remove all html tags from php string

<?php $data = "<div><p>Welcome to my PHP class, we are glad you are here</p></div>"; echo strip_tags($data); ?>

Or if you have a content coming from the database;

<?php $data = strip_tags($get_row['description']); ?> <?=substr($data, 0, 100) ?><?php if(strlen($data) > 100) { ?>...<?php } ?>

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Filter values only if not null using lambda in Java8

You just need to filter the cars that have a null name:

requiredCars = cars.stream()
                   .filter(c -> c.getName() != null)
                   .filter(c -> c.getName().startsWith("M"));

How to use OrderBy with findAll in Spring Data

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public List<StudentEntity> findAllByOrderByIdAsc();
}

The code above should work. I'm using something similar:

public List<Pilot> findTop10ByOrderByLevelDesc();

It returns 10 rows with the highest level.

IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:

findAllByOrderByIdAsc(); // don't miss "by"
       ^

Input type DateTime - Value format?

That one shows up correctly as HTML5-Tag for those looking for this:

<input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

It may sound banal, but for me Build > Clean Project fixed this error without any other changes.

How to remove all ListBox items?

isn't the same as the Winform and Webform way?

listBox1.Items.Clear();

How to format background color using twitter bootstrap?

Move your row before <div class="container marketing"> and wrap it with a new container, because current container width is 1170px (not 100%):

<div class='hero'>
  <div class="row">
   ...
  </div>
</div>

CSS:

.hero {
  background-color: #2ba6cb;
  padding: 0 90px;
}

How to set selected value from Combobox?

Try this one.

cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);

Hope that helps. :)

Algorithm/Data Structure Design Interview Questions

When interviewing recently, I was often asked to implement a data structure, usually LinkedList or HashMap. Both of these are easy enough to be doable in a short time, and difficult enough to eliminate the clueless.

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

matplotlib: how to draw a rectangle on image

You need use patches.

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')

ax2.add_patch(
     patches.Rectangle(
        (0.1, 0.1),
        0.5,
        0.5,
        fill=False      # remove background
     ) ) 
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

What is the difference between HAVING and WHERE in SQL?

WHERE is applied as a limitation on the set returned by SQL; it uses SQL's built-in set oeprations and indexes and therefore is the fastest way to filter result sets. Always use WHERE whenever possible.

HAVING is necessary for some aggregate filters. It filters the query AFTER sql has retrieved, assembled, and sorted the results. Therefore, it is much slower than WHERE and should be avoided except in those situations that require it.

SQL Server will let you get away with using HAVING even when WHERE would be much faster. Don't do it.

JavaScript, Node.js: is Array.forEach asynchronous?

It is possible to code even the solution like this for example :

 var loop = function(i, data, callback) {
    if (i < data.length) {
        //TODO("SELECT * FROM stackoverflowUsers;", function(res) {
            //data[i].meta = res;
            console.log(i, data[i].title);
            return loop(i+1, data, errors, callback);
        //});
    } else {
       return callback(data);
    }
};

loop(0, [{"title": "hello"}, {"title": "world"}], function(data) {
    console.log("DONE\n"+data);
});

On the other hand, it is much slower than a "for".

Otherwise, the excellent Async library can do this: https://caolan.github.io/async/docs.html#each

mat-form-field must contain a MatFormFieldControl

This can also happen if you have a proper input within a mat-form-field, but it has a ngIf on it. E.g.:

<mat-form-field>
    <mat-chip-list *ngIf="!_dataLoading">
        <!-- other content here -->
    </mat-chip-list>
</mat-form-field>

In my case, mat-chip-list is supposed to "appear" only after its data is loaded. However, the validation is performed and mat-form-field complains with

mat-form-field must contain a MatFormFieldControl

To fix it, the control must be there, so I have used [hidden]:

<mat-form-field>
    <mat-chip-list [hidden]="_dataLoading">
        <!-- other content here -->
    </mat-chip-list>
</mat-form-field>

An alternative solution is proposed by Mosta: move *ngIf for mat-form-field:

<mat-form-field *ngIf="!_dataLoading">
    <mat-chip-list >
        <!-- other content here -->
    </mat-chip-list>
</mat-form-field>

ls command: how can I get a recursive full-path listing, one line per file?

I knew the file name but wanted the directory as well.

find $PWD | fgrep filename

worked perfectly in Mac OS 10.12.1

using favicon with css

There is no explicit way to change the favicon globally using CSS that I know of. But you can use a simple trick to change it on the fly.

First just name, or rename, the favicon to "favicon.ico" or something similar that will be easy to remember, or is relevant for the site you're working on. Then add the link to the favicon in the head as you usually would. Then when you drop in a new favicon just make sure it's in the same directory as the old one, and that it has the same name, and there you go!

It's not a very elegant solution, and it requires some effort. But dropping in a new favicon in one place is far easier than doing a find and replace of all the links, or worse, changing them manually. At least this way doesn't involve messing with the code.

Of course dropping in a new favicon with the same name will delete the old one, so make sure to backup the old favicon in case of disaster, or if you ever want to go back to the old design.

Importing lodash into angular2 + typescript application

If anyone else runs into this issue and none of the above solutions work due to "Duplicate identifier" issues, run this:

npm install typings --global

With older versions of typings things mess up and you'll get a bunch of "Duplicate identifier" issues. Also you don't need to use --ambient anymore as far as I could tell.

So once typings is up to date, this should work (using the Angular 2 quickstart).

Run:

npm install lodash --save 
typings install lodash --save

First, add this to systemjs.config.js:

'lodash':                     'node_modules/lodash/lodash.js'

Now you can use this in any file: import * as _ from 'lodash';

Delete your typings folder and run npm install if you're still having issues.

jQuery access input hidden value

If you want to select an individual hidden field, you can select it through the different selectors of jQuery :

<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/> 


$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class

Basic Python client socket example

You might be confusing compilation from execution. Python has no compilation step! :) As soon as you type python myprogram.py the program runs and, in your case, tries to connect to an open port 5000, giving an error if no server program is listening there. It sounds like you are familiar with two-step languages, that require compilation to produce an executable — and thus you are confusing Python's runtime compilaint that “I can't find anyone listening on port 5000!” with a compile-time error. But, in fact, your Python code is fine; you just need to bring up a listener before running it!

How to zoom div content using jquery?

 $('image').animate({ 'zoom': 1}, 400);

Generating Unique Random Numbers in Java

This is the most simple method to generate unique random values in a range or from an array.

In this example, I will be using a predefined array but you can adapt this method to generate random numbers as well. First, we will create a sample array to retrieve our data from.

  1. Generate a random number and add it to the new array.
  2. Generate another random number and check if it is already stored in the new array.
  3. If not then add it and continue
  4. else reiterate the step.
ArrayList<Integer> sampleList = new ArrayList<>();
sampleList.add(1);
sampleList.add(2);
sampleList.add(3);
sampleList.add(4);
sampleList.add(5);
sampleList.add(6);
sampleList.add(7);
sampleList.add(8);

Now from the sampleList we will produce five random numbers that are unique.

int n;
randomList = new ArrayList<>();
for(int  i=0;i<5;i++){
    Random random = new Random();
    n=random.nextInt(8);     //Generate a random index between 0-7

    if(!randomList.contains(sampleList.get(n)))
    randomList.add(sampleList.get(n));
    else
        i--;    //reiterating the step
}
        

This is conceptually very simple. If the random value generated already exists then we will reiterate the step. This will continue until all the values generated are unique.

If you found this answer useful then you can vote it up as it is much simple in concept as compared to the other answers.

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

It's actually a simple answer.

Your function is returning a string rather than the div node. appendChild can only append a node.

For example, if you try to appendChild the string:

var z = '<p>test satu dua tiga</p>'; // is a string 
document.body.appendChild(z);

The above code will never work. What will work is:

var z = document.createElement('p'); // is a node
z.innerHTML = 'test satu dua tiga';
document.body.appendChild(z);

Close Bootstrap Modal

this worked for me:

<span class="button" data-dismiss="modal" aria-label="Close">cancel</span>

use this link modal close

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

CSS submit button weird rendering on iPad/iPhone

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

   -webkit-appearance: none;

Who sets response content-type in Spring MVC (@ResponseBody)

Note that in Spring MVC 3.1 you can use the MVC namespace to configure message converters:

<mvc:annotation-driven>
  <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

Or code-based configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  private static final Charset UTF8 = Charset.forName("UTF-8");

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
    stringConverter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain", UTF8)));
    converters.add(stringConverter);

    // Add other converters ...
  }
}

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Please use test flight to obtain UDID from testers but not using untrusted source e.g. http://get.udid.io/

You can 1. Invite testers in email from test flight webpage. Testers open the link in email and install a profile from test flight. Therefore developers can obtain UDIDs on the test flight webpage. 2. Add those UDIDs on the Apple provisioning portal.

(Ref: http://help.testflightapp.com/customer/portal/articles/829537-how-does-it-work-)

The process doesn't require testers to use Mac/ PC to obtain UDID (more convenient). And I think test flight is a company that can be trusted (no worries when passing UDID to this company).

I have tested this method and it works on iOS 8.

Visual Studio - How to change a project's folder name and solution name without breaking the solution

I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.

Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.

How can I fill a div with an image while keeping it proportional?

You can achieve this using css flex properties. Please see the code below

_x000D_
_x000D_
.img-container {_x000D_
  border: 2px solid red;_x000D_
  justify-content: center;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  overflow: hidden;_x000D_
  _x000D_
}_x000D_
.img-container .img-to-fit {_x000D_
  flex: 1;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="img-container">_x000D_
  <img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I had a .NET 4.0, ASP.NET MVC 2.0, Entity Framework 4.0 web application developed in Visual Studio 2010. I had the same problem, that it worked on one Windows Server 2008 R2 server but not on another Windows Server 2008 R2 server, even though the versions of .NET and ASP.NET MVC were the same, throwing this same error as yours.

I went to follow miko's suggestion, so I installed Windows SDK v7.1 (x64) on the failing server, so I could run !dumpheap.

Well, it turns out that installing Windows SDK v7.1 (x64) resolved the issue. Whatever dependency was missing must have been included in the SDK. It can be downloaded from Microsoft Windows SDK for Windows 7 and .NET Framework 4.

Calculate distance between two latitude-longitude points? (Haversine formula)

If you want the driving distance/route (posting it here because this is the first result for the distance between two points on google but for most people the driving distance is more useful), you can use Google Maps Distance Matrix Service:

getDrivingDistanceBetweenTwoLatLong(origin, destination) {

 return new Observable(subscriber => {
  let service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [new google.maps.LatLng(origin.lat, origin.long)],
      destinations: [new google.maps.LatLng(destination.lat, destination.long)],
      travelMode: 'DRIVING'
    }, (response, status) => {
      if (status !== google.maps.DistanceMatrixStatus.OK) {
        console.log('Error:', status);
        subscriber.error({error: status, status: status});
      } else {
        console.log(response);
        try {
          let valueInMeters = response.rows[0].elements[0].distance.value;
          let valueInKms = valueInMeters / 1000;
          subscriber.next(valueInKms);
          subscriber.complete();
        }
       catch(error) {
        subscriber.error({error: error, status: status});
       }
      }
    });
});
}

How to check String in response body with mockMvc

Spring MockMvc now has direct support for JSON. So you just say:

.andExpect(content().json("{'message':'ok'}"));

and unlike string comparison, it will say something like "missing field xyz" or "message Expected 'ok' got 'nok'.

This method was introduced in Spring 4.1.

Multi value Dictionary

Just create a Pair<TFirst, TSecond> type and use that as your value.

I have an example of one in my C# in Depth source code. Reproduced here for simplicity:

using System;
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond>
    : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first;
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second)
    {
        this.first = first;
        this.second = second;
    }

    public TFirst First
    {
        get { return first; }
    }

    public TSecond Second
    {
        get { return second; }
    }

    public bool Equals(Pair<TFirst, TSecond> other)
    {
        if (other == null)
        {
            return false;
        }
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
               EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

    public override bool Equals(object o)
    {
        return Equals(o as Pair<TFirst, TSecond>);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
               EqualityComparer<TSecond>.Default.GetHashCode(second);
    }
}

How to run crontab job every week on Sunday

Following is the format of the crontab file.

{minute} {hour} {day-of-month} {month} {day-of-week} {user} {path-to-shell-script}

So, to run each sunday at midnight (Sunday is 0 usually, 7 in some rare cases) :

0 0 * * 0 root /path_to_command

Importing json file in TypeScript

It's easy to use typescript version 2.9+. So you can easily import JSON files as @kentor decribed.

But if you need to use older versions:

You can access JSON files in more TypeScript way. First, make sure your new typings.d.ts location is the same as with the include property in your tsconfig.json file.

If you don't have an include property in your tsconfig.json file. Then your folder structure should be like that:

- app.ts
+ node_modules/
- package.json
- tsconfig.json
- typings.d.ts

But if you have an include property in your tsconfig.json:

{
    "compilerOptions": {
    },
    "exclude"        : [
        "node_modules",
        "**/*spec.ts"
    ], "include"        : [
        "src/**/*"
    ]
}

Then your typings.d.ts should be in the src directory as described in include property

+ node_modules/
- package.json
- tsconfig.json
- src/
    - app.ts
    - typings.d.ts

As In many of the response, You can define a global declaration for all your JSON files.

declare module '*.json' {
    const value: any;
    export default value;
}

but I prefer a more typed version of this. For instance, let's say you have configuration file config.json like that:

{
    "address": "127.0.0.1",
    "port"   : 8080
}

Then we can declare a specific type for it:

declare module 'config.json' {
    export const address: string;
    export const port: number;
}

It's easy to import in your typescript files:

import * as Config from 'config.json';

export class SomeClass {
    public someMethod: void {
        console.log(Config.address);
        console.log(Config.port);
    }
}

But in compilation phase, you should copy JSON files to your dist folder manually. I just add a script property to my package.json configuration:

{
    "name"   : "some project",
    "scripts": {
        "build": "rm -rf dist && tsc && cp src/config.json dist/"
    }
}

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

if it is standalone program, download mysql connector jar and add it to your classpath.

if it is a maven project, add below dependency and run your program.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
</dependency>

how to check if object already exists in a list

Simply use Contains method. Note that it works based on the equality function Equals

bool alreadyExist = list.Contains(item);

How to maintain state after a page refresh in React.js?

We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.

When the user selects an option, we can push the value of that onto the current route with:

history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});

pathname can be the current path. In your case params would look something like:

{
  selectedOption: 5
}

Then at the top level of the React tree, React Router will update the props of that component with a prop of location.search which is the encoded value we set earlier, so there will be something in componentWillReceiveProps like:

params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});

Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.

React Router: https://github.com/reactjs/react-router

History: https://github.com/ReactTraining/history

The query string library: https://github.com/ljharb/qs

Android device chooser - My device seems offline

I had the same problem with my Galaxy S4, when connected to a Win 7 64 machine, not showing up as an available device in Eclipse. Tried rebooting phone, starting/restarting adb, switching from usb 3 to usb 2 port... none of which helped. Downloaded Samsung drivers from here: http://www.samsung.com/us/support/owners/product/SGH-I337ZWAATT

installed drivers and then when I reconnected my phone, windows installed the new drivers (took a min or so). I then restarted Eclipse and was able to see the phone and run the app.

I also tried this with the usb 3 port and it works as well.

Microsoft.ACE.OLEDB.12.0 provider is not registered

Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.

GoTo Next Iteration in For Loop in java

As mentioned in all other answers, the keyword continue will skip to the end of the current iteration.

Additionally you can label your loop starts and then use continue [labelname]; or break [labelname]; to control what's going on in nested loops:

loop1: for (int i = 1; i < 10; i++) {
    loop2: for (int j = 1; j < 10; j++) {
        if (i + j == 10)
            continue loop1;

        System.out.print(j);
    }
    System.out.println();
}

Eclipse CDT: no rule to make target all

I just solved this exact issue for myself; even referenced this question.

I'm assuming you haven't written the "all" rule that Eclipse is complaining about. If this is the case, take these steps:

  1. Go to Project Properties > C/C++ Build > Behaviour Tab.
  2. Leave Build (Incremental Build) Checked.
  3. Remove "all" from the text box next to Build (Incremental Build).
  4. Compile away!

This lets Eclipse know you aren't trying to use a make target called "all". For some reason, that is the default.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

My case, the server was encrypting with padding disabled. But the client was trying to decrypt with the padding enabled.

While using EVP_CIPHER*, by default the padding is enabled. To disable explicitly we need to do

EVP_CIPHER_CTX_set_padding(context, 0);

So non matching padding options can be one reason.

PHP date() with timezone?

this works perfectly in 2019:

date('Y-m-d H:i:s',strtotime($date. ' '.$timezone)); 

Java LinkedHashMap get first or last entry

For first element use entrySet().iterator().next() and stop iterating after 1 iteration. For last one the easiest way is to preserve the key in a variable whenever you do a map.put.

How to check whether a Storage item is set?

Best and Safest way i can suggest is this,

if(Object.prototype.hasOwnProperty.call(localStorage, 'infiniteScrollEnabled')){
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

This passes through ESLint's no-prototype-builtins rule.

jquery drop down menu closing by clicking outside

Stopping Event Propagation in some particular elements ma y become dangerous as it may prevent other some scripts from running. So check whether the triggering is from the excluded area from inside the function.

$(document).on('click', function(event) {
  if (!$(event.target).closest('#menucontainer').length) {
    // Hide the menus.
  }
});

Here function is initiated when clicking on document, but it excludes triggering from #menucontainer. For details https://css-tricks.com/dangers-stopping-event-propagation/

Returning a value from callback function in Node.js

If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:

Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.

Basically, you can do something like this:

function doCall(urlToCall) {
  return co(function *(){
    var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.                             
    var statusCode = response.statusCode;
    finalData = getResponseJson(statusCode, data.toString());
    return finalData;
  });
}

Then,

var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.

By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.

Force Internet Explorer to use a specific Java Runtime Environment install?

I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.

I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.

This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.

Programmatically change the height and width of a UIImageView Xcode Swift

imageView is a subview of the main view. It works this way

image.frame = CGRectMake(0 , 0, super.view.frame.width, super.view.frame.height * 0.2)

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Adding an .env file to React Project

  1. Install dotenv as devDependencies:
npm i --save-dev dotenv
  1. Create a .env file in the root directory:
my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
  1. Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name.
REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
  1. [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file.

For example, I've create a file named base.js and update it like below:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:
process.env.REACT_APP_BASE_URL

How to create own dynamic type or dynamic object in C#?

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

How do I check if a number is a palindrome?

For any given number:

n = num;
rev = 0;
while (num > 0)
{
    dig = num % 10;
    rev = rev * 10 + dig;
    num = num / 10;
}

If n == rev then num is a palindrome:

cout << "Number " << (n == rev ? "IS" : "IS NOT") << " a palindrome" << endl;

How to Truncate a string in PHP to the word closest to a certain number of characters?

I have a function that does almost what you want, if you'll do a few edits, it will fit exactly:

<?php
function stripByWords($string,$length,$delimiter = '<br>') {
    $words_array = explode(" ",$string);
    $strlen = 0;
    $return = '';
    foreach($words_array as $word) {
        $strlen += mb_strlen($word,'utf8');
        $return .= $word." ";
        if($strlen >= $length) {
            $strlen = 0;
            $return .= $delimiter;
        }
    }
    return $return;
}
?>

How do I convert a Swift Array to a String?

FOR SWIFT 3:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == phoneField
    {
        let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
        let components = newString.components(separatedBy: NSCharacterSet.decimalDigits.inverted)

        let decimalString = NSString(string: components.joined(separator: ""))
        let length = decimalString.length
        let hasLeadingOne = length > 0 && decimalString.character(at: 0) == (1 as unichar)

        if length == 0 || (length > 10 && !hasLeadingOne) || length > 11
        {
            let newLength = NSString(string: textField.text!).length + (string as NSString).length - range.length as Int

            return (newLength > 10) ? false : true
        }
        var index = 0 as Int
        let formattedString = NSMutableString()

        if hasLeadingOne
        {
            formattedString.append("1 ")
            index += 1
        }
        if (length - index) > 3
        {
            let areaCode = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("(%@)", areaCode)
            index += 3
        }
        if length - index > 3
        {
            let prefix = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("%@-", prefix)
            index += 3
        }

        let remainder = decimalString.substring(from: index)
        formattedString.append(remainder)
        textField.text = formattedString as String
        return false
    }
    else
    {
        return true
    }
}

Giving graphs a subtitle in matplotlib

What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different fontsize arguments). Hope that helps!

Subtract two dates in SQL and get days of the result

Use DATEDIFF

Select I.Fee
From Item I
WHERE  DATEDIFF(day, GETDATE(), I.DateCreated) < 365

C# string does not contain possible?

So you can utilize short-circuiting:

bool containsBoth = compareString.Contains(firstString) && 
                    compareString.Contains(secondString);

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

Rename a file in C#

Move is doing the same = copy and delete old one.

File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf", DateTime.Now));

Casting LinkedHashMap to Complex Object

I had similar Issue where we have GenericResponse object containing list of values

 ResponseEntity<ResponseDTO> responseEntity = restTemplate.exchange(
                redisMatchedDriverUrl,
                HttpMethod.POST,
                requestEntity,
                ResponseDTO.class
        );

Usage of objectMapper helped in converting LinkedHashMap into respective DTO objects

 ObjectMapper mapper = new ObjectMapper();

 List<DriverLocationDTO> driverlocationsList = mapper.convertValue(responseDTO.getData(), new TypeReference<List<DriverLocationDTO>>() { });

How to convert a byte array to its numeric value (Java)?

Each cell in the array is treated as unsigned int:

private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
    return res;


for (int i=0;i<bytes.length;i++){
    res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}

Add content to a new open window

When You want to open new tab/window (depends on Your browser configuration defaults):

output = 'Hello, World!';
window.open().document.write(output);

When output is an Object and You want get JSON, for example (also can generate any type of document, even image encoded in Base64)

output = ({a:1,b:'2'});
window.open('data:application/json;' + (window.btoa?'base64,'+btoa(JSON.stringify(output)):JSON.stringify(output)));

Update

Google Chrome (60.0.3112.90) block this code:

Not allowed to navigate top frame to data URL: data:application/json;base64,eyJhIjoxLCJiIjoiMiJ9

When You want to append some data to existing page

output = '<h1>Hello, World!</h1>';
window.open('output.html').document.body.innerHTML += output;

output = 'Hello, World!';
window.open('about:blank').document.body.innerText += output;

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

Pass a javascript variable value into input type hidden value

<script type="text/javascript">
  function product(x,y)
  {
   return x*y;
  }
 document.getElementById('myvalue').value = product(x,y);
 </script>

 <input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}

Unix epoch time to Java Date object

How about just:

Date expiry = new Date(Long.parseLong(date));

EDIT: as per rde6173's answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:

Date expiry = new Date(Long.parseLong(date) * 1000);

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

How do I concatenate two arrays in C#?

Try this:

List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();

Converting java.sql.Date to java.util.Date

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");

Apache SSL Configuration Error (SSL Connection Error)

I got this problem and the solution was a bit silly.

I am using Cloudflare which acts as a proxy to my website. In order to be able to login via SSH, I added an entry to my /etc/hosts file so I didn't need to remember my server's IP address.

xxx.xx.xx.xxx  example.com

So in my browser when I went to https://www.example.com, I was using the Cloudflare proxy, and when I went to to https://example.com I was going directly to the server. Because the Cloudflare setup doesn't require you to add the intermediate certificates, I was seeing this security exception in my browser when I went to https://example.com, but https://www.example.com was working.

The solution: remove the entry from my laptop's /etc/hosts file.

If this isn't your problem, I recommend using one of the many online SSL checker tools to try diagnose your problem.

I also recommend using ping to check the IP address being reported and check it against the IP address expected.

ping https://www.example.com/

Another very helpful SSL resource is the Mozilla SSL Configuration Generator. It can generate SSL configuration for you.

How to change the project in GCP using CLI commands

You can try: gcloud config set project [project_id]

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

Jquery Chosen plugin - dynamically populate list by Ajax

The chosen answer is outdated, same goes to meltingice /ajax-chosen plugin.

With Select2 plugin got many bugs which is i can't resolve it.

Here my answer for this question.

I integrated my solution with function trigger after user type. Thanks to this answer : https://stackoverflow.com/a/5926782/4319179.

//setup before functions
  var typingTimer;                //timer identifier
  var doneTypingInterval = 2000;  //time in ms (2 seconds)
  var selectID = 'YourSelectId';    //Hold select id
  var selectData = [];           // data for unique id array

  //on keyup, start the countdown
  $('#' + selectID + '_chosen .chosen-choices input').keyup(function(){

      // Change No Result Match text to Searching.
      $('#' + selectID + '_chosen .no-results').html('Searching = "'+ $('#' + selectID + '_chosen .chosen-choices input').val() + '"');


      clearTimeout(typingTimer);  //Refresh Timer on keyup 
      if ($('#' + selectID + '_chosen .chosen-choices input').val()) {

           typingTimer = setTimeout(doneTyping, doneTypingInterval);  //Set timer back if got value on input

      }

  });

  //user is "finished typing," do something
  function doneTyping () {

      var inputData = $('#' + selectID + '_chosen .chosen-choices input').val();  //get input data

      $.ajax({
        url: "YourUrl",
         data: {data: inputData},
        type:'POST',
        dataType: "json",
        beforeSend: function(){
          // Change No Result Match to Getting Data beforesend
          $('#' + selectID + '_chosen .no-results').html('Getting Data = "'+$('#' + selectID + '_chosen .chosen-choices input').val()+'"');
    },
        success: function( data ) { 

          // iterate data before append
          $.map( data, function( item ) {

            // matching data eg: by id or something unique; if data match: <option> not append - else: append <option>
            // This will prevent from select the same thing twice.
            if($.inArray(item.attr_hash,selectData) == -1){

              // if not match then append in select
              $('#' + selectID ).append('<option id="'+item.id+'" data-id = "'+item.id+'">' + item.data + '</option>');

            }            

          });

          // Update chosen again after append <option>
          $('#' + selectID ).trigger("chosen:updated");

        }
      });

  }

  // Chosen event listen on input change eg: after select data / deselect this function will be trigger
  $('#' + selectID ).on('change', function() {

    // get select jquery object
    var domArray = $('#' + selectID ).find('option:selected');

    // empty array data
    selectData = [];

    for (var i = 0, length = domArray.length; i < length; i++ ){

      // Push unique data to array (for matching purpose)
      selectData.push( $(domArray[i]).data('id') );

    }

    // Replace select <option> to only selected option
    $('#' + selectID ).html(domArray);

    // Update chosen again after replace selected <option>
    $('#' + selectID ).trigger("chosen:updated");

  });

Why do you have to link the math library in C?

There's a thorough discussion of linking to external libraries in An Introduction to GCC - Linking with external libraries. If a library is a member of the standard libraries (like stdio), then you don't need to specify to the compiler (really the linker) to link them.

EDIT: After reading some of the other answers and comments, I think the libc.a reference and the libm reference that it links to both have a lot to say about why the two are separate.

Note that many of the functions in 'libm.a' (the math library) are defined in 'math.h' but are not present in libc.a. Some are, which may get confusing, but the rule of thumb is this--the C library contains those functions that ANSI dictates must exist, so that you don't need the -lm if you only use ANSI functions. In contrast, `libm.a' contains more functions and supports additional functionality such as the matherr call-back and compliance to several alternative standards of behavior in case of FP errors. See section libm, for more details.

How to quickly clear a JavaScript Object?

The short answer to your question, I think, is no (you can just create a new object).

  1. In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.

  2. You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.

  3. This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.

Feel free to correct me if there's anything incorrect above.

Is it possible to use argsort in descending order?

Instead of using np.argsort you could use np.argpartition - if you only need the indices of the lowest/highest n elements.

That doesn't require to sort the whole array but just the part that you need but note that the "order inside your partition" is undefined, so while it gives the correct indices they might not be correctly ordered:

>>> avgDists = [1, 8, 6, 9, 4]
>>> np.array(avgDists).argpartition(2)[:2]  # indices of lowest 2 items
array([0, 4], dtype=int64)

>>> np.array(avgDists).argpartition(-2)[-2:]  # indices of highest 2 items
array([1, 3], dtype=int64)

SSRS Query execution failed for dataset

I also had a very similar issue with a very similar error message. My issue was that the database could not be connected to. In our case, we have mirrored databases and the connection string did not specify the Failover Partner. So when the database couldn't connect, it never went to the mirror and was throwing this error. Once I specified the Failover Partner in the connection string for my datasource, it resolved the issue.

What is causing "Unable to allocate memory for pool" in PHP?

I received the error "Unable to allocate memory for pool" after moving an OpenCart installation to a different server. I also tried raising the memory_limit.

The error stopped after I changed the permissions of the file in the error message to have write access by the user that apache runs as (apache, www-data, etc.). Instead of modifying /etc/group directly (or chmod-ing the files to 0777), I used usermod:

usermod -a -G vhost-user-group apache-user

Then I had to restart apache for the change to take effect:

apachectl restart

Or

sudo /etc/init.d/httpd restart

Or whatever your system uses to restart apache.

If the site is on shared hosting, maybe you must change the file permissions with an FTP program, or contact the hosting provider?

set column width of a gridview in asp.net

This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.

    <asp:TemplateField   HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
    <asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate> 
 <EditItemTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate> 
<FooterTemplate>
    <asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>

node.js Error: connect ECONNREFUSED; response from server

i ran the local mysql database, but not in administrator mode, which threw this error

Format numbers to strings in Python

str() in python on an integer will not print any decimal places.

If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).

Perhaps the following code will demonstrate:

>>> str(5)
'5'
>>> int(8.7)
8

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

How to change port for jenkins window service when 8080 is being used

On Windows (with Windows Service).

Edit the file C:\Program Files (x86)\Jenkins\jenkins.xml with 8083 if you want 8083 port.

<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8083</arguments>

What does the "map" method do in Ruby?

The map method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!):

[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]

Array and Range are enumerable types. map with a block returns an Array. map! mutates the original array.

Where is this helpful, and what is the difference between map! and each? Here is an example:

names = ['danil', 'edmund']

# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']

names.each { |name| puts name + ' is a programmer' } # here we just do something with each element

The output:

Danil is a programmer
Edmund is a programmer

How to force a line break on a Javascript concatenated string?

document.getElementById("address_box").value = 
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);

How to generate XML file dynamically using PHP?

I see examples with both DOM and SimpleXML, but none with the XMLWriter.

Please keep in mind that from the tests I've done, both DOM and SimpleXML are almost twice slower then the XMLWriter and for larger files you should consider using the later one.

Here's a full working example, clear and simple that meets the requirements, written with XMLWriter (I'm sure it will help other users):

// array with the key / value pairs of the information to be added (can be an array with the data fetched from db as well)
$songs = [
    'song1.mp3' => 'Track 1 - Track Title',
    'song2.mp3' => 'Track 2 - Track Title',
    'song3.mp3' => 'Track 3 - Track Title',
    'song4.mp3' => 'Track 4 - Track Title',
    'song5.mp3' => 'Track 5 - Track Title',
    'song6.mp3' => 'Track 6 - Track Title',
    'song7.mp3' => 'Track 7 - Track Title',
    'song8.mp3' => 'Track 8 - Track Title',
];

$xml = new XMLWriter();
$xml->openURI('songs.xml');
$xml->setIndent(true);
$xml->setIndentString('    ');
$xml->startDocument('1.0', 'UTF-8');
    $xml->startElement('xml');
            foreach($songs as $song => $track){
                $xml->startElement('track');
                    $xml->writeElement('path', $song);
                    $xml->writeElement('title', $track);
                $xml->endElement();
            }
    $xml->endElement();
$xml->endDocument();
$xml->flush();
unset($xml);

Reference jars inside a jar

if you do not want to create a custom class loader. You can read the jar file stream. And transfer it to a File object. Then you can get the url of the File. Send it to the URLClassLoader, you can load the jar file as you want. sample:

InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("example"+ ".jar");
final File tempFile = File.createTempFile("temp", ".jar");
tempFile.deleteOnExit();  // you can delete the temp file or not
try (FileOutputStream out = new FileOutputStream(tempFile)) {
    IOUtils.copy(resourceAsStream, out);
}
IOUtils.closeQuietly(resourceAsStream);
URL url = tempFile.toURI().toURL();
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
urlClassLoader.loadClass()
...

Smooth scroll to specific div on click

What if u use scrollIntoView function?

var elmntToView = document.getElementById("sectionId");
elmntToView.scrollIntoView(); 

Has {behavior: "smooth"} too.... ;) https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Valid characters of a hostname?

Checkout this wiki, specifically the section Restrictions on valid host names

Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, "en.wikipedia.org" is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9', and the hyphen ('-'). The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

'AND' vs '&&' as operator

I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:

true && false || false; // returns false

true and false || false; // returns true

Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.

UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:

var_dump(true and false || false); // bool(false)

$a = true and false || false; var_dump($a); // bool(true)

The reason why $a === true is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.

Prevent the keyboard from displaying on activity start

Just Add in AndroidManifest.xml

<activity android:name=".HomeActivity"  android:windowSoftInputMode="stateHidden">
</activity>

Angular/RxJs When should I unsubscribe from `Subscription`

For handling subscription I use a "Unsubscriber" class.

Here is the Unsubscriber Class.

export class Unsubscriber implements OnDestroy {
  private subscriptions: Subscription[] = [];

  addSubscription(subscription: Subscription | Subscription[]) {
    if (Array.isArray(subscription)) {
      this.subscriptions.push(...subscription);
    } else {
      this.subscriptions.push(subscription);
    }
  }

  unsubscribe() {
    this.subscriptions
      .filter(subscription => subscription)
      .forEach(subscription => {
        subscription.unsubscribe();
      });
  }

  ngOnDestroy() {
    this.unsubscribe();
  }
}

And You can use this class in any component / Service / Effect etc.

Example:

class SampleComponent extends Unsubscriber {
    constructor () {
        super();
    }

    this.addSubscription(subscription);
}

How to sort alphabetically while ignoring case sensitive?

Since Java 8 you can sort using the Streams API:

List<String> fruits = Arrays.asList("apple", "Apricot", "banana");

List<String> sortedFruit = fruits.stream()
      .sorted(String.CASE_INSENSITIVE_ORDER)
      .collect(Collectors.toList())

The difference with Collections.sort is that this will return a new list and will not modify the existing one.

Having issues with a MySQL Join that needs to meet multiple conditions

SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

javascript, is there an isObject function like isArray?

In jQuery there is $.isPlainObject() method for that:

Description: Check to see if an object is a plain object (created using "{}" or "new Object").

Difference between View and table in sql

A view helps us in get rid of utilizing database space all the time. If you create a table it is stored in database and holds some space throughout its existence. Instead view is utilized when a query runs hence saving the db space. And we cannot create big tables all the time joining different tables though we could but its depends how big the table is to save the space. So view just temporarily create a table with joining different table at the run time. Experts,Please correct me if I am wrong.

CMD what does /im (taskkill)?

It tells taskkill that the next parameter something.exe is an image name, a.k.a executable name

C:\>taskkill /?

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]

Description:
    This tool is used to terminate tasks by process id (PID) or image name.

Parameter List:
    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which the
                           command should execute.

    /P    [password]       Specifies the password for the given user
                           context. Prompts for input if omitted.

    /FI   filter           Applies a filter to select a set of tasks.
                           Allows "*" to be used. ex. imagename eq acme*

    /PID  processid        Specifies the PID of the process to be terminated.
                           Use TaskList to get the PID.

    /IM   imagename        Specifies the image name of the process
                           to be terminated. Wildcard '*' can be used
                           to specify all tasks or image names.

    /T                     Terminates the specified process and any
                           child processes which were started by it.

    /F                     Specifies to forcefully terminate the process(es).

    /?                     Displays this help message.

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

How can I create Min stl priority_queue?

The third template parameter for priority_queue is the comparator. Set it to use greater.

e.g.

std::priority_queue<int, std::vector<int>, std::greater<int> > max_queue;

You'll need #include <functional> for std::greater.

What is the best way to do a substring in a batch file?

As an additional info to Joey's answer, which isn't described in the help of set /? nor for /?.

%~0 expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as

%~0   - mYbAtCh
%~n0  - mybatch
%~nx0 - mybatch.bat

But there is one exception, expanding in a subroutine could fail

echo main- %~0
call :myFunction
exit /b

:myFunction
echo func - %~0
echo func - %~n0
exit /b

This results to

main - myBatch
Func - :myFunction
func - mybatch

In a function %~0 expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!

Trigger change event <select> using jquery

If you want to do some checks then use this way

 <select size="1" name="links" onchange="functionToTriggerClick(this.value)">
    <option value="">Select a Search Engine</option>        
    <option value="http://www.google.com">Google</option>
    <option value="http://www.yahoo.com">Yahoo</option>
</select>

<script>

   function functionToTriggerClick(link) {

     if(link != ''){
        window.location.href=link;
        }
    }  

</script>

In Python, how do I determine if an object is iterable?

The best solution I've found so far:

hasattr(obj, '__contains__')

which basically checks if the object implements the in operator.

Advantages (none of the other solutions has all three):

  • it is an expression (works as a lambda, as opposed to the try...except variant)
  • it is (should be) implemented by all iterables, including strings (as opposed to __iter__)
  • works on any Python >= 2.5

Notes:

  • the Python philosophy of "ask for forgiveness, not permission" doesn't work well when e.g. in a list you have both iterables and non-iterables and you need to treat each element differently according to it's type (treating iterables on try and non-iterables on except would work, but it would look butt-ugly and misleading)
  • solutions to this problem which attempt to actually iterate over the object (e.g. [x for x in obj]) to check if it's iterable may induce significant performance penalties for large iterables (especially if you just need the first few elements of the iterable, for example) and should be avoided

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

How do I get the old value of a changed cell in Excel VBA?

I have the same problem like you and luckily I have read the solution from this link: http://access-excel.tips/value-before-worksheet-change/

Dim oldValue As Variant
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    oldValue = Target.Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
    'do something with oldValue...
End Sub

Note: you must place oldValue variable as a global variable so all subclasses can use it.

How to attach a file using mail command on Linux?

mpack -a -s"Hey: might this serve as your report?" -m 0 -c application/x-tar-gz survey_results.tar.gz [email protected]

mpack and munpack work together with metamail to extend mailx and make it useful with modern email cluttered with html mark up and attachments.

Those four packages taken together will permit you to handle any email you could in a gui mail client.

How to add an image in the title bar using html?

it works

Add this inside your head tag

<link rel="shortcut icon" href="http://example.com/myicon.png" />

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Also register your created service in the Manifest and uses-permission as

<application ...>
   <service android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="com.example.MyBroadcastReciver"/>
        </intent-filter>
   </service>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

and then in braod cast Reciever call your service

public class MyBroadcastReceiver extends BroadcastReceiver 
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Intent myIntent = new Intent(context, MyService.class);
        context.startService(myIntent);
    }
}

Ball to Ball Collision - Detection and Handling

A good way of reducing the number of collision checks is to split the screen into different sections. You then only compare each ball to the balls in the same section.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

  • Open the start menu
  • Type windows+R or open "Run
  • Execute the following command.

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

Call a stored procedure with parameter in c#

The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.

A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :

  CREATE PROCEDURE SPCOUNTRY
  @COUNTRY VARCHAR(20)
  AS
  SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
  GO

The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.

  command.CommandType = CommandType.StoredProcedure;
  param = new SqlParameter("@COUNTRY", "Germany");
  param.Direction = ParameterDirection.Input;
  param.DbType = DbType.String;
  command.Parameters.Add(param);

The above code passing country parameter to the stored procedure from C# application.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection ;
            SqlDataAdapter adapter ;
            SqlCommand command = new SqlCommand();
            SqlParameter param ;
            DataSet ds = new DataSet();

            int i = 0;

            connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
            connection = new SqlConnection(connetionString);

            connection.Open();
            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "SPCOUNTRY";

            param = new SqlParameter("@COUNTRY", "Germany");
            param.Direction = ParameterDirection.Input;
            param.DbType = DbType.String;
            command.Parameters.Add(param);

            adapter = new SqlDataAdapter(command);
            adapter.Fill(ds);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
            }

            connection.Close();
        }
    }
}

Display fullscreen mode on Tkinter

This creates a fullscreen window. Pressing Escape resizes the window to '200x200+0+0' by default. If you move or resize the window, Escape toggles between the current geometry and the previous geometry.

import Tkinter as tk

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

root=tk.Tk()
app=FullScreenApp(root)
root.mainloop()

removing table border

Try giving your table an ID and then using !important to set border to none in CSS. If JavaScript is tampering with your table then that should get around it.

<table id="mytable"
...

table#mytable,
table#mytable td
{
    border: none !important;
}

Meaning of = delete after function declaration

= delete is a feature introduce in C++11. As per =delete it will not allowed to call that function.

In detail.

Suppose in a class.

Class ABC{
 Int d;
 Public:
  ABC& operator= (const ABC& obj) =delete
  {

  }
};

While calling this function for obj assignment it will not allowed. Means assignment operator is going to restrict to copy from one object to another.

Make a div into a link

Not sure if this is valid but it worked for me.

The code :

_x000D_
_x000D_
<div style='position:relative;background-color:#000000;width:600px;height:30px;border:solid;'>_x000D_
  <p style='display:inline;color:#ffffff;float:left;'> Whatever </p>     _x000D_
  <a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Histogram using gnuplot?

yes, and its quick and simple though very hidden:

binwidth=5
bin(x,width)=width*floor(x/width)

plot 'datafile' using (bin($1,binwidth)):(1.0) smooth freq with boxes

check out help smooth freq to see why the above makes a histogram

to deal with ranges just set the xrange variable.

Open firewall port on CentOS 7

Fedora, did it via iptables

sudo iptables -I INPUT -p tcp --dport 3030 -j ACCEPT
sudo service iptables save

Seems to work

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

What does java:comp/env/ do?

There is also a property resourceRef of JndiObjectFactoryBean that is, when set to true, used to automatically prepend the string java:comp/env/ if it is not already present.

<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="jdbc/loc"/>
  <property name="resourceRef" value="true"/>
</bean>

Writing handler for UIAlertAction

Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handler argument. Observe:

func someHandler(alert: UIAlertAction!) {
    // Do something...
}

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                              handler: someHandler))

How to get numeric position of alphabets in java?

Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.

This sounds like homework. If so, please tag it as such.

Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.

Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.

Python to print out status bar and percentage

def printProgressBar(value,label):
    n_bar = 40 #size of progress bar
    max = 100
    j= value/max
    sys.stdout.write('\r')
    bar = '¦' * int(n_bar * j)
    bar = bar + '-' * int(n_bar * (1-j))

    sys.stdout.write(f"{label.ljust(10)} | [{bar:{n_bar}s}] {int(100 * j)}% ")
    sys.stdout.flush()

call:

printProgressBar(30,"IP")

IP | [¦¦¦¦¦¦¦¦¦¦¦¦----------------------------] 30%

WPF global exception handler

A complete solution is here

it's explained very nice with sample code. However, be careful that it does not close the application.Add the line Application.Current.Shutdown(); to gracefully close the app.

Generate random 5 characters string

The following should provide the least chance of duplication (you might want to replace mt_rand() with a better random number source e.g. from /dev/*random or from GUIDs):

<?php
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $result = '';
    for ($i = 0; $i < 5; $i++)
        $result .= $characters[mt_rand(0, 61)];
?>

EDIT:
If you are concerned about security, really, do not use rand() or mt_rand(), and verify that your random data device is actually a device generating random data, not a regular file or something predictable like /dev/zero. mt_rand() considered harmful:
https://spideroak.com/blog/20121205114003-exploit-information-leaks-in-random-numbers-from-python-ruby-and-php

EDIT: If you have OpenSSL support in PHP, you could use openssl_random_pseudo_bytes():

<?php
    $length = 5;
    $randomBytes = openssl_random_pseudo_bytes($length);
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $charactersLength = strlen($characters);
    $result = '';
    for ($i = 0; $i < $length; $i++)
        $result .= $characters[ord($randomBytes[$i]) % $charactersLength];
?>

Is there a way to access the "previous row" value in a SELECT statement?

Oracle, PostgreSQL, SQL Server and many more RDBMS engines have analytic functions called LAG and LEAD that do this very thing.

In SQL Server prior to 2012 you'd need to do the following:

SELECT  value - (
        SELECT  TOP 1 value
        FROM    mytable m2
        WHERE   m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND m2.pk < m1.pk)
        ORDER BY 
                col1, pk
        )
FROM mytable m1
ORDER BY
      col1, pk

, where COL1 is the column you are ordering by.

Having an index on (COL1, PK) will greatly improve this query.

How to resize an image with OpenCV2.0 and Python2.6

If you wish to use CV2, you need to use the resize function.

For example, this will resize both axes by half:

small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 

and this will resize the image to have 100 cols (width) and 50 rows (height):

resized_image = cv2.resize(image, (100, 50)) 

Another option is to use scipy module, by using:

small = scipy.misc.imresize(image, 0.5)

There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).


Update:
According to the SciPy documentation:

imresize is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use skimage.transform.resize instead.

Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale.

how to get domain name from URL

/[^w{3}\.]([a-zA-Z0-9]([a-zA-Z0-9\-]{0,65}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}/gim

usage of this javascript regex ignores www and following dot, while retaining the domain intact. also properly matches no www and cc tld

How do you redirect HTTPS to HTTP?

all the above did not work when i used cloudflare, this one worked for me:

RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

and this one definitely works without proxies in the way:

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Object of class DateTime could not be converted to string

$Date = $row['Received_date']->format('d/m/Y');

then it cast date object from given in database

Return single column from a multi-dimensional array

If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)

$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}