Programs & Examples On #Multiplexing

In telecommunications and computer networks, multiplexing (also known as muxing) is a method by which multiple analogue message signals or digital data streams are combined into one signal over a shared medium.

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Security is one aspect you missed.

With Websockets the data has to go via a central webserver which typically sees all the traffic and can access it.

With WebRTC the data is end-to-end encrypted and does not pass through a server (except sometimes TURN servers are needed, but they have no access to the body of the messages they forward).

Depending on your application this may or may not matter.

If you are sending large amounts of data, the saving in cloud bandwidth costs due to webRTC's P2P architecture may be worth considering too.

How to set back button text in Swift

Set self.title = "" before self.navigationController?.pushViewController(vc, animated: true).

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

Importing CommonCrypto in a Swift framework

It happened the same to me after updating Xcode. I tried everything I can do such as reinstalling cocoapods and cleaning the project, but it didn't work. Now it's been solved after restart the system.

Expression must be a modifiable lvalue

You test k = M instead of k == M.
Maybe it is what you want to do, in this case, write if (match == 0 && (k = M))

Error: No module named psycopg2.extensions

For macOS Mojave just run pip install psycopg2-binary. Works fine for me, python version -> Python 3.7.2

C# guid and SQL uniqueidentifier

Store it in the database in a field with a data type of uniqueidentifier.

How to add leading zeros for for-loop in shell?

Just a note: I have experienced different behaviours on different versions of bash:

  • version 3.1.17(1)-release-(x86_64-suse-linux) and
  • Version 4.1.17(9)-release (x86_64-unknown-cygwin))

for the former (3.1) for nn in (00..99) ; do ... works but for nn in (000..999) ; do ... does not work both will work on version 4.1 ; haven't tested printf behaviour (bash --version gave the version info)

Cheers, Jan

Get second child using jQuery

You can use two methods in jQuery as given below-

Using jQuery :nth-child Selector You have put the position of an element as its argument which is 2 as you want to select the second li element.

_x000D_
_x000D_
$( "ul li:nth-child(2)" ).click(function(){_x000D_
  //do something_x000D_
});
_x000D_
_x000D_
_x000D_

Using jQuery :eq() Selector

If you want to get the exact element, you have to specify the index value of the item. A list element starts with an index 0. To select the 2nd element of li, you have to use 2 as the argument.

_x000D_
_x000D_
$( "ul li:eq(1)" ).click(function(){_x000D_
  //do something_x000D_
});
_x000D_
_x000D_
_x000D_

See Example: Get Second Child Element of List in jQuery

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

React Native add bold or italics to single words in <Text> field

Use this react native library

To install

npm install react-native-htmlview --save

Basic Usage

 import React from 'react';
 import HTMLView from 'react-native-htmlview';

  class App extends React.Component {
  render() {
   const htmlContent = 'This is a sentence <b>with</b> one word in bold';

  return (
   <HTMLView
     value={htmlContent}
   />    );
  }
}

Supports almost all html tags.

For more advanced usage like

  1. Link handling
  2. Custom Element Rendering

View this ReadMe

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

I got this issue on a Web API project. Finally figured out that it was in my "///" method comments. I have these comments set to auto-generate documentation for the API methods. Something in my comments made it go crazy. I deleted all the carriage returns, special characters, etc. Not really sure which thing it didn't like, but it worked.

Get text from pressed button

The view you get passed in on onClick() is the Button you are looking for.

public void onClick(View v) {
    // 1) Possibly check for instance of first 
    Button b = (Button)v;
    String buttonText = b.getText().toString();
}

1) If you are using a non-anonymous class as onClickListener, you may want to check for the type of the view before casting it, as it may be something different than a Button.

Django MEDIA_URL and MEDIA_ROOT

Adding to Micah Carrick answer for django 1.8:

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

How to animate button in android?

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class HeightAnimation extends Animation {
    protected final int originalHeight;
    protected final View view;
    protected float perValue;

    public HeightAnimation(View view, int fromHeight, int toHeight) {
        this.view = view;
        this.originalHeight = fromHeight;
        this.perValue = (toHeight - fromHeight);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
        view.requestLayout();
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

uss to:

HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2017 (Developer Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQLServer2017Media\Developer_ENU and click OK

Any way of using frames in HTML5?

I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.

Flutter position stack widget in center

Have a look at this solution I came up with

Positioned( child: SizedBox( child: CircularProgressIndicator(), width: 50, height: 50,), left: MediaQuery.of(context).size.width / 2 - 25);

What is the correct way to represent null XML elements?

It depends on how you validate your XML. If you use XML Schema validation, the correct way of representing null values is with the xsi:nil attribute.

[Source]

How to delete all rows from all tables in a SQL Server database?

For some requirements we might have to skip certain tables. I wrote the below script to add some extra conditions to filter the list of tables. The below script will also display the pre delete count and post delete count.

        IF OBJECT_ID('TEMPDB..#TEMPRECORDCOUNT') IS NOT NULL 
        DROP TABLE #TEMPRECORDCOUNT 

        CREATE TABLE #TEMPRECORDCOUNT 
            (    TABLENAME NVARCHAR(128)
                ,PREDELETECOUNT BIGINT
                ,POSTDELETECOUNT BIGINT
            ) 

        INSERT INTO #TEMPRECORDCOUNT (TABLENAME, PREDELETECOUNT, POSTDELETECOUNT)

        SELECT   O.name TableName
                ,DDPS.ROW_COUNT PREDELETECOUNT
                ,NULL  FROM sys.objects O 

        INNER JOIN (

                    SELECT OBJECT_ID, SUM(row_count) ROW_COUNT 
                    FROM SYS.DM_DB_PARTITION_STATS
                    GROUP BY OBJECT_ID
                   ) DDPS ON DDPS.OBJECT_ID = O.OBJECT_ID
        WHERE O.type = 'U' AND O.name NOT LIKE 'OC%' AND O.schema_id = 1

        DECLARE @TableName NVARCHAR(MAX);
        DECLARE TableDeleteCursor CURSOR FAST_FORWARD 
        FOR 
        SELECT TableName from #TEMPRECORDCOUNT

        OPEN TableDeleteCursor
        FETCH NEXT FROM TableDeleteCursor INTO @TableName

        WHILE (@@FETCH_STATUS <> -1)
        BEGIN
        IF (@@FETCH_STATUS <> -2)
        BEGIN
        DECLARE @STATEMENT NVARCHAR(MAX);
        SET @STATEMENT = ' DISABLE TRIGGER ALL ON ' + @TableName + 
                         '; ALTER TABLE ' + @TableName + ' NOCHECK CONSTRAINT ALL' +
                         '; DELETE FROM ' + @TableName +
                         '; ALTER TABLE ' + @TableName + ' CHECK CONSTRAINT ALL' +
                         '; ENABLE TRIGGER ALL ON ' + @TableName;
        PRINT @STATEMENT
        EXECUTE SP_EXECUTESQL @STATEMENT;
        END
        FETCH NEXT FROM TableDeleteCursor INTO @TableName
        END
        CLOSE TableDeleteCursor
        DEALLOCATE TableDeleteCursor

        UPDATE T 
         SET T.POSTDELETECOUNT = I.ROW_COUNT 
         FROM #TEMPRECORDCOUNT T 
         INNER JOIN (
                        SELECT O.name TableName, DDPS.ROW_COUNT ROW_COUNT  
                        FROM sys.objects O 
                        INNER JOIN (

                                SELECT OBJECT_ID, SUM(row_count) ROW_COUNT 
                                FROM SYS.DM_DB_PARTITION_STATS
                                GROUP BY OBJECT_ID
                               ) DDPS ON DDPS.OBJECT_ID = O.OBJECT_ID
                        WHERE O.type = 'U' AND O.name NOT LIKE 'OC%' AND O.schema_id = 1

                    ) I ON I.TableName COLLATE DATABASE_DEFAULT = T.TABLENAME 

        SELECT * FROM #TEMPRECORDCOUNT 
        ORDER BY TABLENAME ASC

How to get public directory?

I know this is a little late, but if someone else comes across this looking, you can now use public_path(); in Laravel 4, it has been added to the helper.php file in the support folder see here.

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

HTML display result in text (input) field?

 <HTML>
      <HEAD>
        <TITLE>Sum</TITLE>

        <script type="text/javascript">
          function sum()
          {

             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').value = sum;
          }
        </script>
      </HEAD>

      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
          <INPUT TYPE="text" NAME="number2" VALUE=""/>
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
          <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
        </FORM>

      </BODY>
</HTML>

This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

If you want as simple as possible, install from the repository:

sudo apt-get install python-opencv libopencv-dev python-numpy python-dev

Finding CN of users in Active Directory

CN refers to class name, so put in your LDAP query CN=Users. Should work.

Call a function on click event in Angular 2

Component code:

import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public items: Array<string>;

  constructor() {
    this.items = ["item1", "item2", "item3"]
  }

  public open(event, item) {
    alert('Open ' + item);
  }

}

View:

<ion-header>
  <ion-navbar primary>
    <ion-title>
      <span>My App</span>
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item *ngFor="let item of items" (click)="open($event, item)">
      {{ item }}
    </ion-item>
  </ion-list>
</ion-content>

As you can see in the code, I'm declaring the click handler like this (click)="open($event, item)" and sending both the event and the item (declared in the *ngFor) to the open() method (declared in the component code).

If you just want to show the item and you don't need to get info from the event, you can just do (click)="open(item)" and modify the open method like this public open(item) { ... }

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

I came researching the options that I would have to do this, however, I believe the method I use is the simplest:

SELECT COUNT(*), 
       DATEADD(dd, DATEDIFF(dd, 0, date_field),0) as dtgroup 
FROM TABLE 
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, date_field),0) 
ORDER BY dtgroup ASC;

How can I pass a username/password in the header to a SOAP WCF Service

The answers above are so wrong! DO NOT add custom headers. Judging from your sample xml, it is a standard WS-Security header. WCF definitely supports it out of the box. When you add a service reference you should have basicHttpBinding binding created for you in the config file. You will have to modify it to include security element with mode TransportWithMessageCredential and message element with clientCredentialType = UserName:

<basicHttpBinding>
  <binding name="usernameHttps">
    <security mode="TransportWithMessageCredential">
      <message clientCredentialType="UserName"/>
    </security>
  </binding>
</basicHttpBinding>

The config above is telling WCF to expect userid/password in the SOAP header over HTTPS. Then you can set id/password in your code before making a call:

var service = new MyServiceClient();
service.ClientCredentials.UserName.UserName = "username";
service.ClientCredentials.UserName.Password = "password";

Unless this particular service provider deviated from the standard, it should work.

Xcode Project vs. Xcode Workspace - Differences

In brief

  • Xcode 3 introduced subproject, which is parent-child relationship, meaning that parent can reference its child target, but no vice versa
  • Xcode 4 introduced workspace, which is sibling relationship, meaning that any project can reference projects in the same workspace

What type of hash does WordPress use?

The best way to do this is using WordPress class to authenticate users. Here is my solutions:

1. Include following WordPress PHP file:

include_once(dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . "wp-includes" . DIRECTORY_SEPARATOR . "class-phpass.php");

2. Create an object of PasswordHash class:

$wp_hasher = new PasswordHash(8, true);

3. call CheckPassword function to authenticate user:

$check = $wp_hasher->CheckPassword($password, $row['user_pass']);

4. check $check variable:

if($check) {
   echo "password is correct";
} else {
   echo "password is incorrect";
}

Please Note that: $password is the un-hashed password in clear text whereas $row['user_pass'] is the hashed password that you need to fetch from the database.

Spring Boot Remove Whitelabel Error Page

Here's an alternative method which is very similar to the "old way" of specifying error mappings in web.xml.

Just add this to your Spring Boot configuration:

@SpringBootApplication
public class Application implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/errors/403.html"));
        factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/errors/404.html"));
        factory.addErrorPages(new ErrorPage("/errors/500.html"));
    }

}

Then you can define the error pages in the static content normally.

The customizer can also be a separate @Component, if desired.

Python dictionary: are keys() and values() always the same order?

According to http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-objects , the keys(), values() and items() methods of a dict will return corresponding iterators whose orders correspond. However, I am unable to find a reference to the official documentation for python 2.x for the same thing.

So as far as I can tell, the answer is yes, but only in python 3.0+

How to force file download with PHP

The answers above me works. But, I'd like to contribute a method on how to perform it using GET

on your html/php page

$File = 'some/dir/file.jpg';
<a href="<?php echo '../sumdir/download.php?f='.$File; ?>" target="_blank">Download</a>

and download.php contains

$file = $_GET['f']; 

header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

$ext = pathinfo($file, PATHINFO_EXTENSION);
$basename = pathinfo($file, PATHINFO_BASENAME);

header("Content-type: application/".$ext);
header('Content-length: '.filesize($file));
header("Content-Disposition: attachment; filename=\"$basename\"");
ob_clean(); 
flush();
readfile($file);
exit;

this should work on any file types. this is not tested using POST, but it could work.

regular expression to validate datetime format (MM/DD/YYYY)

you can look into this link and I hope this may be of great help as its was for me.

If you are using the regex given in the above link in Java code then use the following regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$"

As I noticed in your example you are using js function then this use regex

"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"

This will match a date in mm/dd/yyyy format from between 1900-01-01 and 2099-12-31, with a choice of four separators. and not to forget the

return regex.test(testdate);

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:

pyinstaller oldlogs.py

From the tool's documentation:

PyInstaller analyzes myscript.py and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

Extracting Ajax return data in jQuery

You can use .filter on a jQuery object that was created from the response:

success: function(data){
    //Create jQuery object from the response HTML.
    var $response=$(data);

    //Query the jQuery object for the values
    var oneval = $response.filter('#one').text();
    var subval = $response.filter('#sub').text();
}

How can I add a table of contents to a Jupyter / JupyterLab notebook?

nbextensions ToC instructions

Introduction

As @Ian and @Sergey have mentioned, nbextensions is a simple solution. To elaborate their answer, here is a few more information.

What is nbextensions?

The nbextensions contains a collection of extensions that add functionality to your Jupyter notebook.

For example, just to cite a few extensions:

  • Table of Contents

  • Collapsible headings

Install nbextensions

The installation can be done through Conda or PIP

# If conda:
conda install -c conda-forge jupyter_contrib_nbextensions
# or with pip:
pip install jupyter_contrib_nbextensions

You will see the new tab Nbextensions in the jupyter notebook menu. Uncheck the checkbox at the top disable configuration for nbextensions without explicit compatibility (they may break your notebook environment, but can be useful to show for nbextension development) and then check Table of Contents(2). That is all. Screenshot:

choice of "Table of Contents(2)" in Configurable nbextensions

Copy js and css files

To copy the nbextensions' javascript and css files into the jupyter server's search directory, do the following:

jupyter contrib nbextension install --user

Toggle extensions

Note that if you are not familiar with the terminal, it would be better to install nbextensions configurator (see the next section)

You can enable/disable the extensions of your choice. As the documentation mentions, the generic command is:

jupyter nbextension enable <nbextension require path>

Concretely, to enable the ToC (Table of Contents) extension, do:

jupyter nbextension enable toc2/main

Install Configuration interface (optional but useful)

As its documentation says, nbextensions_configurator provides config interfaces for nbextensions.

It looks like the following: nbextensions configurators

To install it if you use conda:

conda install -c conda-forge jupyter_nbextensions_configurator

If you don't have Conda or don't want to install through Conda, then do the following 2 steps:

pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

How to write URLs in Latex?

A minimalist implementation of the \url macro that uses only Tex primitives:

\def\url#1{\expandafter\string\csname #1\endcsname}

This url absolutely won't break over lines, though; the hypperef package is better for that.

Googlemaps API Key for Localhost

  1. Go to this address: https://console.developers.google.com/apis
  2. Create new project and Create Credentials (API key)
  3. Click on "Library"
  4. Click on any API that you want
  5. Click on "Enable"
  6. Click on "Credentials" > "Edit Key"
  7. Under "Application restrictions", select "HTTP referrers (web sites)"
  8. Under "Website restrictions", Click on "ADD AN ITEM"
  9. Type your website address (or "localhost", "127.0.0.1", "localhost:port" etc for local tests) in the text field and press ENTER to add it to the list
  10. SAVE and Use your key in your project

How do I rename a column in a SQLite database table?

Since version 2018-09-15 (3.25.0) sqlite supports renaming columns

https://sqlite.org/changes.html

Install apk without downloading

you can use this code .may be solve the problem

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);

Programmatically Creating UILabel

For swift

var label = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 50))
label.textAlignment = .left
label.text = "This is a Label"
self.view.addSubview(label)

MySQL date formats - difficulty Inserting a date

Put the date in single quotes and move the parenthesis (after the 'yes') to the end:

INSERT INTO custorder 
  VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
                        ^                                     ^
---parenthesis removed--|                and added here ------|

But you can always use dates without STR_TO_DATE() function, just use the (Y-m-d) '20120101' or '2012-01-01' format. Check the MySQL docs: Date and Time Literals

INSERT INTO custorder 
  VALUES ('Kevin', 'yes', '2012-01-01') ;

How to prevent IFRAME from redirecting top-level window

I use sandbox="..."

  • allow-forms allows form submission
  • allow-popups allows popups
  • allow-pointer-lock allows pointer lock
  • allow-same-origin allows the document to maintain its origin
  • allow-scripts allows JavaScript execution, and also allows features to trigger automatically
  • allow-top-navigation allows the document to break out of the frame by navigating the top-level window

Top navigation is what you want to prevent, so leave that out and it will not be allowed. Anything left out will be blocked

ex.

        <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="http://www.example.com"</iframe>

What does "Git push non-fast-forward updates were rejected" mean?

A fast-forward update is where the only changes one one side are after the most recent commit on the other side, so there doesn't need to be any merging. This is saying that you need to merge your changes before you can push.

Set default host and port for ng serve in config file

If you want to specifically have your local ip address open when running ng serve you can do the following:

npm install internal-ip-cli --save
ng serve --open --host $(./node_modules/.bin/internal-ip --ipv4)

How to run composer from anywhere?

For MAC and LINUX use the following procedure:

Add the directory where composer.phar is located to you PATH:

export PATH=$PATH:/yourdirectory

and then rename composer.phar to composer:

mv composer.phar composer

The type initializer for 'MyClass' threw an exception

In my case I had this failing on Logger.Create inside a class library that was being used by my main (console) app. The problem was I had forgotten to add a reference to NLog.dll in my console app. Adding the reference with the correct .NET Framework library version fixed the problem.

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

//Call .noConflict() to restore JQuery reference.

jQuery.noConflict(); OR  $.noConflict();

//Do something with jQuery.

jQuery( "div.class" ).hide(); OR $( "div.class" ).show();

Found a swap file by the name

Looks like you have an open git commit or git merge going on, and an editor is still open editing the commit message.

Two choices:

  1. Find the session and finish it (preferable).
  2. Delete the .swp file (if you're sure the other git session has gone away).

Clarification from comments:

  • The session is the editing session.
  • You can see what .swp is being used by entering the command :sw within the editing session, but generally it's a hidden file in the same directory as the file you are using, with a .swp file suffix (i.e. ~/myfile.txt would be ~/.myfile.txt.swp).

what is trailing whitespace and how can I handle this?

This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding. But if you're obsessed about clean coding, same as me, you have two options:

  1. Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
  2. Press f1 then type trim trailing whitespace.

What is the maximum characters for the NVARCHAR(MAX)?

I think actually nvarchar(MAX) can store approximately 1070000000 chars.

Should ol/ul be inside <p> or outside?

GO here http://validator.w3.org/ upload your html file and it will tell you what is valid and what is not.

Force unmount of NFS-mounted directory

Couldn't find a working answer here; but on linux you can run "umount.nfs4 /volume -f" and it definitely unmounts it.

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here

What's the simplest way to extend a numpy array in 2 dimensions?

A useful alternative answer to the first question, using the examples from tomeedee’s answer, would be to use numpy’s vstack and column_stack methods:

Given a matrix p,

>>> import numpy as np
>>> p = np.array([ [1,2] , [3,4] ])

an augmented matrix can be generated by:

>>> p = np.vstack( [ p , [5 , 6] ] )
>>> p = np.column_stack( [ p , [ 7 , 8 , 9 ] ] )
>>> p
array([[1, 2, 7],
       [3, 4, 8],
       [5, 6, 9]])

These methods may be convenient in practice than np.append() as they allow 1D arrays to be appended to a matrix without any modification, in contrast to the following scenario:

>>> p = np.array([ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] )
>>> p = np.append( p , [ 7 , 8 , 9 ] , 1 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 3234, in append
    return concatenate((arr, values), axis=axis)
ValueError: arrays must have same number of dimensions

In answer to the second question, a nice way to remove rows and columns is to use logical array indexing as follows:

Given a matrix p,

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )

suppose we want to remove row 1 and column 2:

>>> r , c = 1 , 2
>>> p = p [ np.arange( p.shape[0] ) != r , : ] 
>>> p = p [ : , np.arange( p.shape[1] ) != c ]
>>> p
array([[ 0,  1,  3,  4],
       [10, 11, 13, 14],
       [15, 16, 18, 19]])

Note - for reformed Matlab users - if you wanted to do these in a one-liner you need to index twice:

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )    
>>> p = p [ np.arange( p.shape[0] ) != r , : ] [ : , np.arange( p.shape[1] ) != c ]

This technique can also be extended to remove sets of rows and columns, so if we wanted to remove rows 0 & 2 and columns 1, 2 & 3 we could use numpy's setdiff1d function to generate the desired logical index:

>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )
>>> r = [ 0 , 2 ]
>>> c = [ 1 , 2 , 3 ]
>>> p = p [ np.setdiff1d( np.arange( p.shape[0] ), r ) , : ] 
>>> p = p [ : , np.setdiff1d( np.arange( p.shape[1] ) , c ) ]
>>> p
array([[ 5,  9],
       [15, 19]])

Optimistic vs. Pessimistic locking

Lot of good things have been said above about optimistic and pessimistic locking. One important point to consider is as follows:

When using optimistic locking, we need to cautious of the fact that how will application recover from these failures.

Specially in asynchronous message driven architectures, this can lead of out of order message processing or lost updates.

Failures scenarios need to be thought through.

Is it possible to delete an object's property in PHP?

This also works if you are looping over an object.

unset($object->$key);

No need to use brackets.

Display Bootstrap Modal using javascript onClick

I was looking for the onClick option to set the title and body of the modal based on the item in a list. T145's answer helped a lot, so I wanted to share how I used it.

Make sure the tag containing the JavaScript function is of type text/javascript to avoid conflicts:

<script type="text/javascript"> function showMyModalSetTitle(myTitle, myBodyHtml) {

   /*
    * '#myModayTitle' and '#myModalBody' refer to the 'id' of the HTML tags in
    * the modal HTML code that hold the title and body respectively. These id's
    * can be named anything, just make sure they are added as necessary.
    *
    */

   $('#myModalTitle').html(myTitle);
   $('#myModalBody').html(myBodyHtml);

   $('#myModal').modal('show');
}</script>

This function can now be called in the onClick method from inside an element such as a button:

<button type="button" onClick="javascript:showMyModalSetTitle('Some Title', 'Some body txt')"> Click Me! </button>

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Change event on select with knockout binding, how can I know if it is a real change?

I had a similar problem and I just modified the event handler to check the type of the variable. The type is only set after the user selects a value, not when the page is first loaded.

self.permissionChanged = function (l) {
    if (typeof l != 'undefined') {
        ...
    }
}

This seems to work for me.

Which MySQL datatype to use for an IP address?

Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:

`ipv4` INT UNSIGNED

And INET_ATON and INET_NTOA to convert them:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARY instead:

`ipv6` BINARY(16)

And use PHP’s inet_pton and inet_ntop for conversion:

'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);

Conditionally hide CommandField or ButtonField in Gridview

First, convert your ButtonField or CommandField to a TemplateField, then bind the Visible property of the button to a method that implements the business logic:

<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Age" HeaderText="Age" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button runat="server" Text="Reject" 
                Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>' 
                CommandName="Select"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Then, in the code behind, add in the method:

protected Boolean IsOverAgeLimit(Decimal Age) {
    return Age > 35M;
}

The advantage here is you can test the IsOverAgeLimit method fairly easily.

Accessing all items in the JToken

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

Something like this:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

Output:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

Is there a decent wait function in C++?

Well, this is an old post but I will just contribute to the question -- someone may find it useful later:

adding 'cin.get();' function just before the return of the main() seems to always stop the program from exiting before printing the results: see sample code below:

int main(){ string fname, lname;

  //ask user to enter name first and last name
  cout << "Please enter your first name: ";
  cin >> fname;

  cout << "Please enter your last name: ";
  cin >> lname;     
  cout << "\n\n\n\nyour first name is: " << fname << "\nyour last name is: " 
  << lname <<endl;

  //stop program from exiting before printing results on the screen
  cin.get();
  return 0;

}

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

I had a similar problem of Eclipse compiling my code just fine but Maven failed when compiling the tests every time despite the fact JUnit was in my list of dependencies and the tests were in /src/test/java/.

In my case, I had the wrong version of JUnit in my list of dependencies. I wrote JUnit4 tests (with annotations) but had JUnit 3.8.x as my dependency. Between version 3.8.x and 4 of JUnit they changed the package name from junit.framework to org.junit which is why Maven still breaks compiling using a JUnit jar.

I'm still not entirely sure why Eclipse successfully compiled. It must have its own copy of JUnit4 somewhere in the classpath. Hope this alternative solution is useful to people. I reached this solution after following Arthur's link above.

Can't use SURF, SIFT in OpenCV

  1. Install OpenCV-Contrib

  2. import cv2 sift = cv2.xfeatures2d.SIFT_create()

  3. sift.something()

This is the easy way to install the Contrib.

Best way to move files between S3 buckets?

We had this exact problem with our ETL jobs at Snowplow, so we extracted our parallel file-copy code (Ruby, built on top of Fog), into its own Ruby gem, called Sluice:

https://github.com/snowplow/sluice

Sluice also handles S3 file delete, move and download; all parallelised and with automatic re-try if an operation fails (which it does surprisingly often). I hope it's useful!

Possible to make labels appear when hovering over a point in matplotlib?

mpld3 solve it for me. EDIT (CODE ADDED):

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

fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
N = 100

scatter = ax.scatter(np.random.normal(size=N),
                 np.random.normal(size=N),
                 c=np.random.random(size=N),
                 s=1000 * np.random.random(size=N),
                 alpha=0.3,
                 cmap=plt.cm.jet)
ax.grid(color='white', linestyle='solid')

ax.set_title("Scatter Plot (with tooltips!)", size=20)

labels = ['point {0}'.format(i + 1) for i in range(N)]
tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels)
mpld3.plugins.connect(fig, tooltip)

mpld3.show()

You can check this example

How to test if parameters exist in rails

use blank? http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F

unless params[:one].blank? && params[:two].blank?

will return true if its empty or nil

also... that will not work if you are testing boolean values.. since

>> false.blank?
=> true

in that case you could use

unless params[:one].to_s.blank? && params[:two].to_s.blank?

How to add a color overlay to a background image?

background-image takes multiple values.

so a combination of just 1 color linear-gradient and css blend modes will do the trick.

.testclass {
    background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
    background-blend-mode: overlay;
}

note that there is no support on IE/Edge for CSS blend-modes at all.

Returning anonymous type in C#

It is actually possible to return an anonymous type from a method in a particular use-case. Let's have a look!

With C# 7 it is possible to return anonymous types from a method, although it comes with a slight constraint. We are going to use a new language feature called local function together with an indirection trick (another layer of indirection can solve any programming challenge, right?).

Here's a use-case I recently identified. I want to log all configuration values after I have loaded them from AppSettings. Why? Because there's some logic around missing values that revert to default values, some parsing and so on. An easy way to log the values after applying the logic is to put them all in a class and serialize it to a logfile (using log4net). I also want to encapsulate the complex logic of dealing with settings and separate that from whatever I need to do with them. All without creating a named class that exists just for a single use!

Let's see how to solve this using a local function that creates an anonymous type.

public static HttpClient CreateHttpClient()
{
    // I deal with configuration values in this slightly convoluted way.
    // The benefit is encapsulation of logic and we do not need to
    // create a class, as we can use an anonymous class.
    // The result resembles an expression statement that
    // returns a value (similar to expressions in F#)
    var config = Invoke(() =>
    {
        // slightly complex logic with default value
        // in case of missing configuration value
        // (this is what I want to encapsulate)
        int? acquireTokenTimeoutSeconds = null;
        if (int.TryParse(ConfigurationManager.AppSettings["AcquireTokenTimeoutSeconds"], out int i))
        {
            acquireTokenTimeoutSeconds = i;
        }

        // more complex logic surrounding configuration values ...

        // construct the aggregate configuration class as an anonymous type!
        var c = new
        {
            AcquireTokenTimeoutSeconds =
                acquireTokenTimeoutSeconds ?? DefaultAcquireTokenTimeoutSeconds,
            // ... more properties
        };

        // log the whole object for monitoring purposes
        // (this is also a reason I want encapsulation)
        Log.InfoFormat("Config={0}", c);
        return c;
    });

    // use this configuration in any way necessary...
    // the rest of the method concerns only the factory,
    // i.e. creating the HttpClient with whatever configuration
    // in my case this:
    return new HttpClient(...);

    // local function that enables the above expression
    T Invoke<T>(Func<T> func) => func.Invoke();
}

I have succeeded in constructing an anonymous class and also encapsulated the logic of dealing with complex settings management, all inside CreateHttpClient and within its own "expression". This might not be exactly what the OP wanted but it is a lightweight approach with anonymous types that is currently possible in modern C#.

How to create an 2D ArrayList in java?

1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it

ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

should be written

List<List<String>> listOfLists = new ArrayList<List<String>>(size); 

Then you will have to instantiate all columns of your 2d array

    for(int i = 0; i < size; i++)  {
        listOfLists.add(new ArrayList<String>());
    }

And you will use it like this :

listOfLists.get(0).add("foobar");

But if you really want to "create a 2D array that each cell is an ArrayList!"

Then you must go the dijkstra way.

The identity used to sign the executable is no longer valid

Neither restarting Xcode nor restarting my Mac helped.

Solution within Xcode:

  1. In Xcode, go to Preferences --> Accounts --> View Details
  2. Press the + symbol and select iOS Development
  3. Press the refresh button in the lower left corner (called Download all in Xcode 7)

PS:

  • Sometimes it may also help to delete invalid provisioning profiles: right-click -> move to trash
  • I saw this error exactly one year after signing up as an Apple developer.

Inserting a value into all possible locations in a list

Use insert() to insert an element before a given position.

For instance, with

arr = ['A','B','C']
arr.insert(0,'D')

arr becomes ['D','A','B','C'] because D is inserted before the element at index 0.

Now, for

arr = ['A','B','C']
arr.insert(4,'D')

arr becomes ['A','B','C','D'] because D is inserted before the element at index 4 (which is 1 beyond the end of the array).

However, if you are looking to generate all permutations of an array, there are ways to do this already built into Python. The itertools package has a permutation generator.

Here's some example code:

import itertools
arr = ['A','B','C']
perms = itertools.permutations(arr)
for perm in perms:
    print perm

will print out

('A', 'B', 'C')
('A', 'C', 'B')
('B', 'A', 'C')
('B', 'C', 'A')
('C', 'A', 'B')
('C', 'B', 'A')

What is the largest Safe UDP Packet Size on the Internet

512 is your best bet. It's used elsewhere and is a nice even number (half of 1024).

Test or check if sheet exists

You don't need error handling in order to accomplish this. All you have to do is iterate over all of the Worksheets and check if the specified name exists:

For i = 1 To Worksheets.Count
    If Worksheets(i).Name = "MySheet" Then
        exists = True
    End If
Next i

If Not exists Then
    Worksheets.Add.Name = "MySheet"
End If

Get the Selected value from the Drop down box in PHP

You need to set a name on the <select> tag like so:

<select name="select_catalog" id="select_catalog">

You can get it in php with this:

$_POST['select_catalog'];

How to calculate a mod b in Python?

mod = a % b

This stores the result of a mod b in the variable mod.

And you are right, 15 mod 4 is 3, which is exactly what python returns:

>>> 15 % 4
3

a %= b is also valid.

Calling Oracle stored procedure from C#?

I have now got the steps needed to call procedure from C#

   //GIVE PROCEDURE NAME
   cmd = new OracleCommand("PROCEDURE_NAME", con);
   cmd.CommandType = CommandType.StoredProcedure;

   //ASSIGN PARAMETERS TO BE PASSED
   cmd.Parameters.Add("PARAM1",OracleDbType.Varchar2).Value = VAL1;
   cmd.Parameters.Add("PARAM2",OracleDbType.Varchar2).Value = VAL2;

   //THIS PARAMETER MAY BE USED TO RETURN RESULT OF PROCEDURE CALL
   cmd.Parameters.Add("vSUCCESS", OracleDbType.Varchar2, 1);
   cmd.Parameters["vSUCCESS"].Direction = ParameterDirection.Output;

   //USE THIS PARAMETER CASE CURSOR IS RETURNED FROM PROCEDURE
   cmd.Parameters.Add("vCHASSIS_RESULT",OracleDbType.RefCursor,ParameterDirection.InputOutput); 

   //CALL PROCEDURE
   con.Open();
   OracleDataAdapter da = new OracleDataAdapter(cmd);
   cmd.ExecuteNonQuery();

   //RETURN VALUE
   if (cmd.Parameters["vSUCCESS"].Value.ToString().Equals("T"))
   {
      //YOUR CODE
   }
   //OR
   //IN CASE CURSOR IS TO BE USED, STORE IT IN DATATABLE
   con.Open();
   OracleDataAdapter da = new OracleDataAdapter(cmd);
   da.Fill(dt);

Hope this helps

How do you disable browser Autocomplete on web form field / input tag?

As of Dec 2019:

Before answering this question let me say, I tried almost all the answers here on SO and from different forums but couldn't find a solution that works for all modern browsers and IE11.

So here is the solution I found, and I believe it's not yet discussed or mentioned in this post.

According to Mozilla Dev Network(MDN) post about how to turn off form autocomplete

By default, browsers remember information that the user submits through fields on websites. This enables the browser to offer autocompletion (that is, suggest possible completions for fields that the user has started typing in) or autofill (that is, pre-populate certain fields upon load)

On same article they discussed the usage of autocmplete property and its limitation. As we know, not all browsers honor this attribute as we desire.

Solution

So at the end of the article they shared a solution that works for all browsers including IE11+Edge. It is basically a jQuery plugin that do the trick. Here is the link to jQuery plugin and how it works.

Code snippet:

$(document).ready(function () {        
    $('#frmLogin').disableAutoFill({
        passwordField: '.password'
    });
});

Point to notice in HTML is that password field is of type text and password class is applied to identify that field:

<input id="Password" name="Password" type="text" class="form-control password">

Hope this would help someone.

Regular expression for number with length of 4, 5 or 6

Try this:

^[0-9]{4,6}$

{4,6} = between 4 and 6 characters, inclusive.

Animate change of view background color on Android

If you want color animation like this,

Enter image description here

this code will help you:

ValueAnimator anim = ValueAnimator.ofFloat(0, 1);   
anim.setDuration(2000);

float[] hsv;
int runColor;
int hue = 0;
hsv = new float[3]; // Transition color
hsv[1] = 1;
hsv[2] = 1;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {

        hsv[0] = 360 * animation.getAnimatedFraction();

        runColor = Color.HSVToColor(hsv);
        yourView.setBackgroundColor(runColor);
    }
});

anim.setRepeatCount(Animation.INFINITE);

anim.start();

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Short form for Java if statement

The way to do it is with ternary operator:

name = city.getName() == null ? city.getName() : "N/A"

However, I believe you have a typo in your code above, and you mean to say:

if (city.getName() != null) ...

Import Excel Spreadsheet Data to an EXISTING sql table?

You can copy-paste data from en excel-sheet to an SQL-table by doing so:

  • Select the data in Excel and press Ctrl + C
  • In SQL Server Management Studio right click the table and choose Edit Top 200 Rows
  • Scroll to the bottom and select the entire empty row by clicking on the row header
  • Paste the data by pressing Ctrl + V

Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.

Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).

How to deserialize JS date using Jackson?

In addition to Varun Achar's answer, this is the Java 8 variant I came up with, that uses java.time.LocalDate and ZonedDateTime instead of the old java.util.Date classes.

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

    @Override
    public LocalDate deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException {

        String string = jsonparser.getText();

        if(string.length() > 20) {
            ZonedDateTime zonedDateTime = ZonedDateTime.parse(string);
            return zonedDateTime.toLocalDate();
        }

        return LocalDate.parse(string);
    }
  }

Java: Replace all ' in a string with \'

You have to first escape the backslash because it's a literal (yielding \\), and then escape it again because of the regular expression (yielding \\\\). So, Try:

 s.replaceAll("'", "\\\\'");

output:

You\'ll be totally awesome, I\'m really terrible

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0

How to open child forms positioned within MDI parent in VB.NET?

If your form is "outside" the MDI parent, then you most likely didn't set the MdiParent property:

Dim f As New Form
f.MdiParent = Me
f.Show()

Me, in this example, is a form that has IsMdiContainer = True so that it can host child forms.

For re-arranging the child form layout, you just call the method from your MdiContainer form:

Me.LayoutMdi(MdiLayout.Cascade)

The MdiLayout enum also has tiling and arrange icons values.

JavaScript string and number conversion

Simplest is when you want to make a integer a string do

var a,b, c;
a = 1;
b = a.toString(); // This will give you string

Now, from the variable b which is of type string we can get the integer

c = b *1; //This will give you integer value of number :-)

If you want to check above is a number. If you are not sure if b contains integer then you can use

if(isNaN(c*1)) {
  //NOt a number
}
else //number

How does one target IE7 and IE8 with valid CSS?

For a more complete list as of 2015:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading

Convert Json String to C# Object List

You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
    public class Option
    {
        public string text { get; set; }
        public string selectedMarks { get; set; }
    }

    public class Model
    {
        public List<Option> options { get; set; }
        public int maxOptions { get; set; }
        public int minOptions { get; set; }
        public bool isAnswerRequired { get; set; }
        public string selectedOption { get; set; }
        public string answerText { get; set; }
        public bool isRangeType { get; set; }
        public string from { get; set; }
        public string to { get; set; }
        public string mins { get; set; }
        public string secs { get; set; }
    }

    public class Question
    {
        public int QuestionId { get; set; }
        public string QuestionText { get; set; }
        public int TypeId { get; set; }
        public string TypeName { get; set; }
        public Model Model { get; set; }
    }

    public class RootObject
    {
        public Question Question { get; set; }
        public string CheckType { get; set; }
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public string S4 { get; set; }
        public string S5 { get; set; }
        public string S6 { get; set; }
        public string S7 { get; set; }
        public string S8 { get; set; }
        public string S9 { get; set; }
        public string S10 { get; set; }
        public string ScoreIfNoMatch { get; set; }
    }
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);

"could not find stored procedure"

If the error message only occurs locally, try opening the sql file and press the play button.

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

Delete statement in SQL is very slow

  1. Disable CONSTRAINT

    ALTER TABLE [TableName] NOCHECK CONSTRAINT ALL;

  2. Disable Index

    ALTER INDEX ALL ON [TableName] DISABLE;

  3. Rebuild Index

    ALTER INDEX ALL ON [TableName] REBUILD;

  4. Enable CONSTRAINT

    ALTER TABLE [TableName] CHECK CONSTRAINT ALL;

  5. Delete again

TypeError: 'dict_keys' object does not support indexing

Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:

next(iter(keys))

Or, if you want to iterate over all items, you can use:

items = iter(keys)
while True:
    try:
        item = next(items)
    except StopIteration as e:
        pass # finish

Your branch is ahead of 'origin/master' by 3 commits

This happened to me once after I merged a pull request on Bitbucket.

I just had to do:

git fetch

My problem was solved. I hope this helps!!!

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

This is all perfectly normal. Microsoft added sequences in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.

If you want to have the old behaviour, you can:

  1. use trace flag 272 - this will cause a log record to be generated for each generated identity value. The performance of identity generation may be impacted by turning on this trace flag.
  2. use a sequence generator with the NO CACHE setting (http://msdn.microsoft.com/en-us/library/ff878091.aspx)

How to enable native resolution for apps on iPhone 6 and 6 Plus?

If you are using asset catalogs, go to the LaunchImages asset catalog and add the new launch images for the two new iPhones. You may need to right-click and choose "Add New Launch Image" to see a place to add the new images.

The iPhone 6 (Retina HD 4.7) requires a portrait launch image of 750 x 1334.

The iPhone 6 Plus (Retina HD 5.5) requires both portrait and landscape images sized as 1242 x 2208 and 2208 x 1242 respectively.

Summernote image upload

This code worked well with new version (v0.8.12) (2019-05-21)

$('#summernote').summernote({
        callbacks: {
            onImageUpload: function(files) {
                for(let i=0; i < files.length; i++) {
                    $.upload(files[i]);
                }
            }
        },
        height: 500,
    });

    $.upload = function (file) {
        let out = new FormData();
        out.append('file', file, file.name);

        $.ajax({
            method: 'POST',
            url: 'upload.php',
            contentType: false,
            cache: false,
            processData: false,
            data: out,
            success: function (img) {
                $('#summernote').summernote('insertImage', img);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(textStatus + " " + errorThrown);
            }
        });
    };

PHP Code (upload.php)

if ($_FILES['file']['name']) {
 if (!$_FILES['file']['error']) {
    $name = md5(rand(100, 200));
    $ext = explode('.', $_FILES['file']['name']);
    $filename = $name . '.' . $ext[1];
    $destination = 'images/' . $filename; //change this directory
    $location = $_FILES["file"]["tmp_name"];
    move_uploaded_file($location, $destination);
    echo 'images/' . $filename;//change this URL
 }
 else
 {
  echo  $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['file']['error'];
 }
}

Set the Value of a Hidden field using JQuery

The selector should not be #input. That means a field with id="input" which is not your case. You want:

$('#chag_sort').val(sort2);

Or if your hidden input didn't have an unique id but only a name="chag_sort":

$('input[name="chag_sort"]').val(sort2);

How to remove anaconda from windows completely?

To use Uninstall-Anaconda.exe in C:\Users\username\Anaconda3 is a good way.

EC2 Instance Cloning

You can use AWS API or console UI to create an AMI(Amazon Machine Image) of your running instance. You can specify to reboot the instance when create your AMI. Then you can use AWS API or console UI to launch more instances with the AMI you created.

Is it possible to write to the console in colour in .NET?

class Program
{
    static void Main()
    {
        Console.BackgroundColor = ConsoleColor.Blue;
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("White on blue.");
        Console.WriteLine("Another line.");
        Console.ResetColor();
    }
}

Taken from here.

Can I use Objective-C blocks as properties?

Of course you could use blocks as properties. But make sure they are declared as @property(copy). For example:

typedef void(^TestBlock)(void);

@interface SecondViewController : UIViewController
@property (nonatomic, copy) TestBlock block;
@end

In MRC, blocks capturing context variables are allocated in stack; they will be released when the stack frame is destroyed. If they are copied, a new block will be allocated in heap, which can be executed later on after the stack frame is poped.

git pull error "The requested URL returned error: 503 while accessing"

Try disabling all the system wide HTTP and HTTPS proxies:

export http_proxy="" 
export https_proxy=""
export HTTP_PROXY=""
export HTTPS_PROXY=""

Compare one String with multiple values in one expression

For those who came here for exact equality checks (not ignoring case), I find that

if (Arrays.asList(str1, str2, str3).contains(strToCheck)) {
    ...
}

is one of, if the most concise solution, and is available on Java 7.

How do you implement a good profanity filter?

Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?

Also, one can't forget The Untold History of Toontown's SpeedChat, where even using a "safe-word whitelist" resulted in a 14 year old quickly circumventing it with: "I want to stick my long-necked Giraffe up your fluffy white bunny."

Bottom line: Ultimately, for any system that you implement, there is absolutely no substitute for human review (whether peer or otherwise). Feel free to implement a rudimentary tool to get rid of the drive-by's, but for the determined troll, you absolutely must have a non-algorithm-based approach.

A system that removes anonymity and introduces accountability (something that Stack Overflow does well) is helpful also, particularly in order to help combat John Gabriel's G.I.F.T.

You also asked where you can get profanity lists to get you started -- one open-source project to check out is Dansguardian -- check out the source code for their default profanity lists. There is also an additional third party Phrase List that you can download for the proxy that may be a helpful gleaning point for you.

Edit in response the question edit: Thanks for the clarification on what you're trying to do. In that case, if you're just trying to do a simple word filter, there are two ways you can do it. One is to create a single long regexp with all of the banned phrases that you want to censor, and merely do a regex find/replace with it. A regex like:

$filterRegex = "(boogers|snot|poop|shucks|argh)"

and run it on your input string using preg_match() to wholesale test for a hit,

or preg_replace() to blank them out.

You can also load those functions up with arrays rather than a single long regex, and for long word lists, it may be more manageable. See the preg_replace() for some good examples as to how arrays can be used flexibly.

For additional PHP programming examples, see this page for a somewhat advanced generic class for word filtering that *'s out the center letters from censored words, and this previous Stack Overflow question that also has a PHP example (the main valuable part in there is the SQL-based filtered word approach -- the leet-speak compensator can be dispensed with if you find it unnecessary).

You also added: "Getting the list of words in the first place is the real question." -- in addition to some of the previous Dansgaurdian links, you may find this handy .zip of 458 words to be helpful.

Correct way to initialize HashMap and can HashMap hold different value types?

Eclipse is recommending that you declare the type of the HashMap because that enforces some type safety. Of course, it sounds like you're trying to avoid type safety from your second part.

If you want to do the latter, try declaring map as HashMap<String,Object>.

JavaScript moving element in the DOM

var swap = function () {
    var divs = document.getElementsByTagName('div');
    var div1 = divs[0];
    var div2 = divs[1];
    var div3 = divs[2];

    div3.parentNode.insertBefore(div1, div3);
    div1.parentNode.insertBefore(div3, div2);
};

This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.

What standards peculiarities does it rely on?

insertBefore Inserts the node newChild before the existing child node refChild. If refChild is null, insert newChild at the end of the list of children. If newChild is a DocumentFragment object, all of its children are inserted, in the same order, before refChild. If the newChild is already in the tree, it is first removed.

rsync: difference between --size-only and --ignore-times

The short answer is that --ignore-times does more than its name implies. It ignores both the time and size. In contrast, --size-only does exactly what it says.


The long answer is that rsync has three ways to decide if a file is outdated:

  1. Compare the size of source and destination.
  2. Compare the timestamp of source and destination.
  3. Compare the static checksum of source and destination.

These checks are performed before transferring data. Notably, this means the static checksum is distinct from the stream checksum - the later is computed while transferring data.

By default, rsync uses only 1 and 2. Both 1 and 2 can be acquired together by a single stat, whereas 3 requires reading the entire file (this is independent from reading the file for transfer). Assuming only one modifier is specified, that means the following:

  • By using --size-only, only 1 is performed - timestamps and checksum are ignored. A file is copied unless its size is identical on both ends.

  • By using --ignore-times, neither of 1, 2 or 3 is performed. A file is always copied.

  • By using --checksum, 3 is used in addition to 1, but 2 is not performed. A file is copied unless size and checksum match. The checksum is only computed if size matches.

How does Java resolve a relative path in new File()?

Only slightly related to the question, but try to wrap your head around this one. So un-intuitive:

import java.nio.file.*;
class Main {
  public static void main(String[] args) {
    Path p1 = Paths.get("/personal/./photos/./readme.txt");
    Path p2 = Paths.get("/personal/index.html");
    Path p3 = p1.relativize(p2);
    System.out.println(p3); //prints  ../../../../index.html  !!
  }
}

Webfont Smoothing and Antialiasing in Firefox and Opera

Adding

font-weight: normal;

To your @font-face fonts will fix the bold appearance in Firefox.

Compare two different files line by line in python

I have just been faced with the same challenge, but I thought "Why programming this in Python if you can solve it with a simple "grep"?, which led to the following Python code:

import subprocess
from subprocess import PIPE

try:
  output1, errors1 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file1.txt", "c:\\file2.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  output2, errors2 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file2.txt", "c:\\file1.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  if (len(output1) + len(output2) + len(errors1) + len(errors2) > 0):
    print ("Compare result : There are differences:");
    if (len(output1) + len(output2) > 0):
      print ("  Output differences : ");
      print (output1);
      print (output2);
    if (len(errors1) + len(errors2) > 0):
      print (" Errors : ");
      print (errors1);
      print (errors2);
  else:
    print ("Compare result : Both files are equal");
except Exception as ex:
  print("Compare result : Exception during comparison");
  print(ex);
  raise;

The trick behind this is the following: grep -Fvf file1.txt file2.txt verifies if all entries in file2.txt are present in file1.txt. By doing this in both directions we can see if the content of both files are "equal". I put "equal" between quotes because duplicate lines are disregarded in this way of working.

Obviously, this is just an example: you can replace grep by any commandline file comparison tool.

How do I parse JSON with Ruby on Rails?

You can try something like this:

def details_to_json
{
  :id                    => self.id, 
  :credit_period_type    => self.credit_period_type,
  :credit_payment_period => self.credit_payment_period,

 }.to_json
end

Error: Java: invalid target release: 11 - IntelliJ IDEA

My project module was set to 8 but the pom.xml was set to 11. When I changed from 8 to 11 in the module, it worked.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

i'am using react-native and this works for me :

  1. in root of project cd android and gradlew clean
  2. open task manager in windows
  3. on tab 'Details' hit endtask on both java.exe proccess

long story short > Task :app:installDebug FAILED Fixed by kiling java.exe prossess

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

In the first plate you have to check that:

  • 1) You install a appropriate version of Crystal Reports SDK => http://downloads.i-theses.com/index.php?option=com_downloads&task=downloads&groupid=9&id=101 (for example)
  • 2) Add reference to dll => crystaldecisions.reportappserver.commlayer.dll

How to get the mouse position without events (without moving the mouse)?

@Tim Down's answer is not performant if you render 2,000 x 2,000 <a> elements:

OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 elements (so that the :hover pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover rule for those elements that changes a property (let's say font-family). In your load handler, cycle through each of the 4 million elements, checking currentStyle / getComputedStyle() until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.

N.B. DON'T DO THIS.

But you don't have to render 4 million elements at once, instead use binary search. Just use 4 <a> elements instead:

  • Step 1: Consider the whole screen as the starting search area
  • Step 2: Split the search area into 2 x 2 = 4 rectangle <a> elements
  • Step 3: Using the getComputedStyle() function determine in which rectangle mouse hovers
  • Step 4: Reduce the search area to that rectangle and repeat from step 2.

This way you would need to repeat these steps max 11 times, considering your screen is not wider than 2048px.

So you will generate max 11 x 4 = 44 <a> elements.

If you don't need to determine the mouse position exactly to a pixel, but say 10px precision is OK. You would repeat the steps at most 8 times, so you would need to draw max 8 x 4 = 32 <a> elements.

Also generating and then destroying the <a> elements is not performat as DOM is generally slow. Instead, you can just reuse the initial 4 <a> elements and just adjust their top, left, width and height as you loop through steps.

Now, creating 4 <a> is an overkill as well. Instead, you can reuse the same one <a> element for when testing for getComputedStyle() in each rectangle. So, instead of splitting the search area into 2 x 2 <a> elements just reuse a single <a> element by moving it with top and left style properties.

So, all you need is a single <a> element change its width and height max 11 times, and change its top and left max 44 times and you will have the exact mouse position.

Parse JSON String into a Particular Object Prototype in JavaScript

While, this is not technically what you want, if you know before hand the type of object you want to handle you can use the call/apply methods of the prototype of your known object.

you can change this

alert(fooJSON.test() ); //Prints 12

to this

alert(Foo.prototype.test.call(fooJSON); //Prints 12

Getting a HeadlessException: No X11 DISPLAY variable was set

I assume you're trying to tunnel into some unix box.

Make sure X11 forwarding is enabled in your PuTTY settings.

enter image description here

Excel how to fill all selected blank cells with text

Here's a tricky way to do this - select the cells that you want to replace and in Excel 2010 select F5 to bring up the "goto" box. Hit the "special" button. Select "blanks" - this should select all the cells that are blank. Enter NULL or whatever you want in the formula box and hit ctrl + enter to apply to all selected cells. Easy!

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

How can I have grep not print out 'No such file or directory' errors?

If you are grepping through a git repository, I'd recommend you use git grep. You don't need to pass in -R or the path.

git grep pattern

That will show all matches from your current directory down.

How can I easily view the contents of a datatable or dataview in the immediate window

Give Xml Visualizer a try. Haven't tried the latest version yet, but I can't work without the previous one in Visual Studio 2003.

on top of displaying DataSet hierarchically, there are also a lot of other handy features such as filtering and selecting the RowState which you want to view.

Git Stash vs Shelve in IntelliJ IDEA

Shelf is a JetBrains feature while Stash is a Git feature for same work. You can switch to different branch without commit and loss of work using either of features. My personal experience is to use Shelf.

What's the console.log() of java?

Use the Android logging utility.

http://developer.android.com/reference/android/util/Log.html

Log has a bunch of static methods for accessing the different log levels. The common thread is that they always accept at least a tag and a log message.

Tags are a way of filtering output in your log messages. You can use them to wade through the thousands of log messages you'll see and find the ones you're specifically looking for.

You use the Log functions in Android by accessing the Log.x objects (where the x method is the log level). For example:

Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Log.e("MyTagGoesHere", "This is my log message at the error level here");

I usually make it a point to make the tag my class name so I know where the log message was generated too. Saves a lot of time later on in the game.

You can see your log messages using the logcat tool for android:

adb logcat

Or by opening the eclipse Logcat view by going to the menu bar

Window->Show View->Other then select the Android menu and the LogCat view

Duplicate headers received from server

The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.

For example:

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

Date validation with ASP.NET validator

Best option would be

Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:

<asp:CompareValidator
    id="dateValidator" runat="server" 
    Type="Date"
    Operator="DataTypeCheck"
    ControlToValidate="txtDatecompleted" 
    ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

Rules for C++ string literals escape character

\a is the bell/alert character, which on some systems triggers a sound. \nnn, represents an arbitrary ASCII character in octal base. However, \0 is special in that it represents the null character no matter what.

To answer your original question, you could escape your '0' characters as well, as:

std::string ("\060\000\060", 3);

(since an ASCII '0' is 60 in octal)

The MSDN documentation has a pretty detailed article on this, as well cppreference

Print second last column/field in awk

Did you tried to start from right to left by using the rev command ? In this case you just need to print the 2nd column:

seq 12 | xargs -n5 | rev | awk '{ print $2}' | rev
4
9
11

Setting up redirect in web.config file

You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect. You could then make a rule like this:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Rewrite to Category">
        <match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
        <action type="Rewrite" url="category.aspx?cid={R:2}" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

What should main() return in C and C++?

The return value can be used by the operating system to check how the program was closed.

Return value 0 usually means OK in most operating systems (the ones I can think of anyway).

It also can be checked when you call a process yourself, and see if the program exited and finished properly.

It's NOT just a programming convention.

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

compile function -

  1. is called before the controller and link function.
  2. In compile function, you have the original template DOM so you can make changes on original DOM before AngularJS creates an instance of it and before a scope is created
  3. ng-repeat is perfect example - original syntax is template element, the repeated elements in HTML are instances
  4. There can be multiple element instances and only one template element
  5. Scope is not available yet
  6. Compile function can return function and object
  7. returning a (post-link) function - is equivalent to registering the linking function via the link property of the config object when the compile function is empty.
  8. returning an object with function(s) registered via pre and post properties - allows you to control when a linking function should be called during the linking phase. See info about pre-linking and post-linking functions below.

syntax

function compile(tElement, tAttrs, transclude) { ... }

controller

  1. called after the compile function
  2. scope is available here
  3. can be accessed by other directives (see require attribute)

pre - link

  1. The link function is responsible for registering DOM listeners as well as updating the DOM. It is executed after the template has been cloned. This is where most of the directive logic will be put.

  2. You can update the dom in the controller using angular.element but this is not recommended as the element is provided in the link function

  3. Pre-link function is used to implement logic that runs when angular js has already compiled the child elements but before any of the child element's post link have been called

post-link

  1. directive that only has link function, angular treats the function as a post link

  2. post will be executed after compile, controller and pre-link funciton, so that's why this is considered the safest and default place to add your directive logic

In a Git repository, how to properly rename a directory?

From Web Application I think you can't, but you can rename all the folders in Git Client, it will move your files in the new renamed folders, than commit and push to remote repository.

I had a very similar issue: I had to rename different folders from uppercase to lowercase (like Abc -> abc), I've renamed all the folders with a dummy name (like 'abc___') and than committed to remote repository, after that I renamed all the folders to the original name with the lowercase (like abc) and it took them!

How to select some rows with specific rownames from a dataframe?

df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <-  letters[1:10]
df[c('a','b'),]

Hibernate SessionFactory vs. JPA EntityManagerFactory

I prefer the JPA2 EntityManager API over SessionFactory, because it feels more modern. One simple example:

JPA:

@PersistenceContext
EntityManager entityManager;

public List<MyEntity> findSomeApples() {
  return entityManager
     .createQuery("from MyEntity where apples=7", MyEntity.class)
     .getResultList();
}

SessionFactory:

@Autowired
SessionFactory sessionFactory;

public List<MyEntity> findSomeApples() {
  Session session = sessionFactory.getCurrentSession();
  List<?> result = session.createQuery("from MyEntity where apples=7")
      .list();
  @SuppressWarnings("unchecked")
  List<MyEntity> resultCasted = (List<MyEntity>) result;
  return resultCasted;
}

I think it's clear that the first one looks cleaner and is also easier to test because EntityManager can be easily mocked.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.

Change the color of a bullet in a html list?

This was impossible in 2008, but it's becoming possible soon (hopefully)!

According to The W3C CSS3 specification, you can have full control over any number, glyph, or other symbol generated before a list item with the ::marker pseudo-element. To apply this to the most voted answer's solution:

<ul>
  <li>item #1</li>
  <li>item #2</li>
  <li>item #3</li>
</ul>

li::marker {
  color: red; /* bullet color */
}
li {
  color: black /* text color */
}

JSFiddle Example

Note, though, that as of July 2016, this solution is only a part of the W3C Working Draft and does not work in any major browsers, yet.

If you want this feature, do these:

Git status shows files as changed even though contents are the same

However, a lot (if not every) file appears as modified even though the contents are exactly the same.

With git 2.8 (March 2016), you will able to quickly check if those changes are eol-related.

If that is the case, Devin G Rhode adds in the comments:

I solved this again by adding a .gitattributes file to a repo with just * text=auto inside of it

For the check, see commit a7630bd (16 Jan 2016) by Torsten Bögershausen (tboegi).
(Merged by Junio C Hamano -- gitster -- in commit 05f1539, 03 Feb 2016)

ls-files: add eol diagnostics

When working in a cross-platform environment, a user may want to check if text files are stored normalized in the repository and if .gitattributes are set appropriately.

Make it possible to let Git show the line endings in the index and in the working tree and the effective text/eol attributes.

The end of line ("eolinfo") are shown like this:

"-text"        binary (or with bare CR) file
"none"         text file without any EOL
"lf"           text file with LF
"crlf"         text file with CRLF
"mixed"        text file with mixed line endings.

The effective text/eol attribute is one of these:

"", "-text", "text", "text=auto", "text eol=lf", "text eol=crlf"

git ls-files --eol gives an output like this:

i/none   w/none   attr/text=auto      t/t5100/empty
i/-text  w/-text  attr/-text          t/test-binary-2.png
i/lf     w/lf     attr/text eol=lf    t/t5100/rfc2047-info-0007
i/lf     w/crlf   attr/text eol=crlf  doit.bat
i/mixed  w/mixed  attr/               locale/XX.po

to show what eol convention is used in the data in the index ('i'), and in the working tree ('w'), and what attribute is in effect, for each path that is shown.

How to pretty print nested dictionaries?

I took sth's answer and modified it slightly to fit my needs of a nested dictionaries and lists:

def pretty(d, indent=0):
    if isinstance(d, dict):
        for key, value in d.iteritems():
            print '\t' * indent + str(key)
            if isinstance(value, dict) or isinstance(value, list):
                pretty(value, indent+1)
            else:
                print '\t' * (indent+1) + str(value)
    elif isinstance(d, list):
        for item in d:
            if isinstance(item, dict) or isinstance(item, list):
                pretty(item, indent+1)
            else:
                print '\t' * (indent+1) + str(item)
    else:
        pass

Which then gives me output like:

>>> 
xs:schema
    @xmlns:xs
        http://www.w3.org/2001/XMLSchema
    xs:redefine
        @schemaLocation
            base.xsd
        xs:complexType
            @name
                Extension
            xs:complexContent
                xs:restriction
                    @base
                        Extension
                    xs:sequence
                        xs:element
                            @name
                                Policy
                            @minOccurs
                                1
                            xs:complexType
                                xs:sequence
                                    xs:element
                                            ...

Python executable not finding libpython shared library

On Solaris 11

Use LD_LIBRARY_PATH_64 to resolve symlink to python libs.

In my case for python3.6 LD_LIBRARY_PATH didn't work but LD_LIBRARY_PATH_64 did.

Hope this helps.
Regards

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Fatal error: Namespace declaration statement has to be the very first statement in the script in

There is a mistake in its source. Check out its source if you may. It reads like this

<?php
    class BulletProofException extends Exception{}

    namespace BulletProof;
    ....

That is insane. Personally, I'd say the code is well documented, and elegant, but the author missed a simple point; he declared the namespace within the class. Namespace whenever used should be the first statement.

Too bad I am not in Github; could have pulled a request otherwise :(

How do I get the current GPS location programmatically in Android?

I have made a project from which we can get the accurate location using Google Play Services, GPS and Network providers. This project can be found here.

Strategy in finding the best location is that first get the location from google play services if location is found then check weather it is better or not, if location found is null restart google play services and try to fetch the location from Android Location API. Register the location on change listeners and when ever the better location is found the call back returns it to the main activity.

It is very simple to use and implement in code only two classes we need to embed i.e. LocationManagerInterface and SmartLocationManager, LocationActivity is implementing the interface and using SmartLocationManager to fetch location.

/**
 * Created by Syed Raza Mehdi Naqvi on 8/10/2016.
 */
public interface LocationManagerInterface {
    String TAG = LocationManagerInterface.class.getSimpleName();

    void locationFetched(Location mLocation, Location oldLocation, String time, String locationProvider);

}

here is the location manager class

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.text.DateFormat;
import java.util.Date;

/**
 * Created by Syed Raza Mehdi Naqvi on 8/9/2016.
 */
public class SmartLocationManager implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private static final String TAG = SmartLocationManager.class.getSimpleName();

    private static final int TWO_MINUTES = 1000 * 60 * 2;
    private static final int PERMISSION_REQUEST_CODE = 1000;
    private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    // default value is false but user can change it
    private String mLastLocationUpdateTime;                                                         // fetched location time
    private String locationProvider;                                                                // source of fetched location

    private Location mLastLocationFetched;                                                          // location fetched
    private Location mLocationFetched;                                                              // location fetched
    private Location networkLocation;
    private Location gpsLocation;

    private int mLocationPiority;
    private long mLocationFetchInterval;
    private long mFastestLocationFetchInterval;

    private Context mContext;                                                                       // application context
    private Activity mActivity;                                                                     // activity context
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private LocationManagerInterface mLocationManagerInterface;

    private android.location.LocationManager locationManager;
    private android.location.LocationListener locationListener;

    boolean isGPSEnabled;
    boolean isNetworkEnabled;

    private int mProviderType;
    public static final int NETWORK_PROVIDER = 1;
    public static final int ALL_PROVIDERS = 0;
    public static final int GPS_PROVIDER = 2;

//    private final double STANDARD_LOCATION_ACCURACY = 100.0;
//    private final double STANDARD_LOCATION_SEED_LIMIT = 6.95;

    public static final int LOCATION_PROVIDER_ALL_RESTICTION = 1;
    public static final int LOCATION_PROVIDER_RESTRICTION_NONE = 0;
    public static final int LOCATION_PROVIDER_GPS_ONLY_RESTICTION = 2;
    public static final int LOCATION_PROVIDER_NETWORK_ONLY_RESTICTION = 3;
    private int mForceNetworkProviders = 0;

    public SmartLocationManager(Context context, Activity activity, LocationManagerInterface locationInterface, int providerType, int locationPiority, long locationFetchInterval, long fastestLocationFetchInterval, int forceNetworkProviders) {
        mContext = context;
        mActivity = activity;
        mProviderType = providerType;

        mLocationPiority = locationPiority;
        mForceNetworkProviders = forceNetworkProviders;
        mLocationFetchInterval = locationFetchInterval;
        mFastestLocationFetchInterval = fastestLocationFetchInterval;

        mLocationManagerInterface = locationInterface;

        initSmartLocationManager();
    }


    public void initSmartLocationManager() {

        // 1) ask for permission for Android 6 above to avoid crash
        // 2) check if gps is available
        // 3) get location using awesome strategy

        askLocationPermission();                            // for android version 6 above
        checkNetworkProviderEnable(mForceNetworkProviders);                       //

        if (isGooglePlayServicesAvailable())                // if googleplay services available
            initLocationObjts();                            // init obj for google play service and start fetching location
        else
            getLocationUsingAndroidAPI();                   // otherwise get location using Android API
    }

    private void initLocationObjts() {
        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(mLocationPiority)
                .setInterval(mLocationFetchInterval)                    // 10 seconds, in milliseconds
                .setFastestInterval(mFastestLocationFetchInterval);     // 1 second, in milliseconds

        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(mActivity)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

        startLocationFetching();                                        // connect google play services to fetch location
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        startLocationUpdates();
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            getLocationUsingAndroidAPI();
        } else {
            setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location == null) {
            getLastKnownLocation();
        } else {
            setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection suspended");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(mActivity, CONNECTION_FAILURE_RESOLUTION_REQUEST); // Start an Activity that tries to resolve the error
                getLocationUsingAndroidAPI();                                                                // try to get location using Android API locationManager
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    private void setNewLocation(Location location, Location oldLocation) {
        if (location != null) {
            mLastLocationFetched = oldLocation;
            mLocationFetched = location;
            mLastLocationUpdateTime = DateFormat.getTimeInstance().format(new Date());
            locationProvider = location.getProvider();
            mLocationManagerInterface.locationFetched(location, mLastLocationFetched, mLastLocationUpdateTime, location.getProvider());
        }
    }

    private void getLocationUsingAndroidAPI() {
        // Acquire a reference to the system Location Manager
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

        setLocationListner();
        captureLocation();
    }

    public void captureLocation() {
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        try {
            if (mProviderType == SmartLocationManager.GPS_PROVIDER) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            } else if (mProviderType == SmartLocationManager.NETWORK_PROVIDER) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
            } else {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    private void setLocationListner() {
        // Define a listener that responds to location updates
        locationListener = new android.location.LocationListener() {
            public void onLocationChanged(Location location) {
                // Called when a new location is found by the network location provider.
                if (location == null) {
                    getLastKnownLocation();
                } else {
                    setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
//                    if (isLocationAccurate(location) && location.getAccuracy() < STANDARD_LOCATION_ACCURACY && location.getSpeed() < STANDARD_LOCATION_SEED_LIMIT) {// no use of this if
//                        setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
//                    } else {
//                        setNewLocation(getBetterLocation(location, mLocationFetched), mLocationFetched);
//                    }
                }
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }
        };
    }

    public Location getAccurateLocation() {
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        try {
            gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Location newLocalGPS, newLocalNetwork;
            if (gpsLocation != null || networkLocation != null) {
                newLocalGPS = getBetterLocation(mLocationFetched, gpsLocation);
                newLocalNetwork = getBetterLocation(mLocationFetched, networkLocation);
                setNewLocation(getBetterLocation(newLocalGPS, newLocalNetwork), mLocationFetched);
            }
        } catch (Exception ex) {
            Log.e(TAG, ex.getMessage());
        }
        return mLocationFetched;
    }

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    public void startLocationFetching() {
        mGoogleApiClient.connect();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
        }
    }

    public void pauseLocationFetching() {
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }

    }

    public void abortLocationFetching() {
        mGoogleApiClient.disconnect();

        // Remove the listener you previously added
        if (locationManager != null && locationListener != null) {
            if (Build.VERSION.SDK_INT >= 23 &&
                    ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            try {
                locationManager.removeUpdates(locationListener);
                locationManager = null;
            } catch (Exception ex) {
                Log.e(TAG, ex.getMessage());

            }
        }
    }

    public void resetLocation() {
        mLocationFetched = null;
        mLastLocationFetched = null;
        networkLocation = null;
        gpsLocation = null;
    }

    //  Android M Permission check
    public void askLocationPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


            if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    ) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.ACCESS_COARSE_LOCATION)
                        || ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.ACCESS_FINE_LOCATION)) {

                    final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setMessage("Please allow all permissions in App Settings for additional functionality.")
                            .setCancelable(false)
                            .setPositiveButton("Allow", new DialogInterface.OnClickListener() {
                                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                                    Toast.makeText(mContext, "Welcome", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .setNegativeButton("Deny", new DialogInterface.OnClickListener() {
                                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                                    mActivity.finish();
                                }
                            });
                    final AlertDialog alert = builder.create();
                    alert.show();

                } else
                    ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION
                            , Manifest.permission.ACCESS_FINE_LOCATION
                    }, PERMISSION_REQUEST_CODE);

            }
        }
    }

    public void checkNetworkProviderEnable(int enforceActive) {
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            buildAlertMessageTurnOnLocationProviders("Your location providers seems to be disabled, please enable it", "OK", "Cancel");
        } else if (!isGPSEnabled && mForceNetworkProviders == LOCATION_PROVIDER_GPS_ONLY_RESTICTION) {
            buildAlertMessageTurnOnLocationProviders("Your GPS seems to be disabled, please enable it", "OK", "Cancel");
        } else if (!isNetworkEnabled && mForceNetworkProviders == LOCATION_PROVIDER_NETWORK_ONLY_RESTICTION) {
            buildAlertMessageTurnOnLocationProviders("Your Network location provider seems to be disabled, please enable it", "OK", "Cancel");
        }
        // getting network status

        if (!isGPSEnabled && !isNetworkEnabled) {
            Toast.makeText(mContext, "Location can't be fetched!", Toast.LENGTH_SHORT).show(); // show alert
            mActivity.finish();
        }
    }

    private void buildAlertMessageTurnOnLocationProviders(String message, String positiveButtonText, String negativeButtonText) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setMessage(message)
                .setCancelable(false)
                .setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        Intent mIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(mIntent);
                    }
                })
                .setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        mActivity.finish();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }


    public Location getLastKnownLocation() {
        locationProvider = LocationManager.NETWORK_PROVIDER;
        Location lastKnownLocation = null;
        // Or use LocationManager.GPS_PROVIDER
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return lastKnownLocation;
        }
        try {
            lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
            return lastKnownLocation;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return lastKnownLocation;
    }

    public boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);

        if (status == ConnectionResult.SUCCESS) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Determines whether one Location reading is better than the current Location fix
     *
     * @param location            The new Location that you want to evaluate
     * @param currentBestLocation The current Location fix, to which you want to compare the new one
     */
    protected Location getBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return location;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return location;
            // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder) {
            return currentBestLocation;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return location;
        } else if (isNewer && !isLessAccurate) {
            return location;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return location;
        }
        return currentBestLocation;
    }

    /**
     * Checks whether two providers are the same
     */

    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }

    public boolean isLocationAccurate(Location location) {
        if (location.hasAccuracy()) {
            return true;
        } else {
            return false;
        }
    }

    public Location getStaleLocation() {
        if (mLastLocationFetched != null) {
            return mLastLocationFetched;
        }
        if (Build.VERSION.SDK_INT >= 23 &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        if (mProviderType == SmartLocationManager.GPS_PROVIDER) {
            return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else if (mProviderType == SmartLocationManager.NETWORK_PROVIDER) {
            return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            return getBetterLocation(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER), locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
        }
    }
}

we can use it with activity or a fragment, here i am using it with activity

import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.example.raza.locationaware.location.LocationManagerInterface;
import com.example.raza.locationaware.location.SmartLocationManager;
import com.google.android.gms.location.LocationRequest;

public class LocationActivity extends AppCompatActivity implements LocationManagerInterface {

    public static final String TAG = LocationActivity.class.getSimpleName();

    SmartLocationManager mLocationManager;
    TextView mLocalTV, mLocationProviderTV, mlocationTimeTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        mLocationManager = new SmartLocationManager(getApplicationContext(), this, this, SmartLocationManager.ALL_PROVIDERS, LocationRequest.PRIORITY_HIGH_ACCURACY, 10 * 1000, 1 * 1000, SmartLocationManager.LOCATION_PROVIDER_RESTRICTION_NONE); // init location manager
        mLocalTV = (TextView) findViewById(R.id.locationDisplayTV);
        mLocationProviderTV = (TextView) findViewById(R.id.locationProviderTV);
        mlocationTimeTV = (TextView) findViewById(R.id.locationTimeFetchedTV);
    }

    protected void onStart() {
        super.onStart();
        mLocationManager.startLocationFetching();
    }

    protected void onStop() {
        super.onStop();
        mLocationManager.abortLocationFetching();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mLocationManager.pauseLocationFetching();
    }

    @Override
    public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
        Toast.makeText(getApplication(), "Lat : " + mLocal.getLatitude() + " Lng : " + mLocal.getLongitude(), Toast.LENGTH_LONG).show();
        mLocalTV.setText("Lat : " + mLocal.getLatitude() + " Lng : " + mLocal.getLongitude());
        mLocationProviderTV.setText(locationProvider);
        mlocationTimeTV.setText(time);
    }
}

Hope it helps, if you can suggest any improvement kindly post it on git. Thanks.

How to turn on front flash light programmatically in Android?

I Got AutoFlash light with below simple Three Steps.

  • I just added Camera and Flash Permission in Manifest.xml file
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="android.hardware.camera.flash" android:required="false" />
  • In your Camera Code do this way.

    //Open Camera
    Camera  mCamera = Camera.open(); 
    
    //Get Camera Params for customisation
    Camera.Parameters parameters = mCamera.getParameters();
    
    //Check Whether device supports AutoFlash, If you YES then set AutoFlash
    List<String> flashModes = parameters.getSupportedFlashModes();
    if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO))
    {
         parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
    }
    mCamera.setParameters(parameters);
    mCamera.startPreview();
    
  • Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.

How to replace substrings in windows batch file

To avoid problems with the batch parser (e.g. exclamation point), look at Problem with search and replace batch file.

Following modification of aflat's script will include special characters like exclamation points.

@echo off
setlocal DisableDelayedExpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=

for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
    SET string=%%A
    setlocal EnableDelayedExpansion
    SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!

    >> %OUTTEXTFILE% echo(!modified!
    endlocal
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%

How to change font-color for disabled input?

You can't for Internet Explorer.

See this comment I wrote on a related topic:

There doesn't seem to be a good way, see: How to change color of disabled html controls in IE8 using css - you can set the input to readonly instead, but that has other consequences (such as with readonly, the input will be sent to the server on submit, but with disabled, it won't be): http://jsfiddle.net/wCFBw/40

Also, see: Changing font colour in Textboxes in IE which are disabled

Function vs. Stored Procedure in SQL Server

Write a user-defined function when you want to compute and return a value for use in other SQL statements; write a stored procedure when you want instead is to group a possibly-complex set of SQL statements. These are two pretty different use cases, after all!

Compare two dates in Java

It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:

switch (today.compareTo(questionDate)) {
    case -1:  System.out.println("today is sooner than questionDate");  break;
    case 0:   System.out.println("today and questionDate are equal");  break;
    case 1:   System.out.println("today is later than questionDate");  break;
    default:  System.out.println("Invalid results from date comparison"); break;
}

It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.

Ruby: How to turn a hash into HTTP parameters?

2.6.3 :001 > hash = {:a => "a", :b => ["c", "d", "e"]}
=> {:a=>"a", :b=>["c", "d", "e"]}
2.6.3 :002 > hash.to_a.map { |x| "#{x[0]}=#{x[1].class == Array ? x[1].join(",") : x[1]}" 
}.join("&")
=> "a=a&b=c,d,e"

Set up git to pull and push all branches

To see all the branches with out using git branch -a you should execute:

for remote in `git branch -r`; do git branch --track $remote; done
git fetch --all
git pull --all

Now you can see all the branches:

git branch

To push all the branches try:

git push --all

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

if you are using python3.x and opencv==4.1.0 then use following commands First of all

python -m pip install --user opencv-contrib-python

after that use this in the python script

cv2.face.LBPHFaceRecognizer_create() 

Configure active profile in SpringBoot via Maven

Or rather easily:

mvn spring-boot:run -Dspring-boot.run.profiles={profile_name}

Transfer data between databases with PostgreSQL

From: hxxp://dbaspot.c om/postgresql/348627-pg_dump-t-give-where-condition.html (NOTE: the link is now broken)

# create temp table with the data
psql mydb
CREATE TABLE temp1 (LIKE mytable);
INSERT INTO temp1 SELECT * FROM mytable WHERE myconditions;
\q

# export the data to a sql file
pg_dump --data-only --column-inserts -t temp1 mtdb > out.sql
psql mydb
DROP TABLE temp1;
\q

# import temp1 rows in another database
cat out.sql | psql -d [other_db]
psql other_db
INSERT INTO mytable (SELECT * FROM temp1);
DROP TABLE temp1;

Another method useful in remotes

  # export a table csv and import in another database
  psql-remote> COPY elements TO '/tmp/elements.csv' DELIMITER ',' CSV HEADER;
  $ scp host.com:/tmp/elements.csv /tmp/elements.csv
  psql-local> COPY elements FROM '/tmp/elements.csv' DELIMITER ',' CSV;

Getting byte array through input type = file

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
  binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
      console.log(arrayBuffer);_x000D_
        document.querySelector('#result').innerHTML = arrayBuffer + '  '+arrayBuffer.byteLength;_x000D_
        }_x000D_
    reader.readAsArrayBuffer(this.files[0]);_x000D_
  }, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Can't create handler inside thread which has not called Looper.prepare()

You create handler in background thread this way

private void createHandler() {
        Thread thread = new Thread() {
          public void run() {
               Looper.prepare();

               final Handler handler = new Handler();
               handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // Do Work
                        handler.removeCallbacks(this);
                        Looper.myLooper().quit();
                   }
                }, 2000);

                Looper.loop();
            }
        };
        thread.start();
    }

Get the short Git version hash

Try this:

git rev-parse --short HEAD

The command git rev-parse can do a remarkable number of different things, so you'd need to go through the documentation very carefully to spot that though.

Getting activity from context in android

This method should be helpful..!

public Activity getActivityByContext(Context context){

if(context == null){
    return null;
    }

else if((context instanceof ContextWrapper) && (context instanceof Activity)){
        return (Activity) context;
    }

else if(context instanceof ContextWrapper){
        return getActivity(((ContextWrapper) context).getBaseContext());
    }

return null;

    }

I hope this helps.. Merry coding!

An error occurred while signing: SignTool.exe not found

  1. Solution Explorer
  2. Your app Right Clik
  3. Propatis
  4. Security
  5. Unchek (Enable ClickOnce Security Settings) Thats Solve..... __:)
  6. https://i.stack.imgur.com/62nKZ.png See

[enter image description here]

Upload file to SFTP using PowerShell

Using PuTTY's pscp.exe (which I have in an $env:path directory):

pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

configure Git to accept a particular self-signed server certificate for a particular https remote

OSX User adjustments.

Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.

I put the cert.pem file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.

Configure git to trust this certificate:

$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem

How do I add a custom script to my package.json file that runs a javascript file?

Custom Scripts

npm run-script <custom_script_name>

or

npm run <custom_script_name>

In your example, you would want to run npm run-script script1 or npm run script1.

See https://docs.npmjs.com/cli/run-script

Lifecycle Scripts

Node also allows you to run custom scripts for certain lifecycle events, like after npm install is run. These can be found here.

For example:

"scripts": {
    "postinstall": "electron-rebuild",
},

This would run electron-rebuild after a npm install command.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Ordering by the order of values in a SQL IN() clause

The IN clause describes a set of values, and sets do not have order.

Your solution with a join and then ordering on the display_order column is the most nearly correct solution; anything else is probably a DBMS-specific hack (or is doing some stuff with the OLAP functions in standard SQL). Certainly, the join is the most nearly portable solution (though generating the data with the display_order values may be problematic). Note that you may need to select the ordering columns; that used to be a requirement in standard SQL, though I believe it was relaxed as a rule a while ago (maybe as long ago as SQL-92).

How to create a generic array in Java?

Look also to this code:

public static <T> T[] toArray(final List<T> obj) {
    if (obj == null || obj.isEmpty()) {
        return null;
    }
    final T t = obj.get(0);
    final T[] res = (T[]) Array.newInstance(t.getClass(), obj.size());
    for (int i = 0; i < obj.size(); i++) {
        res[i] = obj.get(i);
    }
    return res;
}

It converts a list of any kind of object to an array of the same type.

m2eclipse error

I also had same problem with Eclipse 3.7.2 (Indigo) and maven 3.0.4.

Eclipse wasn't picking up my maven settings, so this is what I did to fix the problem:

  1. Window - Preferences - Maven - Installations

    • Add (Maven 3.0.4 instead of using Embedded)
    • Click Apply & OK
  2. Maven > Update Project Configuration... on project (right click)

  3. Shutdown Eclipse

  4. Run mvn install from the command line.

  5. Open Eclipse

Those steps worked for me, but the problem isn't consistent. I've only had with issue on one computer.

Maven2: Best practice for Enterprise Project (EAR file)

I've been searching high and low for an end-to-end example of a complete maven-based ear-packaged application and finally stumbled upon this. The instructions say to select option 2 when running through the CLI but for your purposes, use option 1.

Passing by reference in C

Your example works because you are passing the address of your variable to a function that manipulates its value with the dereference operator.

While C does not support reference data types, you can still simulate passing-by-reference by explicitly passing pointer values, as in your example.

The C++ reference data type is less powerful but considered safer than the pointer type inherited from C. This would be your example, adapted to use C++ references:

void f(int &j) {
  j++;
}

int main() {
  int i = 20;
  f(i);
  printf("i = %d\n", i);

  return 0;
}

How to uncheck a radio button?

Try

$(this).removeAttr('checked')

Since a lot of browsers will interpret 'checked=anything' as true. This will remove the checked attribute altogether.

Hope this helps.

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

It happen if there are two more ContextLoaderListener exist in your project.

For ex: in my case 2 ContextLoaderListener was exist using

  1. java configuration
  2. web.xml

So, remove any one ContextLoaderListener from your project and run your application.

POST request with a simple string in body with Alamofire

If you want to post string as raw body in request

return Alamofire.request(.POST, "http://mywebsite.com/post-request" , parameters: [:], encoding: .Custom({
            (convertible, params) in
            let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest

            let data = ("myBodyString" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            mutableRequest.HTTPBody = data
            return (mutableRequest, nil)
        }))

Modulo operator in Python

Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3

Beware of floating point accuracy issues.

What is a smart pointer and when should I use one?

A smart pointer is like a regular (typed) pointer, like "char*", except when the pointer itself goes out of scope then what it points to is deleted as well. You can use it like you would a regular pointer, by using "->", but not if you need an actual pointer to the data. For that, you can use "&*ptr".

It is useful for:

  • Objects that must be allocated with new, but that you'd like to have the same lifetime as something on that stack. If the object is assigned to a smart pointer, then they will be deleted when the program exits that function/block.

  • Data members of classes, so that when the object is deleted all the owned data is deleted as well, without any special code in the destructor (you will need to be sure the destructor is virtual, which is almost always a good thing to do).

You may not want to use a smart pointer when:

  • ... the pointer shouldn't actually own the data... i.e., when you are just using the data, but you want it to survive the function where you are referencing it.
  • ... the smart pointer isn't itself going to be destroyed at some point. You don't want it to sit in memory that never gets destroyed (such as in an object that is dynamically allocated but won't be explicitly deleted).
  • ... two smart pointers might point to the same data. (There are, however, even smarter pointers that will handle that... that is called reference counting.)

See also:

How do I get the current username in .NET using C#?

String myUserName = Environment.UserName

This will give you output - your_user_name

How do you easily create empty matrices javascript?

For a 2-d matrix I'd do the following

var data = Array(9 * 9).fill(0);
var index = (i,j) => 9*i + j;
//any reference to an index, eg. (3,4) can be done as follows
data[index(3,4)]; 

You can replace 9 with any generic ROWS and COLUMNS constants.

How can I extract the folder path from file path in Python?

Here is the code:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

Jquery onclick on div

Nothing.

$('#content').click(function(e) {  
    alert(1);
});

Will bind to an existing HTML element with the ID set to content, and will show a message box on click.

  • Make sure that #content exists before using that code
  • That the ID is unique
  • Check your Javascript console for any errors or issues

How to change the status bar color in Android?

If you want to set a custom drawable file use this code snippet

fun setCustomStatusBar(){
    if (Build.VERSION.SDK_INT >= 21) {
        val decor = window.decorView
        decor.viewTreeObserver.addOnPreDrawListener(object :
            ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                decor.viewTreeObserver.removeOnPreDrawListener(this)
                val statusBar = decor.findViewById<View> 
                  (android.R.id.statusBarBackground)
                statusBar.setBackgroundResource(R.drawable.bg_statusbar)
                return true
            }
        })
    }
}

"FATAL: Module not found error" using modprobe

Try insmod instead of modprobe. Modprobe looks in the module directory /lib/modules/uname -r for all the modules and other files

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

This is due to the different encoding method when read the file. In python, it defaultly encode the data with unicode. However, it may not works in various platforms.

I propose an encoding method which can help you solve this if 'utf-8' not works.

with open(path, newline='', encoding='cp1252') as csvfile:
    reader = csv.reader(csvfile)

It should works if you change the encoding method here. Also, you can find other encoding method here standard-encodings , if above doesn't work for you.

Select 2 columns in one and combine them

Yes, you can combine columns easily enough such as concatenating character data:

select col1 | col 2 as bothcols from tbl ...

or adding (for example) numeric data:

select col1 + col2 as bothcols from tbl ...

In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.

Laravel 5 Application Key

From the line

'key' => env('APP_KEY', 'SomeRandomString'),

APP_KEY is a global environment variable that is present inside the .env file.

You can replace the application key if you trigger

php artisan key:generate

command. This will always generate the new key.

The output may be like this:


Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.

Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.

Base64 encoding should be the default in Laravel 5.4

Note that when you first create your Laravel application, key:generate is automatically called.

If you change the key be aware that passwords saved with Hash::make() will no longer be valid.

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

find section [MySQLi] in your php.ini and add line mysqli.default_charset = "UTF-8". Similar changes my require for section [Pdo_mysql] and [mysqlnd].

Issue seems to be specifically with MySQL version 8.0, and above solution found working with PHP Version 7.2, and solution didn't work with PHP 7.0

How to group an array of objects by key

I love to write it with no dependency/complexity just pure simple js.

_x000D_
_x000D_
const mp = {}
const cars = [
  {
    model: 'Imaginary space craft SpaceX model',
    year: '2025'
  },
  {
    make: 'audi',
    model: 'r8',
    year: '2012'
  },
  {
    make: 'audi',
    model: 'rs5',
    year: '2013'
  },
  {
    make: 'ford',
    model: 'mustang',
    year: '2012'
  },
  {
    make: 'ford',
    model: 'fusion',
    year: '2015'
  },
  {
    make: 'kia',
    model: 'optima',
    year: '2012'
  }
]

cars.forEach(c => {
  if (!c.make) return // exit (maybe add them to a "no_make" category)

  if (!mp[c.make]) mp[c.make] = [{ model: c.model, year: c.year }]
  else mp[c.make].push({ model: c.model, year: c.year })
})

console.log(mp)
_x000D_
_x000D_
_x000D_

How to format LocalDate to string?

With the help of ProgrammersBlock posts I came up with this. My needs were slightly different. I needed to take a string and return it as a LocalDate object. I was handed code that was using the older Calendar and SimpleDateFormat. I wanted to make it a little more current. This is what I came up with.

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;


    void ExampleFormatDate() {

    LocalDate formattedDate = null;  //Declare LocalDate variable to receive the formatted date.
    DateTimeFormatter dateTimeFormatter;  //Declare date formatter
    String rawDate = "2000-01-01";  //Test string that holds a date to format and parse.

    dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;

    //formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
    //First, the rawDate string is formatted according to DateTimeFormatter.  Second, that formatted string is parsed into
    //the LocalDate formattedDate object.
    formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));

}

Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.

What's the key difference between HTML 4 and HTML 5?

From Wikipedia:

  • New parsing rules oriented towards flexible parsing and compatibility
  • New elements – section, video, progress, nav, meter, time, aside, canvas
  • New input attributes – dates and times, email, url
  • New attributes – ping, charset, async
  • Global attributes (that can be applied for every element) – id, tabindex, repeat
  • Deprecated elements dropped – center, font, strike

convert month from name to number

$string = "July";
echo $month_number = date("n",strtotime($string));

returns '7' [month number]

Use date("m",strtotime($string)); for the output "08"

For more formats reffer this..
http://php.net/manual/en/function.date.php

How to scroll the window using JQuery $.scrollTo() function

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

Force GUI update from UI Thread

After updating the UI, start a task to perform with the long running operation:

label.Text = "Please Wait...";

Task<string> task = Task<string>.Factory.StartNew(() =>
{
    try
    {
        SomewhatLongRunningOperation();
        return "Success!";
    }
    catch (Exception e)
    {
        return "Error: " + e.Message;
    }
});
Task UITask = task.ContinueWith((ret) =>
{
    label.Text = ret.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());

This works in .NET 3.5 and later.

How to add jQuery in JS file

it is not possible to import js file inside another js file

The way to use jquery inside js is

import the js in the html or whatever view page you are using inside which you are going to include the js file

view.html

 <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
 <script src="<%=request.getContextPath()%>/js/default.js"></script>

default.js

$('document').ready(function() {
    $('li#user').click(function() {
         $(this).addClass('selectedEmp');
    });
});

this will definitely work for you

hide div tag on mobile view only?

try this

@media handheld{
    #title_message { display: none; }
}

What are the various "Build action" settings in Visual Studio project properties and what do they do?

In VS2008, the doc entry that seems the most useful is:

Windows Presentation Foundation Building a WPF Application (WPF)

ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/wpf_conceptual/html/a58696fd-bdad-4b55-9759-136dfdf8b91c.htm

ApplicationDefinition Identifies the XAML markup file that contains the application definition (a XAML markup file whose root element is Application). ApplicationDefinition is mandatory when Install is true and OutputType is winexe. A WPF application and, consequently, an MSBuild project can only have one ApplicationDefinition.

Page Identifies a XAML markup file whose content is converted to a binary format and compiled into an assembly. Page items are typically implemented in conjunction with a code-behind class.

The most common Page items are XAML files whose top-level elements are one of the following:

Window (System.Windows..::.Window).

Page (System.Windows.Controls..::.Page).

PageFunction (System.Windows.Navigation..::.PageFunction<(Of <(T>)>)).

ResourceDictionary (System.Windows..::.ResourceDictionary).

FlowDocument (System.Windows.Documents..::.FlowDocument).

UserControl (System.Windows.Controls..::.UserControl).

Resource Identifies a resource file that is compiled into an application assembly. As mentioned earlier, UICulture processes Resource items.

Content Identifies a content file that is distributed with an application. Metadata that describes the content file is compiled into the application (using AssemblyAssociatedContentFileAttribute).

How to empty a list in C#?

To give an alternative answer (Who needs 5 equal answers?):

list.Add(5); 
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now

Keep in mind that all other references to the old list have not been cleared (depending on the situation, this might be what you want). Also, in terms of performance, it is usually a bit slower.