Programs & Examples On #Sentinel

A sentinel is a loop exit value or list delimiter whose value is outside the range of valid input, such as -1 for a zero-based array index, or ~ for alphabetic strings.

Return a "NULL" object if search result not found

There are several possible answers here. You want to return something that might exist. Here are some options, ranging from my least preferred to most preferred:

  • Return by reference, and signal can-not-find by exception.

    Attr& getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            throw no_such_attribute_error;
    }

It's likely that not finding attributes is a normal part of execution, and hence not very exceptional. The handling for this would be noisy. A null value cannot be returned because it's undefined behaviour to have null references.

  • Return by pointer

    Attr* getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return &attributes[i];
       //if not found
            return nullptr;
    }

It's easy to forget to check whether a result from getAttribute would be a non-NULL pointer, and is an easy source of bugs.

  • Use Boost.Optional

    boost::optional<Attr&> getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            return boost::optional<Attr&>();
    }

A boost::optional signifies exactly what is going on here, and has easy methods for inspecting whether such an attribute was found.


Side note: std::optional was recently voted into C++17, so this will be a "standard" thing in the near future.

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

In case someone is still struggling with this issue:

I faced similar issue where 2 requests were hitting the server at the same time. There was no situation like below:

T1:
    BEGIN TRANSACTION
    INSERT TABLE A
    INSERT TABLE B
    END TRANSACTION

T2:
    BEGIN TRANSACTION
    INSERT TABLE B
    INSERT TABLE A
    END TRANSACTION

So, I was puzzled why deadlock is happening.

Then I found that there was parent child relation ship between 2 tables because of foreign key. When I was inserting a record in child table, the transaction was acquiring a lock on parent table's row. Immediately after that I was trying to update the parent row which was triggering elevation of lock to EXCLUSIVE one. As 2nd concurrent transaction was already holding a SHARED lock, it was causing deadlock.

Refer to: https://blog.tekenlight.com/2019/02/21/database-deadlock-mysql.html

Search for one value in any column of any table inside a database

I expanded the code, because it's not told me the 'record number', and I must to refind it.

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

-- Copyright @ 2012 Gyula Kulifai. All rights reserved.
-- Extended By: Gyula Kulifai
-- Purpose: To put key values, to exactly determine the position of search
-- Resources: Anatoly Lubarsky
-- Date extension: 19th October 2012 12:24 GMT
-- Tested on: SQL Server 10.0.5500 (SQL Server 2008 SP3)

CREATE TABLE #Results (TableName nvarchar(370), KeyValues nvarchar(3630), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    ,@TableShortName nvarchar(256)
    ,@TableKeys nvarchar(512)
    ,@SQL nvarchar(3830)

SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''

    -- Scan Tables
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
    Set @TableShortName=PARSENAME(@TableName, 1)
    -- print @TableName + ';' + @TableShortName +'!' -- *** DEBUG LINE ***

        -- LOOK Key Fields, Set Key Columns
        SET @TableKeys=''
        SELECT @TableKeys = @TableKeys + '''' + QUOTENAME([name]) + ': '' + CONVERT(nvarchar(250),' + [name] + ') + ''' + ',' + ''' + '
         FROM syscolumns 
         WHERE [id] IN (
            SELECT [id] 
             FROM sysobjects 
             WHERE [name] = @TableShortName)
           AND colid IN (
            SELECT SIK.colid 
             FROM sysindexkeys SIK 
             JOIN sysobjects SO ON 
                SIK.[id] = SO.[id]  
             WHERE 
                SIK.indid = 1
                AND SO.[name] = @TableShortName)
        If @TableKeys<>''
            SET @TableKeys=SUBSTRING(@TableKeys,1,Len(@TableKeys)-8)
        -- Print @TableName + ';' + @TableKeys + '!' -- *** DEBUG LINE ***

    -- Search in Columns
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        ) -- Set ColumnName

        IF @ColumnName IS NOT NULL
        BEGIN
            SET @SQL='
                SELECT 
                    ''' + @TableName + '''
                    ,'+@TableKeys+'
                    ,''' + @ColumnName + '''
                ,LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            --Print @SQL -- *** DEBUG LINE ***
            INSERT INTO #Results
                Exec (@SQL)
        END -- IF ColumnName
    END -- While Table and Column
END --While Table

SELECT TableName, KeyValues, ColumnName, ColumnValue FROM #Results
END

How to install Laravel's Artisan?

in laravel, artisan is a file under root/protected page

for example,

c:\xampp\htdocs\my_project\protected\artisan

you can view the content of "artisan" file with any text editor, it's a php command syntax

so when we type

php artisan

we tell php to run php script in "artisan" file

for example:

php artisan change

will show the change of current laravel version

to see the other option, just type

php artisan

What is the difference between public, private, and protected?

The mentioned keywords are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

Correct way of looping through C++ arrays

sizeof(texts) on my system evaluated to 96: the number of bytes required for the array and its string instances.

As mentioned elsewhere, the sizeof(texts)/sizeof(texts[0]) would give the value of 3 you were expecting.

Checking if a worksheet-based checkbox is checked

It seems that in VBA macro code for an ActiveX checkbox control you use

If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)

and for a Form checkbox control you use

If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)

How can I keep my branch up to date with master with git?

If your branch is local only and hasn't been pushed to the server, use

git rebase master

Otherwise, use

git merge master

bootstrap button shows blue outline when clicked

May be your properties are getting overridden. Try attaching !important to your code along with the :active .

.btn:focus,.btn:active {
   outline: none !important;
   box-shadow: none;
}

Also add box-shadow because otherwise you will still see the shadow around button.

Although this isn't a good practise to use !important I suggest you use more specific class and then try applying the css with the use of !important...

How do I check if an array includes a value in JavaScript?

Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.

As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

Of course, you may as well extend Array prototype:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

And now you can simply use the following:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false

What is the official "preferred" way to install pip and virtualenv systemwide?

There really isn't a single "answer" to this question, but there are definitely some helpful concepts that can help you to come to a decision.

The first question that needs to be answered in your use case is "Do I want to use the system Python?" If you want to use the Python distributed with your operating system, then using the apt-get install method may be just fine. Depending on the operating system distribution method though, you still have to ask some more questions, such as "Do I want to install multiple versions of this package?" If the answer is yes, then it is probably not a good idea to use something like apt. Dpkg pretty much will just untar an archive at the root of the filesystem, so it is up to the package maintainer to make sure the package installs safely under very little assumptions. In the case of most debian packages, I would assume (someone can feel free to correct me here) that they simply untar and provide a top level package.

For example, say the package is "virtualenv", you'd end up with /usr/lib/python2.x/site-packages/virtualenv. If you install it with easy_install you'd get something like /usr/lib/python2.x/site-packages/virtualenv.egg-link that might point to /usr/lib/python2.x/site-packages/virtualenv-1.2-2.x.egg which may be a directory or zipped egg. Pip does something similar although it doesn't use eggs and instead will place the top level package directly in the lib directory.

I might be off on the paths, but the point is that each method takes into account different needs. This is why tools like virtualenv are helpful as they allow you to sandbox your Python libraries such that you can have any combination you need of libraries and versions.

Setuptools also allows installing packages as multiversion which means there is not a singular module_name.egg-link created. To import those packages you need to use pkg_resources and the __import__ function.

Going back to your original question, if you are happy with the system python and plan on using virtualenv and pip to build environments for different applications, then installing virtualenv and / or pip at the system level using apt-get seems totally appropriate. One word of caution though is that if you plan on upgrading your distributions Python, that may have a ripple effect through your virtualenvs if you linked back to your system site packages.

I should also mention that none of these options is inherently better than the others. They simply take different approaches. Using the system version is an excellent way to install Python applications, yet it can be a very difficult way to develop with Python. Easy install and setuptools is very convenient in a world without virtualenv, but if you need to use different versions of the same library, then it also become rather unwieldy. Pip and virtualenv really act more like a virtual machine. Instead of taking care to install things side by side, you just create an whole new environment. The downside here is that 30+ virtualenvs later you might have used up quite bit of diskspace and cluttered up your filesystem.

As you can see, with the many options it is difficult to say which method to use, but with a little investigation into your use cases, you should be able to find a method that works.

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

How to set default values in Rails?

In Ruby on Rails v3.2.8, using the after_initialize ActiveRecord callback, you can call a method in your model that will assign the default values for a new object.

after_initialize callback is triggered for each object that is found and instantiated by a finder, with after_initialize being triggered after new objects are instantiated as well (see ActiveRecord Callbacks).

So, IMO it should look something like:

class Foo < ActiveRecord::Base
  after_initialize :assign_defaults_on_new_Foo
  ...
  attr_accessible :bar
  ...
  private
  def assign_defaults_on_new_Foo
    # required to check an attribute for existence to weed out existing records
    self.bar = default_value unless self.attribute_whose_presence_has_been_validated
  end
end

Foo.bar = default_value for this instance unless the instance contains an attribute_whose_presence_has_been_validated previously on save/update. The default_value will then be used in conjunction with your view to render the form using the default_value for the bar attribute.

At best this is hacky...

EDIT - use 'new_record?' to check if instantiating from a new call

Instead of checking an attribute value, use the new_record? built-in method with rails. So, the above example should look like:

class Foo < ActiveRecord::Base
  after_initialize :assign_defaults_on_new_Foo, if: 'new_record?'
  ...
  attr_accessible :bar
  ...
  private
  def assign_defaults_on_new_Foo
    self.bar = default_value
  end
end

This is much cleaner. Ah, the magic of Rails - it's smarter than me.

401 Unauthorized: Access is denied due to invalid credentials

i faced the same issue under IIS 8.5. A working solution for me was changing the IIS to display detailled errors. See answer from sna2stha. But i think it is not a good idea to forward detailed error messages to browsers in production enviroments. I added/changed the existingResponse attribute in the httpErrors-Section, so the IIS not handled any extisting Asp.net Response:

<system.webServer>
   <httpErrors existingResponse="PassThrough" />
</system.webServer>

This works for me.

How to create JSON object Node.js

The JavaScript Object() constructor makes an Object that you can assign members to.

myObj = new Object()
myObj.key = value;
myObj[key2] = value2;   // Alternative

What is the recommended way to delete a large number of items from DynamoDB?

What I ideally want to do is call LogTable.DeleteItem(user_id) - Without supplying the range, and have it delete everything for me.

An understandable request indeed; I can imagine advanced operations like these might get added over time by the AWS team (they have a history of starting with a limited feature set first and evaluate extensions based on customer feedback), but here is what you should do to avoid the cost of a full scan at least:

  1. Use Query rather than Scan to retrieve all items for user_id - this works regardless of the combined hash/range primary key in use, because HashKeyValue and RangeKeyCondition are separate parameters in this API and the former only targets the Attribute value of the hash component of the composite primary key..

    • Please note that you''ll have to deal with the query API paging here as usual, see the ExclusiveStartKey parameter:

      Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter. The LastEvaluatedKey can be passed back in a new query request to continue the operation from that point.

  2. Loop over all returned items and either facilitate DeleteItem as usual

    • Update: Most likely BatchWriteItem is more appropriate for a use case like this (see below for details).

Update

As highlighted by ivant, the BatchWriteItem operation enables you to put or delete several items across multiple tables in a single API call [emphasis mine]:

To upload one item, you can use the PutItem API and to delete one item, you can use the DeleteItem API. However, when you want to upload or delete large amounts of data, such as uploading large amounts of data from Amazon Elastic MapReduce (EMR) or migrate data from another database in to Amazon DynamoDB, this API offers an efficient alternative.

Please note that this still has some relevant limitations, most notably:

  • Maximum operations in a single request — You can specify a total of up to 25 put or delete operations; however, the total request size cannot exceed 1 MB (the HTTP payload).

  • Not an atomic operation — Individual operations specified in a BatchWriteItem are atomic; however BatchWriteItem as a whole is a "best-effort" operation and not an atomic operation. That is, in a BatchWriteItem request, some operations might succeed and others might fail. [...]

Nevertheless this obviously offers a potentially significant gain for use cases like the one at hand.

Reloading submodules in IPython

IPython offers dreload() to recursively reload all submodules. Personally, I prefer to use the %run() magic command (though it does not perform a deep reload, as pointed out by John Salvatier in the comments).

What's the difference between align-content and align-items?

First, align-items is for items in a single row. So for a single row of elements on main axis, align-items will align these items respective of each other and it will start with fresh perspective from the next row.

Now, align-content doesn't interfere with items in a row but with rows itself. Hence, align-content will try to align rows with respect to each other and flex container.

Check this fiddle : https://jsfiddle.net/htym5zkn/8/

How do I set Tomcat Manager Application User Name and Password for NetBeans?

When you're launching tomcat server from netbeans IDE you need to check in menu "tools->servers" on connection tab for tomcat server - there is catalina base directory. And you need to include something like:

 <role rolename="manager"/>
  <user username="admin" password="admin" roles="manager"/>

at file

\CATALINA_BASE\conf\tomcat-users.xml

or use username automatically generated by IDE with description already placed in this file or on connection tab

For Manager Apps : GUI access:

<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

Named instances?

URL: jdbc:sqlserver://[serverName][\instanceName][:portNumber][;property=value]

Note: backward slash

Java: Get first item from a collection

In Java 8 you have some many operators to use, for instance limit

     /**
 * Operator that limit the total number of items emitted through the pipeline
 * Shall print
 * [1]
 * @throws InterruptedException
 */
@Test
public void limitStream() throws InterruptedException {
    List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)
                               .stream()
                               .limit(1)
                               .collect(toList());
    System.out.println(list);
}

Cross-Origin Request Headers(CORS) with PHP headers

I got the same error, and fixed it with the following PHP in my back-end script:

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

run Android SDK Manager as administrator. that solved my problem

sudo android

How to add a new row to an empty numpy array

Here is my solution:

arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)

How can I check if a URL exists via PHP?

you cannot use curl in certain servers u can use this code

<?php
$url = 'http://www.example.com';
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200"))
  {
    echo 'url exists';
  }
  else
  {
    echo 'url does not exist';
  }
?>

Two div blocks on same line

You can use a HTML table:

<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>   

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

When to use RSpec let()?

I always prefer let to an instance variable for a couple of reasons:

  • Instance variables spring into existence when referenced. This means that if you fat finger the spelling of the instance variable, a new one will be created and initialized to nil, which can lead to subtle bugs and false positives. Since let creates a method, you'll get a NameError when you misspell it, which I find preferable. It makes it easier to refactor specs, too.
  • A before(:each) hook will run before each example, even if the example doesn't use any of the instance variables defined in the hook. This isn't usually a big deal, but if the setup of the instance variable takes a long time, then you're wasting cycles. For the method defined by let, the initialization code only runs if the example calls it.
  • You can refactor from a local variable in an example directly into a let without changing the referencing syntax in the example. If you refactor to an instance variable, you have to change how you reference the object in the example (e.g. add an @).
  • This is a bit subjective, but as Mike Lewis pointed out, I think it makes the spec easier to read. I like the organization of defining all my dependent objects with let and keeping my it block nice and short.

A related link can be found here: http://www.betterspecs.org/#let

Count all values in a matrix greater than a value

To count the number of values larger than x in any numpy array you can use:

n = len(matrix[matrix > x])

The boolean indexing returns an array that contains only the elements where the condition (matrix > x) is met. Then len() counts these values.

How can I convert integer into float in Java?

You just need to transfer the first value to float, before it gets involved in further computations:

float z = x * 1.0 / y;

php - insert a variable in an echo string

echo '<p class="paragraph'.$i.'"></p>'

should do the trick.

What's the most elegant way to cap a number to a segment?

If you don’t want to define any function, writing it like Math.min(Math.max(x, a), b) isn’t that bad.

Reading file from Workspace in Jenkins with Groovy script

May this help to someone if they have the same requirement.

This will read a file that contains the Jenkins Job name and run them iteratively from one single job.

Please change below code accordingly in your Jenkins.

_x000D_
_x000D_
pipeline {
   agent any

   stages {
      stage('Hello') {
         steps {
             script{
            git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '

##To read file from workspace which will contain the Jenkins Job Name ###
           
     def filePath = readFile "${WORKSPACE}/ Your File Location"                   

##To read file line by line ###
 
     def lines = filePath.readLines() 
      
##To iterate and run Jenkins Jobs one by one ####

                    for (line in lines) {                                            
                      build(job: "$line/branchName",
                        parameters:
                        [string(name: 'vertical', value: "${params.vert}"),
                        string(name: 'environment', value: "${params.env}"),
                        string(name: 'branch', value: "${params.branch}"),
                        string(name: 'project', value: "${params.project}")
                        ]
                    )
                        }  
                                       }
                    
         }
         }
      }
   }
_x000D_
_x000D_
_x000D_

jQuery.inArray(), how to use it right?

It will return the index of the item in the array. If it's not found you will get -1

Expand a div to fill the remaining width

This would be a good example of something that's trivial to do with tables and hard (if not impossible, at least in a cross-browser sense) to do with CSS.

If both the columns were fixed width, this would be easy.

If one of the columns was fixed width, this would be slightly harder but entirely doable.

With both columns variable width, IMHO you need to just use a two-column table.

Iterate Multi-Dimensional Array with Nested Foreach Statement

Use LINQ .Cast<int>() to convert 2D array to IEnumerable<int>.

LINQPad example:

var arr = new int[,] { 
  { 1, 2, 3 }, 
  { 4, 5, 6 } 
};

IEnumerable<int> values = arr.Cast<int>();
Console.WriteLine(values);

Output:

Sequence is 1,2,3,4,5,6

how to run the command mvn eclipse:eclipse

The m2e plugin uses it's own distribution of Maven, packaged with the plugin.

In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows

Once Maven is properly installed (i.e. be sure that MAVEN_HOME, JAVA_HOME and PATH variables are set correctly): you must run mvn eclipse:eclipse from the directory containing the pom.xml.

Extending from two classes

The creators of java decided that the problems of multiple inheritance outweigh the benefits, so they did not include multiple inheritance. You can read about one of the largest issues of multiple inheritance (the double diamond problem) here.

The two most similar concepts are interface implementation and including objects of other classes as members of the current class. Using default methods in interfaces is almost exactly the same as multiple inheritance, however it is considered bad practice to use an interface with only default methods.

CSS: styled a checkbox to look like a button, is there a hover?

it looks like you need a rule very similar to your checked rule

http://jsfiddle.net/VWBN4/3

#ck-button input:hover + span {
    background-color:#191;
    color:#fff;
}

and for hover and clicked state:

#ck-button input:checked:hover + span {
    background-color:#c11;
    color:#fff;
}

the order is important though.

How to insert table values from one database to another database?

    --Code for same server
USE [mydb1]
GO

INSERT INTO dbo.mytable1 (
    column1
    ,column2
    ,column3
    ,column4
    )
SELECT column1
    ,column2
    ,column3
    ,column4
FROM [mydb2].dbo.mytable2 --WHERE any condition

/*
steps-
    1-  [mydb1] means our opend connection database 
    2-  mytable1 the table in mydb1 database where we want insert record
    3-  mydb2 another database.
    4-  mytable2 is database table where u fetch record from it. 
*/

--Code for different server
        USE [mydb1]

    SELECT *
    INTO mytable1
    FROM OPENDATASOURCE (
            'SQLNCLI'
            ,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
            ).[mydb2].dbo.mytable2

        /*  steps - 
            1-  [mydb1] means our opend connection database 
            2-  mytable1 means create copy table in mydb1 database where we want 
                insert record
            3-  XXX.XX.XX.XXX - another server name.
            4-  mydb2 another server database.
            5-  write User id and Password of another server credential
            6-  mytable2 is another server table where u fetch record from it. */

matplotlib: Group boxplots

Just to add to the conversation, I have found a more elegant way to change the color of the box plot by iterating over the dictionary of the object itself

import numpy as np
import matplotlib.pyplot as plt

def color_box(bp, color):

    # Define the elements to color. You can also add medians, fliers and means
    elements = ['boxes','caps','whiskers']

    # Iterate over each of the elements changing the color
    for elem in elements:
        [plt.setp(bp[elem][idx], color=color) for idx in xrange(len(bp[elem]))]
    return

a = np.random.uniform(0,10,[100,5])    

bp = plt.boxplot(a)
color_box(bp, 'red')

Original box plot

Modified box plot

Cheers!

How to find lines containing a string in linux

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file.

setting content between div tags using javascript

If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.

The innerHtml property did not work for me. So I experimented with ...

    <div id=successAndErrorMessages-1>100% OK</div>
    <div id=successAndErrorMessages-2>This is an error mssg!</div>

and toggled one of the two on/off ...

 $("#successAndErrorMessages-1").css('display', 'none')
 $("#successAndErrorMessages-2").css('display', '')

For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

How to copy a file to another path?

You could also use File.Copy to copy and File.Move to rename it afterwords.

// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);

// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
//       However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
//    File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
//    throw new IOException("Failed to rename file after copying, because destination file exists!");

EDIT
Commented out the "rename" code, because File.Copy can already copy and rename in one step, as astander noted correctly in the comments.

However, the rename code could be adapted if the OP desired to rename the source file after it has been copied to a new location.

Convert array of strings into a string in Java

Try the Arrays.toString overloaded methods.

Or else, try this below generic implementation:

public static void main(String... args) throws Exception {

    String[] array = {"ABC", "XYZ", "PQR"};

    System.out.println(new Test().join(array, ", "));
}

public <T> String join(T[] array, String cement) {
    StringBuilder builder = new StringBuilder();

    if(array == null || array.length == 0) {
        return null;
    }

    for (T t : array) {
        builder.append(t).append(cement);
    }

    builder.delete(builder.length() - cement.length(), builder.length());

    return builder.toString();
}

Creating an abstract class in Objective-C

You can use a method proposed by @Yar (with some modification):

#define mustOverride() @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"%s must be overridden in a subclass/category", __PRETTY_FUNCTION__] userInfo:nil]
#define setMustOverride() NSLog(@"%@ - method not implemented", NSStringFromClass([self class])); mustOverride()

Here you will get a message like:

<Date> ProjectName[7921:1967092] <Class where method not implemented> - method not implemented
<Date> ProjectName[7921:1967092] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[<Base class (if inherited or same if not> <Method name>] must be overridden in a subclass/category'

Or assertion:

NSAssert(![self respondsToSelector:@selector(<MethodName>)], @"Not implemented");

In this case you will get:

<Date> ProjectName[7926:1967491] *** Assertion failure in -[<Class Name> <Method name>], /Users/kirill/Documents/Projects/root/<ProjectName> Services/Classes/ViewControllers/YourClass:53

Also you can use protocols and other solutions - but this is one of the simplest ones.

Play sound on button click android

This is the most important part in the code provided in the original post.

Button one = (Button) this.findViewById(R.id.button1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        mp.start();
    }
});

To explain it step by step:

Button one = (Button) this.findViewById(R.id.button1);

First is the initialization of the button to be used in playing the sound. We use the Activity's findViewById, passing the Id we assigned to it (in this example's case: R.id.button1), to get the button that we need. We cast it as a Button so that it is easy to assign it to the variable one that we are initializing. Explaining more of how this works is out of scope for this answer. This gives a brief insight on how it works.

final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);

This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play, in this case R.raw.soho. We declare it as final. Jon Skeet provided a great explanation on why we do so here.

one.setOnClickListener(new OnClickListener(){

    public void onClick(View v) {
        //code
    }
});

Finally, we set what our previously initialized button will do. Play a sound on button click! To do this, we set the OnClickListener of our button one. Inside is only one method, onClick() which contains what instructions the button should do on click.

public void onClick(View v) {
    mp.start();
}

To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.

There, you can now play a sound on button click in Android!


Bonus part:

As noted in the comment belowThanks Langusten Gustel!, and as recommended in the Android Developer Reference, it is important to call the release() method to free up resources that will no longer be used. Usually, this is done once the sound to be played has completed playing. To do so, we add an OnCompletionListener to our mp like so:

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        //code
    }
});

Inside the onCompletion method, we release it like so:

public void onCompletion(MediaPlayer mp) {
    mp.release();
}

There are obviously better ways of implementing this. For example, you can make the MediaPlayer a class variable and handle its lifecycle along with the lifecycle of the Fragment or Activity that uses it. However, this is a topic for another question. To keep the scope of this answer small, I wrote it just to illustrate how to play a sound on button click in Android.


Original Post

First. You should put your statements inside a block, and in this case the onCreate method.

Second. You initialized the button as variable one, then you used a variable zero and set its onClickListener to an incomplete onClickListener. Use the variable one for the setOnClickListener.

Third, put the logic to play the sound inside the onClick.

In summary:

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BasicScreenActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_screen);

        Button one = (Button)this.findViewById(R.id.button1);
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
        one.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                mp.start();
            }
        });
    }
}

IIS Request Timeout on long ASP.NET operation

Great and exhaustive answerby @Kev!

Since I did long processing only in one admin page in a WebForms application I used the code option. But to allow a temporary quick fix on production I used the config version in a <location> tag in web.config. This way my admin/processing page got enough time, while pages for end users and such kept their old time out behaviour.

Below I gave the config for you Googlers needing the same quick fix. You should ofcourse use other values than my '4 hour' example, but DO note that the session timeOut is in minutes, while the request executionTimeout is in seconds!

And - since it's 2015 already - for a NON- quickfix you should use .Net 4.5's async/await now if at all possible, instead of the .NET 2.0's ASYNC page that was state of the art when KEV answered in 2010 :).

<configuration>
    ... 
    <compilation debug="false" ...>
    ... other stuff ..

    <location path="~/Admin/SomePage.aspx">
        <system.web>
            <sessionState timeout="240" />
            <httpRuntime executionTimeout="14400" />
        </system.web>
    </location>
    ...
</configuration>

Ways to iterate over a list in Java

A JDK8-style iteration:

public class IterationDemo {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3);
        list.stream().forEach(elem -> System.out.println("element " + elem));
    }
}

uncaught syntaxerror unexpected token U JSON

This answer can be a possible solution from many. This answer is for the people who are facing this error while working with File Upload..

We were using middleware for token based encryption - decryption and we encountered same error.

Following was our code in route file:

  router.route("/uploadVideoMessage")
  .post(
    middleware.checkToken,
    upload.single("video_file"),
    videoMessageController.uploadVideoMessage
  );

here we were calling middleware before upload function and that was causing the error. So when we changed it to this, it worked.

router.route("/uploadVideoMessage")
  .post(
    upload.single("video_file"),
    middleware.checkToken,
    videoMessageController.uploadVideoMessage
  );

How do I remove background-image in css?

If your div rule is just div {...}, then #a {...} will be sufficient. If it is more complicated, you need a "more specific" selector, as defined by the CSS specification on specificity. (#a being more specific than div is just single aspect in the algorithm.)

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

Hyphen, underscore, or camelCase as word delimiter in URIs?

You should use hyphens in a crawlable web application URL. Why? Because the hyphen separates words (so that a search engine can index the individual words), and is not a word character. Underscore is a word character, meaning it should be considered part of a word.

Double-click this in Chrome: camelCase
Double-click this in Chrome: under_score
Double-click this in Chrome: hyphen-ated

See how Chrome (I hear Google makes a search engine too) only thinks one of those is two words?

camelCase and underscore also require the user to use the shift key, whereas hyphenated does not.

So if you should use hyphens in a crawlable web application, why would you bother doing something different in an intranet application? One less thing to remember.

MSVCP140.dll missing

That's probably the C++ runtime library. Since it's a DLL it is not included in your program executable. Your friend can download those libraries from Microsoft.

bash assign default value

Please look at http://www.tldp.org/LDP/abs/html/parameter-substitution.html for examples

${parameter-default}, ${parameter:-default}

If parameter not set, use default. After the call, parameter is still not set.
Both forms are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null.

unset EGGS
echo 1 ${EGGS-spam}   # 1 spam
echo 2 ${EGGS:-spam}  # 2 spam

EGGS=
echo 3 ${EGGS-spam}   # 3
echo 4 ${EGGS:-spam}  # 4 spam

EGGS=cheese
echo 5 ${EGGS-spam}   # 5 cheese
echo 6 ${EGGS:-spam}  # 6 cheese

${parameter=default}, ${parameter:=default}

If parameter not set, set parameter value to default.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

# sets variable without needing to reassign
# colons suppress attempting to run the string
unset EGGS
: ${EGGS=spam}
echo 1 $EGGS     # 1 spam
unset EGGS
: ${EGGS:=spam}
echo 2 $EGGS     # 2 spam

EGGS=
: ${EGGS=spam}
echo 3 $EGGS     # 3        (set, but blank -> leaves alone)
EGGS=
: ${EGGS:=spam}
echo 4 $EGGS     # 4 spam

EGGS=cheese
: ${EGGS:=spam}
echo 5 $EGGS     # 5 cheese
EGGS=cheese
: ${EGGS=spam}
echo 6 $EGGS     # 6 cheese

${parameter+alt_value}, ${parameter:+alt_value}

If parameter set, use alt_value, else use null string. After the call, parameter value not changed.
Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is null

unset EGGS
echo 1 ${EGGS+spam}  # 1
echo 2 ${EGGS:+spam} # 2

EGGS=
echo 3 ${EGGS+spam}  # 3 spam
echo 4 ${EGGS:+spam} # 4

EGGS=cheese
echo 5 ${EGGS+spam}  # 5 spam
echo 6 ${EGGS:+spam} # 6 spam

Call two functions from same onclick

With jQuery :

jQuery("#btn").on("click",function(event){
    event.preventDefault();
    pay();
    cls();
});

Open Facebook Page in Facebook App (if installed) on Android

I already have answered here and it's working for me, please refer this link https://stackoverflow.com/a/40133225/3636561

    String socailLink="https://www.facebook.com/kfc";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
    if (facebookUrl == null || facebookUrl.length() == 0) {
        Log.d("facebook Url", " is coming as " + facebookUrl);
        return;
    }
    intent.setData(Uri.parse(facebookUrl));
    startActivity(intent);

please refer link to get rest part.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

Eclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!

So you have two solutions:

  1. Move the folder counter_src somewhere else, then create the project (which will create the directory), then import the source files back into the newly created counter_src.

  2. Right-click on the project explorer and import an existing project, select C:\Users\Martin\Java\Counter\ as your root directory. If Eclipse sees a project, you will be able to import it.

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

Pythonic way to return list of every nth item in a larger list

  1. source_list[::10] is the most obvious, but this doesn't work for any iterable and is not memory efficient for large lists.
  2. itertools.islice(source_sequence, 0, None, 10) works for any iterable and is memory-efficient, but probably is not the fastest solution for large list and big step.
  3. (source_list[i] for i in xrange(0, len(source_list), 10))

Execute PowerShell Script from C# with Commandline Arguments

You can also just use the pipeline with the AddScript Method:

string cmdArg = ".\script.ps1 -foo bar"            
Collection<PSObject> psresults;
using (Pipeline pipeline = _runspace.CreatePipeline())
            {
                pipeline.Commands.AddScript(cmdArg);
                pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
                psresults = pipeline.Invoke();
            }
return psresults;

It will take a string, and whatever parameters you pass it.

How do I check if a file exists in Java?

There are multiple ways to achieve this.

  1. In case of just for existence. It could be file or a directory.

    new File("/path/to/file").exists();
    
  2. Check for file

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isFile()) {}
    
  3. Check for Directory.

    File f = new File("/path/to/file"); 
      if(f.exists() && f.isDirectory()) {}
    
  4. Java 7 way.

    Path path = Paths.get("/path/to/file");
    Files.exists(path)  // Existence 
    Files.isDirectory(path)  // is Directory
    Files.isRegularFile(path)  // Regular file 
    Files.isSymbolicLink(path)  // Symbolic Link
    

Check if any type of files exist in a directory using BATCH script

To check if a folder contains at least one file

>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder or any of its descendents contain at least one file

>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder contains at least one file or folder.
Note addition of /a option to enable finding of hidden and system files/folders.

dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)

To check if a folder contains at least one folder

dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)

How can I add an item to a SelectList in ASP.net MVC

I don't if anybody else has a better option...

<% if (Model.VariableName == "" || Model.VariableName== null) { %>
   <%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], "", 
        new{stlye=" "})%>
<% } else{ %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], 
        Model.VariableName, new{stlye=" "})%>
<% }>

Truncate Two decimal places without rounding

Actually you want 3.46 from 3.4679 . This is only representation of characters.So there is nothing to do with math function.Math function is not intended to do this work. Simply use the following code.

Dim str1 As String
str1=""
str1 ="3.4679" 
  Dim substring As String = str1.Substring(0, 3)

    ' Write the results to the screen.
    Console.WriteLine("Substring: {0}", substring)

Or 
    Please use the following code.
Public function result(ByVal x1 As Double) As String 
  Dim i as  Int32
  i=0
  Dim y as String
  y = ""
  For Each ch as Char In x1.ToString
    If i>3 then
     Exit For
    Else
    y + y +ch
    End if
    i=i+1
  Next
  return y
End Function

The above code can be modified for any numbers Put the following code in a button click event

Dim str As String 
str= result(3.4679)
 MsgBox("The number is " & str)

How can I get a process handle by its name in C++?

There are two basic techniques. The first uses PSAPI; MSDN has an example that uses EnumProcesses, OpenProcess, EnumProcessModules, and GetModuleBaseName.

The other uses Toolhelp, which I prefer. Use CreateToolhelp32Snapshot to get a snapshot of the process list, walk over it with Process32First and Process32Next, which provides module name and process ID, until you find the one you want, and then call OpenProcess to get a handle.

Reset C int array to zero : the fastest way?

For static declaration I think you could use:

T myarray[100] = {0};

For dynamic declaration I suggest the same way: memset

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

How to set default values in Go structs

From https://golang.org/doc/effective_go.html#composite_literals:

Sometimes the zero value isn't good enough and an initializing constructor is necessary, as in this example derived from package os.

    func NewFile(fd int, name string) *File {
      if fd < 0 {
        return nil
      }
      f := new(File)
      f.fd = fd
      f.name = name
      f.dirinfo = nil
      f.nepipe = 0
      return f
}

What is the difference between angular-route and angular-ui-router?

Generally ui-router works on a state mechanism... It can be understood with an easy example:

Let's say we have a big application of a music library (like ..gaana or saavan or any other). And at the bottom of the page, you have a music player which is shared across all the state of the page.

Now let's say you just click on some songs to play. In this case, only that music player state should change instead of reloading the full page. That can be easily handled by ui-router.

While in ngRoute we just attach the view and the controller.

How to reduce a huge excel file

I wrote a VBA file to add a tool cleaning these abnormally biggest file. This script clear all columns and rows after the last cells realy used to reset the last cells ( [Ctrl]+[End] ), and it also provides enable images compression.

I dev an AddIns with auto install (just run it with macro enabled) to include in context menu many new buttons:

  1. Optimize
  2. Optimize and Save
  3. Disable Optimizer

Context menu after install it

This is based on KB of Microsoft office 2003 and answer of PP. with personals improvement :

  1. add compression of images
  2. fix bug for Columns
  3. feat compatibility with excel 2007 - 2010 - ... (more than 255 columns)

SOLUTION > you can download my *.xlam file ToolsKit

the main code is

Sub ClearExcessRowsAndColumns()
    Dim ar As Range, r As Double, c As Double, tr As Double, tc As Double
    Dim wksWks As Worksheet, ur As Range, arCount As Integer, i As Integer
    Dim blProtCont As Boolean, blProtScen As Boolean, blProtDO As Boolean
    Dim shp As Shape
    Application.ScreenUpdating = False
    On Error Resume Next
    For Each wksWks In ActiveWorkbook.Worksheets
      Err.Clear
      'Store worksheet protection settings and unprotect if protected.
      blProtCont = wksWks.ProtectContents
      blProtDO = wksWks.ProtectDrawingObjects
      blProtScen = wksWks.ProtectScenarios
      wksWks.Unprotect ""
      If Err.Number = 1004 Then
         Err.Clear
         MsgBox "'" & wksWks.Name & "' is protected with a password and cannot be checked.", vbInformation
      Else
         Application.StatusBar = "Checking " & wksWks.Name & ", Please Wait..."
         r = 0
         c = 0

         'Determine if the sheet contains both formulas and constants
         Set ur = Union(wksWks.UsedRange.SpecialCells(xlCellTypeConstants), wksWks.UsedRange.SpecialCells(xlCellTypeFormulas))
         'If both fails, try constants only
         If Err.Number = 1004 Then
            Err.Clear
            Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeConstants)
         End If
         'If constants fails then set it to formulas
         If Err.Number = 1004 Then
            Err.Clear
            Set ur = wksWks.UsedRange.SpecialCells(xlCellTypeFormulas)
         End If
         'If there is still an error then the worksheet is empty
         If Err.Number <> 0 Then
            Err.Clear
            If wksWks.UsedRange.Address <> "$A$1" Then
               ur.EntireRow.Delete
            Else
               Set ur = Nothing
            End If
         End If
         'On Error GoTo 0
         If Not ur Is Nothing Then
            arCount = ur.Areas.Count
            'determine the last column and row that contains data or formula
            For Each ar In ur.Areas
               i = i + 1
               tr = ar.Range("A1").Row + ar.Rows.Count - 1
               tc = ar.Range("A1").Column + ar.Columns.Count - 1
               If tc > c Then c = tc
               If tr > r Then r = tr
            Next
            'Determine the area covered by shapes
            'so we don't remove shading behind shapes
            For Each shp In wksWks.Shapes
               tr = shp.BottomRightCell.Row
               tc = shp.BottomRightCell.Column
               If tc > c Then c = tc
               If tr > r Then r = tr
            Next
            Application.StatusBar = "Clearing Excess Cells in " & wksWks.Name & ", Please Wait..."
            Set ur = wksWks.Rows(r + 1 & ":" & wksWks.Rows.Count)
                'Reset row height which can also cause the lastcell to be innacurate
                ur.EntireRow.RowHeight = wksWks.StandardHeight
                ur.Clear

            Set ur = wksWks.Columns(ColLetter(c + 1) & ":" & ColLetter(wksWks.Columns.Count))
                'Reset column width which can also cause the lastcell to be innacurate
                ur.EntireColumn.ColumnWidth = wksWks.StandardWidth
                ur.Clear
         End If
      End If
      'Reset protection.
      wksWks.Protect "", blProtDO, blProtCont, blProtScen
      Err.Clear
    Next
    Application.StatusBar = False
    ' prepare les combinaison de touches pour la validation automatique de la fenetre
    ' Application.SendKeys "%(oe)~{TAB}~"

    ' ouvre la fenetre de compression des images
    Application.CommandBars.ExecuteMso "PicturesCompress"
    Application.ScreenUpdating = True
End Sub


Function ColLetter(ColNumber As Integer) As String
    ColLetter = Left(Cells(1, ColNumber).Address(False, False), Len(Cells(1, ColNumber).Address(False, False)) - 1)
End Function

How to determine device screen size category (small, normal, large, xlarge) using code?

Copy and paste this code into your Activity and when it is executed it will Toast the device's screen size category.

int screenSize = getResources().getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK;

String toastMsg;
switch(screenSize) {
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        toastMsg = "Large screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        toastMsg = "Normal screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        toastMsg = "Small screen";
        break;
    default:
        toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();

How to repeat a char using printf?

Short answer - yes, long answer: not how you want it.

You can use the %* form of printf, which accepts a variable width. And, if you use '0' as your value to print, combined with the right-aligned text that's zero padded on the left..

printf("%0*d\n", 20, 0);

produces:

00000000000000000000

With my tongue firmly planted in my cheek, I offer up this little horror-show snippet of code.

Some times you just gotta do things badly to remember why you try so hard the rest of the time.

#include <stdio.h>

int width = 20;
char buf[4096];

void subst(char *s, char from, char to) {
    while (*s == from)
    *s++ = to;
}

int main() {
    sprintf(buf, "%0*d", width, 0);
    subst(buf, '0', '-');
    printf("%s\n", buf);
    return 0;
}

ERROR 1064 (42000) in MySQL

I got this error

ERROR 1064 (42000)

because the downloaded .sql.tar file was somehow corrupted. Downloading and extracting it again solved the issue.

Imply bit with constant 1 or 0 in SQL Server

Slightly more condensed than gbn's:

Assuming CourseId is non-zero

CAST (COALESCE(FC.CourseId, 0) AS Bit)

COALESCE is like an ISNULL(), but returns the first non-Null.

A Non-Zero CourseId will get type-cast to a 1, while a null CourseId will cause COALESCE to return the next value, 0

Make the current commit the only (initial) commit in a Git repository?

To remove the last commit from git, you can simply run

git reset --hard HEAD^ 

If you are removing multiple commits from the top, you can run

git reset --hard HEAD~2 

to remove the last two commits. You can increase the number to remove even more commits.

More info here.

Git tutoturial here provides help on how to purge repository:

you want to remove the file from history and add it to the .gitignore to ensure it is not accidentally re-committed. For our examples, we're going to remove Rakefile from the GitHub gem repository.

git clone https://github.com/defunkt/github-gem.git

cd github-gem

git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch Rakefile' \
  --prune-empty --tag-name-filter cat -- --all

Now that we've erased the file from history, let's ensure that we don't accidentally commit it again.

echo "Rakefile" >> .gitignore

git add .gitignore

git commit -m "Add Rakefile to .gitignore"

If you're happy with the state of the repository, you need to force-push the changes to overwrite the remote repository.

git push origin master --force

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

How to force open links in Chrome not download them?

Just found your question whilst trying to solve another problem I'm having, you will find that currently Google isn't able to perform a temporary download so therefore you have to download instead.

See: http://productforums.google.com/forum/#!topic/chrome/Drge_Zrwg-c

How to send a "multipart/form-data" with requests in python?

Here is the python snippet you need to upload one large single file as multipart formdata. With NodeJs Multer middleware running on the server side.

import requests
latest_file = 'path/to/file'
url = "http://httpbin.org/apiToUpload"
files = {'fieldName': open(latest_file, 'rb')}
r = requests.put(url, files=files)

For the server side please check the multer documentation at: https://github.com/expressjs/multer here the field single('fieldName') is used to accept one single file, as in:

var upload = multer().single('fieldName');

Set folder browser dialog start location

Set the SelectedPath property before you call ShowDialog ...

folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();

Will start them at C:\Temp

How can I switch themes in Visual Studio 2012

Slightly off topic, but for those of you that want to modify the built-in colors of the Dark/Light themes you can use this little tool I wrote for Visual Studio 2012.

More info here:

Modify Visual Studio 2012 Dark (and Light) Themes

Source Code

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

JQuery - $ is not defined

This is the common issue to resolve this you have to check some point

  1. Include Main Jquery Library
  2. Check Cross-Browser Issue
  3. Add Library on TOP of the jquery code
  4. Check CDNs might be blocked.

Full details are given in this blog click here

What's the difference between equal?, eql?, ===, and ==?

=== #---case equality

== #--- generic equality

both works similar but "===" even do case statements

"test" == "test"  #=> true
"test" === "test" #=> true

here the difference

String === "test"   #=> true
String == "test"  #=> false

How can I get a file's size in C++?

You need to seek to the end of the file and then ask for the position:

fseek(fp, 0L, SEEK_END);
sz = ftell(fp);

You can then seek back, e.g.:

fseek(fp, 0L, SEEK_SET);

or (if seeking to go to the beginning)

rewind(fp);

Tab separated values in awk

Use:

awk -v FS='\t' -v OFS='\t' ...

Example from one of my scripts.

I use the FS and OFS variables to manipulate BIND zone files, which are tab delimited:

awk -v FS='\t' -v OFS='\t' \
    -v record_type=$record_type \
    -v hostname=$hostname \
    -v ip_address=$ip_address '
$1==hostname && $3==record_type {$4=ip_address}
{print}
' $zone_file > $temp

This is a clean and easy to read way to do this.

Using routes in Express-js

You could also organise them into modules. So it would be something like.

./
controllers
    index.js
    indexController.js
app.js

and then in the indexController.js of the controllers export your controllers.

//indexController.js
module.exports = function(){
//do some set up

var self = {
     indexAction : function (req,res){
       //do your thing
}
return self;
};

then in index.js of controllers dir

exports.indexController = require("./indexController");

and finally in app.js

var controllers = require("./controllers");

app.get("/",controllers.indexController().indexAction);

I think this approach allows for clearer seperation and also you can configure your controllers by passing perhaps a db connection in.

how to store Image as blob in Sqlite & how to retrieve it?

Here the code i used for my app

This code will take a image from url and convert is to a byte array

byte[] logoImage = getLogoImage(IMAGEURL);

private byte[] getLogoImage(String url){
     try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                  baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
          Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}

To save the image to db i used this code.

 public void insertUser(){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String delSql = "DELETE FROM ACCOUNTS";
        SQLiteStatement delStmt = db.compileStatement(delSql);
        delStmt.execute();

        String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)";
        SQLiteStatement insertStmt = db.compileStatement(sql);
        insertStmt.clearBindings();
        insertStmt.bindString(1, Integer.toString(this.accId));
        insertStmt.bindString(2,this.accName);
        insertStmt.bindBlob(3, this.accImage);
        insertStmt.executeInsert();
        db.close();
}

To retrieve the image back this is code i used.

public Account getCurrentAccount() {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    String sql = "SELECT * FROM ACCOUNTS";
    Cursor cursor = db.rawQuery(sql, new String[] {});

    if(cursor.moveToFirst()){
        this.accId  = cursor.getInt(0);
        this.accName = cursor.getString(1);
        this.accImage = cursor.getBlob(2);
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    db.close();
    if(cursor.getCount() == 0){
        return null;
    } else {
        return this;
    }
}

Finally to load this image to a imageview

logoImage.setImageBitmap(BitmapFactory.decodeByteArray( currentAccount.accImage, 
        0,currentAccount.accImage.length));

Custom Date/Time formatting in SQL Server

You're going to need DATEPART here. You can concatenate the results of the DATEPART calls together.

To get the month abbreviations, you might be able to use DATENAME; if that doesn't work for you, you can use a CASE statement on the DATEPART.

DATEPART also works for the time field.

I can think of a couple of ways of getting the AM/PM indicator, including comparing new dates built via DATEPART or calculating the total seconds elapsed in the day and comparing that to known AM/PM thresholds.

Finding element in XDocument?

My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).

In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d457c3b-292c-49e1-9fd4-9b6a950f9010/how-to-get-tag-name-of-xml-by-using-xdocument?forum=csharpgeneral

In short, you can create a GetElement function:

private XElement GetElement(XDocument doc,string elementName)
{
    foreach (XNode node in doc.DescendantNodes())
    {
        if (node is XElement)
        {
            XElement element = (XElement)node;
            if (element.Name.LocalName.Equals(elementName))
                return element;
        }
    }
    return null;
}

Which you can then call like this:

XElement element = GetElement(doc,"Band");

Note that this will return null if no matching element is found.

Regex doesn't work in String.matches()

String.matches returns whether the whole string matches the regex, not just any substring.

..The underlying connection was closed: An unexpected error occurred on a receive

  • .NET 4.6 and above. You don’t need to do any additional work to support TLS 1.2, it’s supported by default.
  • .NET 4.5. TLS 1.2 is supported, but it’s not a default protocol. You need to opt-in to use it. The following code will make TLS 1.2 default, make sure to execute it before making a connection to secured resource:
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  • .NET 4.0. TLS 1.2 is not supported, but if you have .NET 4.5 (or above) installed on the system then you still can opt in for TLS 1.2 even if your application framework doesn’t support it. The only problem is that SecurityProtocolType in .NET 4.0 doesn’t have an entry for TLS1.2, so we’d have to use a numerical representation of this enum value:
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

  • .NET 3.5 or below. TLS 1.2 is not supported. Upgrade your application to more recent version of the framework.

PHP 5 disable strict standards error

I didn't see an answer that's clean and suitable for production-ready software, so here it goes:

/*
 * Get current error_reporting value,
 * so that we don't lose preferences set in php.ini and .htaccess
 * and accidently reenable message types disabled in those.
 *
 * If you want to disable e.g. E_STRICT on a global level,
 * use php.ini (or .htaccess for folder-level)
 */
$old_error_reporting = error_reporting();

/*
 * Disable E_STRICT on top of current error_reporting.
 *
 * Note: do NOT use ^ for disabling error message types,
 * as ^ will re-ENABLE the message type if it happens to be disabled already!
 */
error_reporting($old_error_reporting & ~E_STRICT);


// code that should not emit E_STRICT messages goes here


/*
 * Optional, depending on if/what code comes after.
 * Restore old settings.
 */
error_reporting($old_error_reporting);

Best way to handle list.index(might-not-exist) in python?

The dict type has a get function, where if the key doesn't exist in the dictionary, the 2nd argument to get is the value that it should return. Similarly there is setdefault, which returns the value in the dict if the key exists, otherwise it sets the value according to your default parameter and then returns your default parameter.

You could extend the list type to have a getindexdefault method.

class SuperDuperList(list):
    def getindexdefault(self, elem, default):
        try:
            thing_index = self.index(elem)
            return thing_index
        except ValueError:
            return default

Which could then be used like:

mylist = SuperDuperList([0,1,2])
index = mylist.getindexdefault( 'asdf', -1 )

How do you remove a specific revision in the git history?

To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash.

I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under "Splitting commits" should hopefully give you enough of an idea to figure it out. (Or someone else might know).

From the git documentation:

Start it with the oldest commit you want to retain as-is:

git rebase -i <after-this-commit>

An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this:

pick deadbee The oneline of this commit
pick fa1afe1 The oneline of the next commit
...

The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names.

By replacing the command "pick" with the command "edit", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.

If you want to fold two or more commits into one, replace the command "pick" with "squash" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit.

How to connect to LocalDB in Visual Studio Server Explorer?

Use SQL Server Object Explorer (SSOX) Instead

Unlike the other answers, this approach uses:
- No special commands.
- No complicated configurations.
Just use the SQL Server Object Explorer

It's pretty straightforward...

  • From the View menu, open SQL Server Object Explorer.

one

  • Right click on the {YourTableName} table > View Designer

two

Done.

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

Let us take an interview Question. There is a method that throws NullPointerException in the superclass. Can we override it with a method that throws RuntimeException?

To answer this question, let us know what is an Unchecked and Checked exception.

  1. Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown.

  2. Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.

public class NullPointerException extends RuntimeException

Unchecked exceptions extend the java.lang.RuntimeException. Thst's why NullPointerException is an Uncheked exception.

Let's take an example: Example 1 :

    public class Parent {
       public void name()  throws NullPointerException {
           System.out.println(" this is parent");
       }
}

public class Child  extends Parent{
     public  void name() throws RuntimeException{
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();
        parent.name();// output => child
    }
}

The program will compile successfully. Example 2:

    public class Parent {
       public void name()  throws RuntimeException {
           System.out.println(" this is parent");
       }
}

public class Child  extends Parent{
     public  void name() throws  NullPointerException {
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();
        parent.name();// output => child
    }
}

The program will also compile successfully. Therefore it is evident, that nothing happens in case of Unchecked exceptions. Now, let's take a look what happens in case of Checked exceptions. Example 3: When base class and child class both throws a checked exception

    public class Parent {
       public void name()  throws IOException {
           System.out.println(" this is parent");
       }
}
public class Child  extends Parent{
     public  void name() throws IOException{
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();

        try {
            parent.name();// output=> child
        }catch( Exception e) {
            System.out.println(e);
        }

    }
}

The program will compile successfully. Example 4: When child class method is throwing border checked exception compared to the same method of base class.

import java.io.IOException;

public class Parent {
       public void name()  throws IOException {
           System.out.println(" this is parent");
       }
}
public class Child  extends Parent{
     public  void name() throws Exception{ // broader exception
             System.out.println(" child ");
     }

     public static void main(String[] args) {
        Parent parent  = new Child();

        try {
            parent.name();//output=> Compilation failure
        }catch( Exception e) {
            System.out.println(e);
        }

    }
}

The program will fail to compile. So, we have to be careful when we are using Checked exceptions.

How do I populate a JComboBox with an ArrayList?

I don't like the accepted answer or @fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.

String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);

Alternatively, you can also maintain strong typing by just using a for loop.

String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
    array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);

generating variable names on fly in python

If you really want to create them on the fly you can assign to the dict that is returned by either globals() or locals() depending on what namespace you want to create them in:

globals()['somevar'] = 'someval'
print somevar  # prints 'someval'

But I wouldn't recommend doing that. In general, avoid global variables. Using locals() often just obscures what you are really doing. Instead, create your own dict and assign to it.

mydict = {}
mydict['somevar'] = 'someval'
print mydict['somevar']

Learn the python zen; run this and grok it well:

>>> import this

Dictionary returning a default value if the key does not exist

TryGetValue will already assign the default value for the type to the dictionary, so you can just use:

dictionary.TryGetValue(key, out value);

and just ignore the return value. However, that really will just return default(TValue), not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, 
     TKey key,
     TValue defaultValue)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}

public static TValue GetValueOrDefault<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key,
     Func<TValue> defaultValueProvider)
{
    TValue value;
    return dictionary.TryGetValue(key, out value) ? value
         : defaultValueProvider();
}

(You may want to put argument checking in, of course :)

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Difference between Role and GrantedAuthority in Spring Security

Think of a GrantedAuthority as being a "permission" or a "right". Those "permissions" are (normally) expressed as strings (with the getAuthority() method). Those strings let you identify the permissions and let your voters decide if they grant access to something.

You can grant different GrantedAuthoritys (permissions) to users by putting them into the security context. You normally do that by implementing your own UserDetailsService that returns a UserDetails implementation that returns the needed GrantedAuthorities.

Roles (as they are used in many examples) are just "permissions" with a naming convention that says that a role is a GrantedAuthority that starts with the prefix ROLE_. There's nothing more. A role is just a GrantedAuthority - a "permission" - a "right". You see a lot of places in spring security where the role with its ROLE_ prefix is handled specially as e.g. in the RoleVoter, where the ROLE_ prefix is used as a default. This allows you to provide the role names withtout the ROLE_ prefix. Prior to Spring security 4, this special handling of "roles" has not been followed very consistently and authorities and roles were often treated the same (as you e.g. can see in the implementation of the hasAuthority() method in SecurityExpressionRoot - which simply calls hasRole()). With Spring Security 4, the treatment of roles is more consistent and code that deals with "roles" (like the RoleVoter, the hasRole expression etc.) always adds the ROLE_ prefix for you. So hasAuthority('ROLE_ADMIN') means the the same as hasRole('ADMIN') because the ROLE_ prefix gets added automatically. See the spring security 3 to 4 migration guide for futher information.

But still: a role is just an authority with a special ROLE_ prefix. So in Spring security 3 @PreAuthorize("hasRole('ROLE_XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')") and in Spring security 4 @PreAuthorize("hasRole('XYZ')") is the same as @PreAuthorize("hasAuthority('ROLE_XYZ')").

Regarding your use case:

Users have roles and roles can perform certain operations.

You could end up in GrantedAuthorities for the roles a user belongs to and the operations a role can perform. The GrantedAuthorities for the roles have the prefix ROLE_ and the operations have the prefix OP_. An example for operation authorities could be OP_DELETE_ACCOUNT, OP_CREATE_USER, OP_RUN_BATCH_JOBetc. Roles can be ROLE_ADMIN, ROLE_USER, ROLE_OWNER etc.

You could end up having your entities implement GrantedAuthority like in this (pseudo-code) example:

@Entity
class Role implements GrantedAuthority {
    @Id
    private String id;

    @ManyToMany
    private final List<Operation> allowedOperations = new ArrayList<>();

    @Override
    public String getAuthority() {
        return id;
    }

    public Collection<GrantedAuthority> getAllowedOperations() {
        return allowedOperations;
    }
}

@Entity
class User {
    @Id
    private String id;

    @ManyToMany
    private final List<Role> roles = new ArrayList<>();

    public Collection<Role> getRoles() {
        return roles;
    }
}

@Entity
class Operation implements GrantedAuthority {
    @Id
    private String id;

    @Override
    public String getAuthority() {
        return id;
    }
}

The ids of the roles and operations you create in your database would be the GrantedAuthority representation, e.g. ROLE_ADMIN, OP_DELETE_ACCOUNT etc. When a user is authenticated, make sure that all GrantedAuthorities of all its roles and the corresponding operations are returned from the UserDetails.getAuthorities() method.

Example: The admin role with id ROLE_ADMIN has the operations OP_DELETE_ACCOUNT, OP_READ_ACCOUNT, OP_RUN_BATCH_JOB assigned to it. The user role with id ROLE_USER has the operation OP_READ_ACCOUNT.

If an admin logs in the resulting security context will have the GrantedAuthorities: ROLE_ADMIN, OP_DELETE_ACCOUNT, OP_READ_ACCOUNT, OP_RUN_BATCH_JOB

If a user logs it, it will have: ROLE_USER, OP_READ_ACCOUNT

The UserDetailsService would take care to collect all roles and all operations of those roles and make them available by the method getAuthorities() in the returned UserDetails instance.

How to set a border for an HTML div tag

can use

border-width:2px;
border-style:solid;
border-color:black;

or as shorthand

border: 2px solid black

If file exists then delete the file

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

creating array without declaring the size - java

How about this

    private Object element[] = new Object[] {};

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

How to find out what this MySQL Error is trying to say:

#1064 - You have an error in your SQL syntax;

This error has no clues in it. You have to double check all of these items to see where your mistake is:

  1. You have omitted, or included an unnecessary symbol: !@#$%^&*()-_=+[]{}\|;:'",<>/?
  2. A misplaced, missing or unnecessary keyword: select, into, or countless others.
  3. You have unicode characters that look like ascii characters in your query but are not recognized.
  4. Misplaced, missing or unnecessary whitespace or newlines between keywords.
  5. Unmatched single quotes, double quotes, parenthesis or braces.

Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.

Regular Expression with wildcards to match any character

Without knowing the exact regex implementation you're making use of, I can only give general advice. (The syntax I will be perl as that's what I know, some languages will require tweaking)

Looking at ABC: (z) jan 02 1999 \n

  • The first thing to match is ABC: So using our regex is /ABC:/

  • You say ABC is always at the start of the string so /^ABC/ will ensure that ABC is at the start of the string.

  • You can match spaces with the \s (note the case) directive. With all directives you can match one or more with + (or 0 or more with *)

  • You need to escape the usage of ( and ) as it's a reserved character. so \(\)

  • You can match any non space or newline character with .

  • You can match anything at all with .* but you need to be careful you're not too greedy and capture everything.

So in order to capture what you've asked. I would use /^ABC:\s*\(.+?\)\s*(.+)$/

Which I read as:

Begins with ABC:

May have some spaces

has (

has some characters

has )

may have some spaces

then capture everything until the end of the line (which is $).

I highly recommend keeping a copy of the following laying about http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

javascript regular expression to not match a word

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

Write HTML to string

When I deal with this problem in other languages I go for a separation of code and HTML. Something like:

1.) Create a HTML template. use [varname] placeholders to mark replaced/inserted content.
2.) Fill your template variables from an array or structure/mapping/dictionary

Write( FillTemplate(myHTMLTemplate, myVariables) ) # pseudo-code

Easiest way to compare arrays in C#

elementwise compare ? what about

public void Linq78a()
{
 int[] numbers1 = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
 bool bb = numbers.Zip(numbers1, (a, b) => (a == b)).Any(p => !p);
 if (!bb) Console.WriteLine("Lists are equal (bb)");
   else Console.WriteLine("Lists are not equal (bb)");
}

Replace the (a==b) condition by anything you'd like to compare in a and b.

(this combines two examples from MSDN developer Linq samples)

How do I turn a python datetime into a string, with readable format date?

This is for format the date?

def format_date(day, month, year):
        # {} betekent 'plaats hier stringvoorstelling van volgend argument'
        return "{}/{}/{}".format(day, month, year)

Reactive forms - disabled attribute

Initialization (component) using:

public selector = new FormControl({value: '', disabled: true});

Then instead of using (template):

<ngx-select
[multiple]="true"
[disabled]="errorSelector"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

Just remove the attribute disabled:

<ngx-select
[multiple]="true"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

And when you have items to show, launch (in component): this.selector.enable();

Disable activity slide-in animation when launching new activity?

FLAG_ACTIVITY_NO_ANIMATION may work, but wasn't doing the trick for me when combined with FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK. I'm apparently seeing the animation for creating a new task with a fresh activity stack as I navigate laterally to my other top-level views.

What did work here was calling "overridePendingTransition(0, 0);" either immediately after my startActivity() call or the onPause(). Both ways worked, but doing it after startActivity() gives me a little more control over when I want animations and when I don't.

Woocommerce, get current product id

If the query hasn't been modified by a plugin for some reason, you should be able to get a single product page's "id" via

global $post;
$id = $post->ID

OR

global $product;
$id = $product->id;

EDIT: As of WooCommerce 3.0 this needs to be

global $product;
$id = $product->get_id();

php pdo: get the columns name of a table

My 2 cents:

$result = $db->query('select * from table limit 1');
$fields = array_keys($result->fetch(PDO::FETCH_ASSOC));

And you will get the column names as an array in the var $fields.

height: 100% for <div> inside <div> with display: table-cell

table{
   height:1px;
}

table > td{
   height:100%;
}

table > td > .inner{
   height:100%;
}

Confirmed working on:

  • Chrome 60.0.3112.113, 63.0.3239.84
  • Firefox 55.0.3, 57.0.1
  • Internet Explorer 11

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

how can I connect to a remote mongo server from Mac OS terminal

With Mongo 3.2 and higher just use your connection string as is:

mongo mongodb://username:[email protected]:10011/my_database

How to break line in JavaScript?

Add %0D%0A to any place you want to encode a line break on the URL.

  • %0D is a carriage return character
  • %0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.


onClick="parent.location='mailto:[email protected]?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'

Why did I get the compile error "Use of unassigned local variable"?

While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules.

Value types can not be null ? the compiler guarantees that. If you ask how, the error message you got is the answer. Once you call their constructors, they got initialized with their default values.

int tmpCnt; // Not accepted
int tmpCnt = new Int(); // Default value applied tmpCnt = 0

Rounding a number to the nearest 5 or 10 or X

To round to the nearest X (without being VBA specific)

N = X * int(N / X + 0.5)

Where int(...) returns the next lowest whole number.

If your available rounding function already rounds to the nearest whole number then omit the addition of 0.5

How do I instantiate a Queue object in java?

Queue<String> qe=new LinkedList<String>();

qe.add("b");
qe.add("a");
qe.add("c");

Since Queue is an interface, you can't create an instance of it as you illustrated

How to assign multiple classes to an HTML container?

Just remove the comma like this:

<article class="column wrapper"> 

What is the purpose of the HTML "no-js" class?

The no-js class is used to style a webpage, dependent on whether the user has JS disabled or enabled in the browser.

As per the Modernizr docs:

no-js

By default, Modernizr will rewrite <html class="no-js"> to <html class="js">. This lets hide certain elements that should only be exposed in environments that execute JavaScript. If you want to disable this change, you can set enableJSClass to false in your config.

Java: How to convert List to Map

Many solutions come to mind, depending on what you want to achive:

Every List item is key and value

for( Object o : list ) {
    map.put(o,o);
}

List elements have something to look them up, maybe a name:

for( MyObject o : list ) {
    map.put(o.name,o);
}

List elements have something to look them up, and there is no guarantee that they are unique: Use Googles MultiMaps

for( MyObject o : list ) {
    multimap.put(o.name,o);
}

Giving all the elements the position as a key:

for( int i=0; i<list.size; i++ ) {
    map.put(i,list.get(i));
}

...

It really depends on what you want to achive.

As you can see from the examples, a Map is a mapping from a key to a value, while a list is just a series of elements having a position each. So they are simply not automatically convertible.

Setting Windows PATH for Postgres tools

Set path For PostgreSQL in Windows:

  1. Searching for env will show Edit environment variables for your account
  2. Select Environment Variables
  3. From the System Variables box select PATH
  4. Click New (to add new path)

Change the PATH variable to include the bin directory of your PostgreSQL installation.
then add new path their....[for example]

C:\Program Files\PostgreSQL\12\bin

After that click OK

Open CMD/Command Prompt. Type this to open psql

psql -U username database_name

For Example psql -U postgres test

Now, you will be prompted to give Password for the User. (It will be hidden as a security measure).

Then you are good to go.

How to convert <font size="10"> to px?

Using the data points from the accepted answer you can use polynomial interpolation to obtain a formula.

WolframAlpha Input: interpolating polynomial {{1,.63},{2,.82}, {3,1}, {4,1.13}, {5,1.5}, {6, 2}, {7,3}}

Formula: 0.00223611x^6 - 0.0530417x^5 + 0.496319x^4 - 2.30479x^3 + 5.51644x^2 - 6.16717x + 3.14

And use in Groovy code:

import java.math.*
def convert = {x -> (0.00223611*x**6 - 0.053042*x**5 + 0.49632*x**4 - 2.30479*x**3 + 5.5164*x**2 - 6.167*x + 3.14).setScale(2, RoundingMode.HALF_UP) }
(1..7).each { i -> println(convert(i)) }

setting request headers in selenium

I wanted something a bit slimmer for RSpec/Ruby so that the custom code only had to live in one place. Here's my solution:

/spec/support/selenium.rb
...
RSpec.configure do |config|
  config.after(:suite) do
    $custom_headers = nil
  end
end

module RequestWithExtraHeaders
  def headers
    $custom_headers.each do |key, value|
      self.set_header "HTTP_#{key}", value
    end if $custom_headers

    super
  end
end
class ActionDispatch::Request
  prepend RequestWithExtraHeaders
end

Then in my specs:

/specs/features/something_spec.rb
...
$custom_headers = {"Referer" => referer_string}

How to send custom headers with requests in Swagger UI?

In ASP.NET Core 2 Web API, using Swashbuckle.AspNetCore package 2.1.0, implement a IDocumentFilter:

SwaggerSecurityRequirementsDocumentFilter.cs

using System.Collections.Generic;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace api.infrastructure.filters
{
    public class SwaggerSecurityRequirementsDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument document, DocumentFilterContext context)
        {
            document.Security = new List<IDictionary<string, IEnumerable<string>>>()
            {
                new Dictionary<string, IEnumerable<string>>()
                {
                    { "Bearer", new string[]{ } },
                    { "Basic", new string[]{ } },
                }
            };
        }
    }
}

In Startup.cs, configure a security definition and register the custom filter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        // c.SwaggerDoc(.....

        c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
        {
            Description = "Authorization header using the Bearer scheme",
            Name = "Authorization",
            In = "header"
        });

        c.DocumentFilter<SwaggerSecurityRequirementsDocumentFilter>();
    });
}

In Swagger UI, click on Authorize button and set value for token.

Window to set value

Result:

curl -X GET "http://localhost:5000/api/tenants" -H "accept: text/plain" -H "Authorization: Bearer ABCD123456"

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

You cant blame code all the time sometime may be your url is wrong , double check urls

How to create empty text file from a batch file?

You can also use SET to create a null byte file as follows

set x=x > EmptyFile.txt

Or if you don't want to create an extra variable reassign an existing variable like

set PROMPT=%PROMPT% > EmptyFile.txt

or like this:

set "PROMPT=%PROMPT%" > EmptyFile.txt

How to do vlookup and fill down (like in Excel) in R?

I think you can also use match():

largetable$HouseTypeNo <- with(lookup,
                     HouseTypeNo[match(largetable$HouseType,
                                       HouseType)])

This still works if I scramble the order of lookup.

How do I add space between two variables after a print in Python

This is a stupid/hacky way

print count,    
print conv

Nested Recycler view height doesn't wrap its content

Android Support Library now handles WRAP_CONTENT property as well. Just import this in your gradle.

compile 'com.android.support:recyclerview-v7:23.2.0'

And done!

AngularJS : Why ng-bind is better than {{}} in angular?

If you are not using ng-bind, instead something like this:

<div>
  Hello, {{user.name}}
</div>

you might see the actual Hello, {{user.name}} for a second before user.name is resolved (before the data is loaded)

You could do something like this

<div>
  Hello, <span ng-bind="user.name"></span>
</div>

if that's an issue for you.

Another solution is to use ng-cloak.

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

You have multiple options. Two options are the following.

numpy.sum(boolarr)
numpy.count_nonzero(boolarr)

Here's an example:

>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False,  True],
       [ True, False,  True],
       [ True, False,  True]], dtype=bool)

>>> np.sum(boolarr)
5

Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.

>>> np.count_nonzero(boolarr)
5

How to detect scroll direction

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});

Demo: http://jsfiddle.net/AlienWebguy/Bka6F/

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Change a HTML5 input's placeholder color with CSS

In addition to toscho's answer I've noticed some webkit inconsistencies between Chrome 9-10 and Safari 5 with the CSS properties supported that are worth noting.

Specifically Chrome 9 and 10 do not support background-color, border, text-decoration and text-transform when styling the placeholder.

The full cross-browser comparison is here.

Is it possible to declare two variables of different types in a for loop?

Not possible, but you can do:

float f;
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
  //...
}

Or, explicitly limit the scope of f and i using additional brackets:

{
    float f; 
    int i;
    for (i = 0,f = 0.0; i < 5; i++)
    {
       //...
    }
}

REST API Authentication

  1. Use HTTP Basic Auth to authenticate clients, but treat username/password only as temporary session token.

    The session token is just a header attached to every HTTP request, eg: Authorization: Basic Ym9ic2Vzc2lvbjE6czNjcmV0

    The string Ym9ic2Vzc2lvbjE6czNjcmV0 above is just the string "bobsession1:s3cret" (which is a username/password) encoded in Base64.

  2. To obtain the temporary session token above, provide an API function (eg: http://mycompany.com/apiv1/login) which takes master-username and master-password as an input, creates a temporary HTTP Basic Auth username / password on the server side, and returns the token (eg: Ym9ic2Vzc2lvbjE6czNjcmV0). This username / password should be temporary, it should expire after 20min or so.

  3. For added security ensure your REST service are served over HTTPS so that information are not transferred plaintext

If you're on Java, Spring Security library provides good support to implement above method

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

Laravel 4: how to run a raw SQL?

This is my simplified example of how to run RAW SELECT, get result and access the values.

$res = DB::select('
        select count(id) as c
        from prices p 
        where p.type in (2,3)
    ');
    if ($res[0]->c > 10)
    {
        throw new Exception('WOW');
    }

If you want only run sql script with no return resutl use this

DB::statement('ALTER TABLE products MODIFY COLUMN physical tinyint(1) AFTER points;');

Tested in laravel 5.1

Node.js: How to read a stream into a buffer?

in ts, [].push(bufferPart) is not compatible;

so:

getBufferFromStream(stream: Part | null): Promise<Buffer> {
    if (!stream) {
        throw 'FILE_STREAM_EMPTY';
    }
    return new Promise(
        (r, j) => {
            let buffer = Buffer.from([]);
            stream.on('data', buf => {
               buffer = Buffer.concat([buffer, buf]);
            });
            stream.on('end', () => r(buffer));
            stream.on('error', j);
        }
    );
}

Arduino Tools > Serial Port greyed out

In my case this turned out to be a bad USB hub.

The 'lsusb' command can be used to display all recognized devices. If the unit is not plugged in the option to set the speed will be disabled.

The lsusb command should output something like the string 'Future Technology Devices International, Ltd Bridge(I2C/SPI/UART/FIFO)' if your device is recognized. Mine was an RFDuino

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

Apart from very good responses here, you could try this as well if you want to use your sub query as is.

Approach:

1) Select the desired column (Only 1) from your sub query

2) Use where to map the column name

Code:

 SELECT count(distinct dNum)
 FROM myDB.dbo.AQ
 WHERE A_ID in 
   (
    SELECT A_ID 
    FROM (SELECT DISTINCT TOP (0.1) PERCENT A_ID, COUNT(DISTINCT dNum) AS ud 
          FROM         myDB.dbo.AQ
          WHERE     M > 1 and B = 0 
          GROUP BY A_ID ORDER BY ud DESC
         ) a 
   )

Length of a JavaScript object

_x000D_
_x000D_
<script>_x000D_
myObj = {"key1" : "Hello", "key2" : "Goodbye"};_x000D_
var size = Object.keys(myObj).length;_x000D_
console.log(size);_x000D_
</script>_x000D_
_x000D_
<p id="myObj">The number of <b>keys</b> in <b>myObj</b> are: <script>document.write(size)</script></p>
_x000D_
_x000D_
_x000D_

This works for me:

var size = Object.keys(myObj).length;

check null,empty or undefined angularjs

You can use angular's function called angular.isUndefined(value) returns boolean.

You may read more about angular's functions here: AngularJS Functions (isUndefined)

"Expected an indented block" error?

I also experienced that for example:

This code doesnt work and get the intended block error.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
return self.title

However, when i press tab before typing return self.title statement, the code works.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
    return self.title

Hope, this will help others.

ERROR 1067 (42000): Invalid default value for 'created_at'

Just convert it by this line :

for the new table :

CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

for Existing Table:

Alter ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Source :

https://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html

Regex for allowing alphanumeric,-,_ and space

Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:

  • You can match alphanumeric with a \w, which is the same as [A-Za-z0-9_] in JavaScript (other languages can differ).
  • That leaves - and spaces, which can be combined into a matching set such as [\w\- ]. However, you may want to consider using \s instead of just the space character (\s also matches tabs, and other forms of whitespace)
    • Note that I'm escaping - as \- so that the regex engine doesn't confuse it with a character range like A-Z
  • Last up, you probably want to ensure that the entire string matches by anchoring the start and end via ^ and $

The full regex you're probably looking for is:

/^[\w\-\s]+$/

(Note that the + indicates that there must be at least one character for it to match; use a * instead, if a zero-length string is also ok)

Finally, http://www.regular-expressions.info/ is an awesome reference


Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.

For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/

How to give a delay in loop execution using Qt

C++11 has some portable timer stuff. Check out sleep_for.

Can I set an unlimited length for maxJsonLength in web.config?

You can configure the max length for json requests in your web.config file:

<configuration>
    <system.web.extensions>
        <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="....">
                </jsonSerialization>
            </webServices>
        </scripting>
    </system.web.extensions>
</configuration>

The default value for maxJsonLength is 102400. For more details, see this MSDN page: http://msdn.microsoft.com/en-us/library/bb763183.aspx

Angular2 multiple router-outlet in the same template

You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows.

Advantage of below approach is thats you can avoid dirty looking URL with it. eg: /home(aux:login) etc.

Assuming on load you are bootstraping appComponent.

app.component.html

<div class="layout">
    <div class="page-header">
        //first outlet to load required component
        <router-outlet name='child1'></router-outlet>
    </div>
    <div class="content">
        //second outlet to load required component
        <router-outlet name='child2'></router-outlet>
    </div>
</div>

Add following to your router.

{
    path: 'home',  // you can keep it empty if you do not want /home
    component: 'appComponent',
    children: [
        {
            path: '',
            component: childOneComponent,
            outlet: 'child1'
        },
        {
            path: '',
            component: childTwoComponent,
            outlet: 'child2'
        }
    ]
}

Now when /home is loaded appComponent will get load with allocated template, then angular router will check the route and load the children component in specified router outlet on the basis of name.

Like above you can configure your router to have multiple router-outlet in same route.

Control the size of points in an R scatterplot?

pch=20 returns a symbol sized between "." and 19.

It's a filled symbol (which is probably what you want).

Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,

dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)

with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
                  ann=F, bg="steelblue2", fg=NULL))

Graph example

How to find a user's home directory on linux or unix?

Try this on Java:

System.out.println("OS: " + System.getProperty("os.name") + ", USER DIRECTORY: " + System.getProperty("user.home"));

How to get the Power of some Integer in Swift language?

Array(repeating: a, count: b).reduce(1, *)

How to get current time and date in Android

For the current date and time, use:

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

Which outputs:

Feb 27, 2012 5:41:23 PM

Replace only text inside a div using jquery

If you actually know the text you are going to replace you could use

$('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"';

http://jsfiddle.net/5rWwh/

Or

$('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"';

$('#one').contents(':not(*)') selects non-element child nodes in this case text nodes and the second node is the one we want to replace.

http://jsfiddle.net/5rWwh/1/

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

Excel VBA Password via Hex Editor

I have your answer, as I just had the same problem today:

Someone made a working vba code that changes the vba protection password to "macro", for all excel files, including .xlsm (2007+ versions). You can see how it works by browsing his code.

This is the guy's blog: http://lbeliarl.blogspot.com/2014/03/excel-removing-password-from-vba.html Here's the file that does the work: https://docs.google.com/file/d/0B6sFi5sSqEKbLUIwUTVhY3lWZE0/edit

Pasted from a previous post from his blog:

For Excel 2007/2010 (.xlsm) files do following steps:

  1. Create a new .xlsm file.
  2. In the VBA part, set a simple password (for instance 'macro').
  3. Save the file and exit.
  4. Change file extention to '.zip', open it by any archiver program.
  5. Find the file: 'vbaProject.bin' (in 'xl' folder).
  6. Extract it from archive.
  7. Open the file you just extracted with a hex editor.
  8. Find and copy the value from parameter DPB (value in quotation mark), example: DPB="282A84CBA1CBA1345FCCB154E20721DE77F7D2378D0EAC90427A22021A46E9CE6F17188A". (This value generated for 'macro' password. You can use this DPB value to skip steps 1-8)

  9. Do steps 4-7 for file with unknown password (file you want to unlock).

  10. Change DBP value in this file on value that you have copied in step 8.

    If copied value is shorter than in encrypted file you should populate missing characters with 0 (zero). If value is longer - that is not a problem (paste it as is).

  11. Save the 'vbaProject.bin' file and exit from hex editor.

  12. Replace existing 'vbaProject.bin' file with modified one.
  13. Change extention from '.zip' back to '.xlsm'
  14. Now, open the excel file you need to see the VBA code in. The password for the VBA code will simply be macro (as in the example I'm showing here).

How to open the terminal in Atom?

  1. Open your Atom IDE
  2. press ctrl+shift+P and search for "platformio-ide-terminal" package
  3. press install
  4. once installed press ctrl+~ (tilde above tab key in a standard keyboard)
  5. terminal opens enjoy!!!

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

SSL InsecurePlatform error when using Requests package

if you just want to stopping insecure warning like:

/usr/lib/python3/dist-packages/urllib3/connectionpool.py:794: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html InsecureRequestWarning)

do:

requests.METHOD("https://www.google.com", verify=False)

verify=False

is the key, followings are not good at it:

requests.packages.urllib3.disable_warnings()

or

urllib3.disable_warnings()

but, you HAVE TO know, that might cause potential security risks.

spark submit add multiple jars in classpath

You can use --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') to include entire folder of Jars. So, spark-submit -- class com.yourClass \ --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') \ ...

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

You can solve it be running on Google API emulator.

To run on Google API emulator, open your Android SDK & AVD Manager > Available packages > Google Repos > select those Google API levels that you need to test on.

After installing them, add them as virtual device and run.

Best way to simulate "group by" from bash?

for summing up multiple fields, based on a group of existing fields, use the example below : ( replace the $1, $2, $3, $4 according to your requirements )

cat file

US|A|1000|2000
US|B|1000|2000
US|C|1000|2000
UK|1|1000|2000
UK|1|1000|2000
UK|1|1000|2000

awk 'BEGIN { FS=OFS=SUBSEP="|"}{arr[$1,$2]+=$3+$4 }END {for (i in arr) print i,arr[i]}' file

US|A|3000
US|B|3000
US|C|3000
UK|1|9000

How can I dynamically switch web service addresses in .NET without a recompile?

I've struggled with this issue for a few days and finally the light bulb clicked. The KEY to being able to change the URL of a webservice at runtime is overriding the constructor, which I did with a partial class declaration. The above, setting the URL behavior to Dynamic must also be done.

This basically creates a web-service wrapper where if you have to reload web service at some point, via add service reference, you don't loose your work. The Microsoft help for Partial classes specially states that part of the reason for this construct is to create web service wrappers. http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.100).aspx

// Web Service Wrapper to override constructor to use custom ConfigSection 
// app.config values for URL/User/Pass
namespace myprogram.webservice
{
    public partial class MyWebService
    {
        public MyWebService(string szURL)
        {
            this.Url = szURL;
            if ((this.IsLocalFileSystemWebService(this.Url) == true))
            {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else
            {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }
    }
}

CSS: 100% font size - 100% of what?

The browser default which is something like 16pt for Firefox, You can check by going into Firefox options, clicking the Content tab, and checking the font size. You can do the same for other browsers as well.

I personally like to control the default font size of my websites, so in a CSS file that is included in every page I will set the BODY default, like so:

body {
    font-family: Helvetica, Arial, sans-serif;
    font-size: 14px
}

Now the font-size of all my HTML tags will inherit a font-size of 14px.

Say that I want a all divs to have a font size 10% bigger than body, I simply do:

div {
    font-size: 110%
}

Now any browser that view my pages will autmoatically make all divs 10% bigger than that of the body, which should be something like 15.4px.

If I want the font-size of all div's to be 10% smaller, I do:

div {
    font-size: 90%
}

This will make all divs have a font-size of 12.6px.

Also you should know that since font-size is inherited, that each nested div will decrease in font size by 10%, so:

<div>Outer DIV.
    <div>Inner DIV</div>
</div>

The inner div will have a font-size of 11.34px (90% of 12.6px), which may not have been intended.

This can help in the explanation: http://www.w3.org/TR/2011/REC-CSS2-20110607/syndata.html#value-def-percentage

Text overflow ellipsis on two lines

          text-overflow: ellipsis;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          line-height: 36px;
          max-height: 18px;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;

I've found a combo of both line-clamp and line-height works :D

ExecuteReader: Connection property has not been initialized

use this and pass connection object :

 SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')",conn);

How do I set the default locale in the JVM?

You can do this:

enter image description here

enter image description here

And to capture locale. You can do this:

private static final String LOCALE = LocaleContextHolder.getLocale().getLanguage()
            + "-" + LocaleContextHolder.getLocale().getCountry();

Which data structures and algorithms book should I buy?

If you don't need in a complete reference to the most part of algorithms and data structures that are in use and just want to get acquainted with common techniques I would recommend something more lightweight than Cormen, Sedgewick or Knuth. I think, Algorithms and Data Structures by N. Wirth is not as bad choice even in spite of it was printed far ago.

SQL command to display history of queries

Look at ~/.myslgui/query-browser/history.xml here you can find the last queries made with mysql_query_browser (some days old)

Import PEM into Java Key Store

In my case I had a pem file which contained two certificates and an encrypted private key to be used in mutual SSL authentication. So my pem file looked like this:

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

-----BEGIN RSA PRIVATE KEY-----

Proc-Type: 4,ENCRYPTED

DEK-Info: DES-EDE3-CBC,C8BF220FC76AA5F9

...

-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----

...

-----END CERTIFICATE-----

Here is what I did

Split the file into three separate files, so that each one contains just one entry, starting with ---BEGIN.. and ending with ---END.. lines. Lets assume we now have three files: cert1.pem, cert2.pem, and pkey.pem.

Convert pkey.pem into DER format using openssl and the following syntax:

openssl pkcs8 -topk8 -nocrypt -in pkey.pem -inform PEM -out pkey.der -outform DER

Note, that if the private key is encrypted you need to supply a password( obtain it from the supplier of the original pem file ) to convert to DER format, openssl will ask you for the password like this: "enter a passphrase for pkey.pem: ".

If conversion is successful, you will get a new file called pkey.der.

Create a new java keystore and import the private key and the certificates:

String keypass = "password";  // this is a new password, you need to come up with to protect your java key store file
String defaultalias = "importkey";
KeyStore ks = KeyStore.getInstance("JKS", "SUN");

// this section does not make much sense to me, 
// but I will leave it intact as this is how it was in the original example I found on internet:   
ks.load( null, keypass.toCharArray());
ks.store( new FileOutputStream ( "mykeystore"  ), keypass.toCharArray());
ks.load( new FileInputStream ( "mykeystore" ),    keypass.toCharArray());
// end of section..


// read the key file from disk and create a PrivateKey

FileInputStream fis = new FileInputStream("pkey.der");
DataInputStream dis = new DataInputStream(fis);
byte[] bytes = new byte[dis.available()];
dis.readFully(bytes);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

byte[] key = new byte[bais.available()];
KeyFactory kf = KeyFactory.getInstance("RSA");
bais.read(key, 0, bais.available());
bais.close();

PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec ( key );
PrivateKey ff = kf.generatePrivate (keysp);


// read the certificates from the files and load them into the key store:

Collection  col_crt1 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert1.pem"));
Collection  col_crt2 = CertificateFactory.getInstance("X509").generateCertificates(new FileInputStream("cert2.pem"));

Certificate crt1 = (Certificate) col_crt1.iterator().next();
Certificate crt2 = (Certificate) col_crt2.iterator().next();
Certificate[] chain = new Certificate[] { crt1, crt2 };

String alias1 = ((X509Certificate) crt1).getSubjectX500Principal().getName();
String alias2 = ((X509Certificate) crt2).getSubjectX500Principal().getName();

ks.setCertificateEntry(alias1, crt1);
ks.setCertificateEntry(alias2, crt2);

// store the private key
ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), chain );

// save the key store to a file         
ks.store(new FileOutputStream ( "mykeystore" ),keypass.toCharArray());

(optional) Verify the content of your new key store:

$ keytool -list -keystore mykeystore -storepass password

Keystore type: JKS Keystore provider: SUN

Your keystore contains 3 entries:

  • cn=...,ou=...,o=.., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 2C:B8: ...

  • importkey, Sep 2, 2014, PrivateKeyEntry, Certificate fingerprint (SHA1): 9C:B0: ...

  • cn=...,o=...., Sep 2, 2014, trustedCertEntry, Certificate fingerprint (SHA1): 83:63: ...

(optional) Test your certificates and private key from your new key store against your SSL server: ( You may want to enable debugging as an VM option: -Djavax.net.debug=all )

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        SSLSocketFactory factory = sclx.getSocketFactory();
        SSLSocket socket = (SSLSocket) factory.createSocket( "192.168.1.111", 443 );
        socket.startHandshake();

        //if no exceptions are thrown in the startHandshake method, then everything is fine..

Finally register your certificates with HttpsURLConnection if plan to use it:

        char[] passw = "password".toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(new FileInputStream ( "mykeystore" ), passw );

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passw);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();

        SSLContext sclx = SSLContext.getInstance("TLS");
        sclx.init( kmf.getKeyManagers(), tm, null);

        HostnameVerifier hv = new HostnameVerifier()
        {
            public boolean verify(String urlHostName, SSLSession session)
            {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost()))
                {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory( sclx.getSocketFactory() );
        HttpsURLConnection.setDefaultHostnameVerifier(hv);

How to resolve git's "not something we can merge" error

As shown in How does "not something we can merge" arise?, this error can arise from a typo in the branch name because you are trying to pull a branch that doesn't exist.

If that is not the problem (as in my case), it is likely that you don't have a local copy of the branch that you want to merge. Git requires local knowledge of both branches in order to merge those branches. You can resolve this by checking out the branch to merge and then going back to the branch you want to merge into.

git checkout branch-name
git checkout master
git merge branch-name

This should work, but if you receive an error saying

error: pathspec 'remote-name/branch-name' did not match any file(s) known to git.

you need to fetch the remote (probably, but not necessarily, "origin") before checking out the branch:

git fetch remote-name

How to create a drop shadow only on one side of an element?

UPDATE 4

Same like update 3 but with modern css (=less rules) so that no special positioning on the pseudo element is required.

_x000D_
_x000D_
#box {_x000D_
    background-color: #3D6AA2;_x000D_
    width: 160px;_x000D_
    height: 90px;_x000D_
    position: absolute;_x000D_
    top: calc(10% - 10px);_x000D_
    left: calc(50% - 80px);_x000D_
}_x000D_
_x000D_
.box-shadow:after {_x000D_
    content:"";_x000D_
    position:absolute;_x000D_
    width:100%;_x000D_
    bottom:1px;_x000D_
    z-index:-1;_x000D_
    transform:scale(.9);_x000D_
    box-shadow: 0px 0px 8px 2px #000000;_x000D_
}
_x000D_
<div id="box" class="box-shadow"></div>
_x000D_
_x000D_
_x000D_

UPDATE 3

All my previous answers have been using extra markup to get create this effect, which is not necessarily needed. I think this a much cleaner solution... the only trick is playing around with the values to get the right positioning of the shadow as well as the right strength/opacity of the shadow. Here's a new fiddle, using pseudo-elements:

http://jsfiddle.net/UnsungHero97/ARRRZ/2/

HTML

<div id="box" class="box-shadow"></div>

CSS

#box {
    background-color: #3D6AA2;
    width: 160px;
    height: 90px;
    margin-top: -45px;
    margin-left: -80px;
    position: absolute;
    top: 50%;
    left: 50%;
}

.box-shadow:after {
    content: "";
    width: 150px;
    height: 1px;
    margin-top: 88px;
    margin-left: -75px;
    display: block;
    position: absolute;
    left: 50%;
    z-index: -1;
    -webkit-box-shadow: 0px 0px 8px 2px #000000;
       -moz-box-shadow: 0px 0px 8px 2px #000000;
            box-shadow: 0px 0px 8px 2px #000000;
}

UPDATE 2

Apparently, you can do this with just an extra parameter to the box-shadow CSS as everyone else just pointed out. Here's the demo:

http://jsfiddle.net/K88H9/821/

CSS

-webkit-box-shadow: 0 4px 4px -2px #000000;
   -moz-box-shadow: 0 4px 4px -2px #000000;
        box-shadow: 0 4px 4px -2px #000000;

This would be a better solution. The extra parameter that is added is described as:

The fourth length is a spread distance. Positive values cause the shadow shape to expand in all directions by the specified radius. Negative values cause the shadow shape to contract.

UPDATE

Check out the demo at jsFiddle: http://jsfiddle.net/K88H9/4/

What I did was create a "shadow element" that would hide behind the actual element that you would want to have a shadow. I made the width of the "shadow element" to be exactly less wide than the actual element by 2 times the shadow you specify; then I aligned it properly.

HTML

<div id="wrapper">
    <div id="element"></div>
    <div id="shadow"></div>
</div>

CSS

#wrapper {
    width: 84px;
    position: relative;
}
#element {
    background-color: #3D668F;
    height: 54px;
    width: 100%;
    position: relative;
    z-index: 10;
}
#shadow {
    background-color: #3D668F;
    height: 8px;
    width: 80px;
    margin-left: -40px;
    position: absolute;
    bottom: 0px;
    left: 50%;
    z-index: 5;
    -webkit-box-shadow: 0px 2px 4px #000000;
       -moz-box-shadow: 0px 2px 4px #000000;
            box-shadow: 0px 2px 4px #000000;
}

Original Answer

Yes, you can do this with the same syntax you have provided. The first value controls the horizontal positioning and the second value controls the vertical positioning. So just set the first value to 0px and the second to whatever offset you'd like as follows:

-webkit-box-shadow: 0px 5px #000000;
   -moz-box-shadow: 0px 5px #000000;
        box-shadow: 0px 5px #000000;

For more info on box shadows, check out these:

I hope this helps.

Check if a string contains a number

You can accomplish this as follows:

if a_string.isdigit(): do_this() else: do_that()

https://docs.python.org/2/library/stdtypes.html#str.isdigit

Using .isdigit() also means not having to resort to exception handling (try/except) in cases where you need to use list comprehension (try/except is not possible inside a list comprehension).

How to resolve 'npm should be run outside of the node repl, in your normal shell'

you just open command prompt, then enter in c:/>('cd../../') then npm install -g cordova enter image description here

Git submodule push

Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

recurse-submodules=<check|on-demand>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

So you could push everything in one go with (from the parent repo) a:

git push --recurse-submodules=on-demand

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.


With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.

See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe).
(Merged by Junio C Hamano -- gitster -- in commit 5d35d72, 21 Dec 2015)

push: add recurseSubmodules config option

The --recurse-submodules command line parameter has existed for some time but it has no config file equivalent.

Following the style of the corresponding parameter for git fetch, let's invent push.recurseSubmodules to provide a default for this parameter.
This also requires the addition of --recurse-submodules=no to allow the configuration to be overridden on the command line when required.

The most straightforward way to implement this appears to be to make push use code in submodule-config in a similar way to fetch.

The git config doc now include:

push.recurseSubmodules:

Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.

  • If the value is 'check', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.
  • If the value is 'on-demand' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -
  • If the value is 'no' then default behavior of ignoring submodules when pushing is retained.

You may override this configuration at time of push by specifying '--recurse-submodules=check|on-demand|no'.

So:

git config push.recurseSubmodules on-demand
git push

Git 2.12 (Q1 2017)

git push --dry-run --recurse-submodules=on-demand will actually work.

See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 12cf113, 16 Dec 2016)

push run with --dry-run doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.

Teach push to respect the --dry-run option when configured to recursively push submodules 'on-demand'.
This is done by passing the --dry-run flag to the child process which performs a push for a submodules when performing a dry-run.


And still in Git 2.12, you now havea "--recurse-submodules=only" option to push submodules out without pushing the top-level superproject.

See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 792e22e, 31 Jan 2017)

How can I copy the output of a command directly into my clipboard?

on Wayland xcopy doesn't seem to work, use wl-clipboard instead. e.g. on fedora

sudo dnf install wl-clipboard

tree | wl-copy

wl-paste > file

Location Services not working in iOS 8

According to the Apple docs:

As of iOS 8, the presence of a NSLocationWhenInUseUsageDescription or a NSLocationAlwaysUsageDescription key value in your app's Info.plist file is required. It's then also necessary to request permission from the user prior to registering for location updates, either by calling [self.myLocationManager requestWhenInUseAuthorization] or [self.myLocationManager requestAlwaysAuthorization] depending on your need. The string you entered into the Info.plist will then be displayed in the ensuing dialog.

If the user grants permission, it's business as usual. If they deny permission, then the delegate is not informed of location updates.

Parse JSON String into a Particular Object Prototype in JavaScript

Do you want to add JSON serialization/deserialization functionality, right? Then look at this:

You want to achieve this:

UML

toJson() is a normal method.
fromJson() is a static method.

Implementation:

var Book = function (title, author, isbn, price, stock){
    this.title = title;
    this.author = author;
    this.isbn = isbn;
    this.price = price;
    this.stock = stock;

    this.toJson = function (){
        return ("{" +
            "\"title\":\"" + this.title + "\"," +
            "\"author\":\"" + this.author + "\"," +
            "\"isbn\":\"" + this.isbn + "\"," +
            "\"price\":" + this.price + "," +
            "\"stock\":" + this.stock +
        "}");
    };
};

Book.fromJson = function (json){
    var obj = JSON.parse (json);
    return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};

Usage:

var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}

var book = Book.fromJson (json);
alert (book.title); //prints: t

Note: If you want you can change all property definitions like this.title, this.author, etc by var title, var author, etc. and add getters to them to accomplish the UML definition.

How to open in default browser in C#

Try this , old school way ;)

public static void openit(string x)
    {
        System.Diagnostics.Process.Start("cmd", "/C start" + " " + x);
    }

using : openit("www.google.com");

How to add two strings as if they were numbers?

Try this if you are looking for simple Javascript code and want to use two input box and add numbers from the two value. Here's the code.

    Enter the first number: <input type="text" id="num1" /><br />
    Enter the seccond number: <input type="text" id="num2" /><br />
    <input type="button" onclick="call()" value="Add"/>

    <script type="text/javascript">
    function call(){
    var q=parseInt(document.getElementById("num1").value);
    var w=parseInt(document.getElementById("num2").value);
    var result=q+w;
    }
    </script>

for more details please visit http://informativejavascript.blogspot.nl/2012/12/javascript-basics.html

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

SQL Query to find the last day of the month

Try this one -

CREATE FUNCTION [dbo].[udf_GetLastDayOfMonth] 
(
    @Date DATETIME
)
RETURNS DATETIME
AS
BEGIN

    RETURN DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @Date) + 1, 0))

END

Query:

DECLARE @date DATETIME
SELECT @date = '2013-05-31 15:04:10.027'

SELECT DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, @date) + 1, 0))

Output:

-----------------------
2013-05-31 00:00:00.000

Tomcat 8 is not able to handle get request with '|' in query parameters?

Adding "relaxedQueryChars" attribute to the server.xml worked for me :

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="443" URIEncoding="UTF-8" relaxedQueryChars="[]|{}^&#x5c;&#x60;&quot;&lt;&gt;"/>

How do I get the height of a div's full content with jQuery?

If you can possibly help it, DO NOT USE .scrollHeight.

.scrollHeight does not yield the same kind of results in different browsers in certain circumstances (most prominently while scrolling).

For example:

<div id='outer' style='width:100px; height:350px; overflow-y:hidden;'>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
<div style='width:100px; height:150px;'></div>
</div>

If you do

console.log($('#outer').scrollHeight);

you'll get 900px in Chrome, FireFox and Opera. That's great.

But, if you attach a wheelevent / wheel event to #outer, when you scroll it, Chrome will give you a constant value of 900px (correct) but FireFox and Opera will change their values as you scroll down (incorrect).

A very simple way to do this is like so (a bit of a cheat, really). (This example works while dynamically adding content to #outer as well):

$('#outer').css("height", "auto");
var outerContentsHeight = $('#outer').height();
$('#outer').css("height", "350px");

console.log(outerContentsHeight); //Should get 900px in these 3 browsers

The reason I pick these three browsers is because all three can disagree on the value of .scrollHeight in certain circumstances. I ran into this issue making my own scrollpanes. Hope this helps someone.

Take a char input from the Scanner

you just need to write this for getting value in char type.

char c = reader.next().charAt(0);

How to fix nginx throws 400 bad request headers on any header testing tools?

Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line

error_log /var/log/nginx/error.log debug;

And then restart nginx:

sudo service nginx restart

That way you can detail what nginx is doing and why it is returning the status code 400.

How to display Woocommerce product price by ID number on a custom page?

Other answers work, but

To get the full/default price:

$product->get_price_html();

Select all child elements recursively in CSS

The rule is as following :

A B 

B as a descendant of A

A > B 

B as a child of A

So

div.dropdown *

and not

div.dropdown > *

How to convert CSV to JSON in Node.js

Using ES6

const toJSON = csv => {
    const lines = csv.split('\n')
    const result = []
    const headers = lines[0].split(',')

    lines.map(l => {
        const obj = {}
        const line = l.split(',')

        headers.map((h, i) => {
            obj[h] = line[i]
        })

        result.push(obj)
    })

    return JSON.stringify(result)
}

const csv = `name,email,age
francis,[email protected],33
matty,[email protected],29`

const data = toJSON(csv)

console.log(data)

Output

// [{"name":"name","email":"email","age":"age"},{"name":"francis","email":"[email protected]","age":"33"},{"name":"matty","email":"[email protected]","age":"29"}]

Java 8 Stream and operation on arrays

Be careful if you have to deal with large numbers.

int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0

The sum above is not 2 * Integer.MIN_VALUE. You need to do this in this case.

long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct