Programs & Examples On #Pdfview

A Macintosh or iOS object that encapsulates the functionality of PDFKit and which can be dropped into an interface using Xcode's Interface Builder.

count number of characters in nvarchar column

You can find the number of characters using system function LEN. i.e.

SELECT LEN(Column) FROM TABLE

Exclude Blank and NA in R

Don't know exactly what kind of dataset you have, so I provide general answer.

x <- c(1,2,NA,3,4,5)
y <- c(1,2,3,NA,6,8)
my.data <- data.frame(x, y)
> my.data
   x  y
1  1  1
2  2  2
3 NA  3
4  3 NA
5  4  6
6  5  8
# Exclude rows with NA values
my.data[complete.cases(my.data),]
  x y
1 1 1
2 2 2
5 4 6
6 5 8

SQL Server convert select a column and convert it to a string

This a stab at creating a reusable column to comma separated string. In this case, I only one strings that have values and I do not want empty strings or nulls.

First I create a user defined type that is a one column table.

-- ================================
-- Create User-defined Table Type
-- ================================
USE [RSINET.MVC]
GO

-- Create the data type
CREATE TYPE [dbo].[SingleVarcharColumn] AS TABLE 
(
    data NVARCHAR(max)
)
GO

The real purpose of the type is to simplify creating a scalar function to put the column into comma separated values.

-- ================================================
-- Template generated from Template Explorer using:
-- Create Scalar Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  Rob Peterson        
-- Create date: 8-26-2015
-- Description: This will take a single varchar column and convert it to
-- comma separated values.
-- =============================================
CREATE FUNCTION fnGetCommaSeparatedString 
(
    -- Add the parameters for the function here
    @column AS [dbo].[SingleVarcharColumn] READONLY
)
RETURNS VARCHAR(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @result VARCHAR(MAX)
DECLARE @current VARCHAR(MAX)
DECLARE @counter INT
DECLARE @c CURSOR

SET @result = ''
SET @counter = 0
-- Add the T-SQL statements to compute the return value here
SET @c = CURSOR FAST_FORWARD
    FOR SELECT COALESCE(data,'') FROM @column
    OPEN @c
    FETCH NEXT FROM @c
    INTO @current
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF @result <> '' AND @current <> '' SET @result = @result + ',' + @current
        IF @result = '' AND @current <> '' SET @result = @current
    FETCH NEXT FROM @c
    INTO @current
    END
    CLOSE @c
    DEALLOCATE @c
-- Return the result of the function
RETURN @result

END
GO

Now, to use this. I select the column I want to convert to a comma separated string into the SingleVarcharColumn Type.

DECLARE @s as SingleVarcharColumn

INSERT INTO @s VALUES ('rob')
INSERT INTO @s VALUES ('paul')
INSERT INTO @s VALUES ('james')
INSERT INTO @s VALUES (null)


INSERT INTO @s
SELECT iClientID FROM [dbo].tClient

SELECT [dbo].fnGetCommaSeparatedString(@s)

To get results like this.

rob,paul,james,1,9,10,11,12,13,14,15,16,18,19,23,26,27,28,29,30,31,32,34,35,36,37,38,39,40,41,42,44,45,46,47,48,49,50,52,53,54,56,57,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,81,82,83,84,87,88,90,91,92,93,94,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159

I made my data column in my SingleVarcharColumn type an NVARCHAR(MAX) which may hurt performance, but I flexibility was what I was looking for and it runs fast enough for my purposes. It would probably be faster if it were a varchar and if it had a fixed and smaller width, but I have not tested it.

Setting value of active workbook in Excel VBA

You're probably after Set wbOOR = ThisWorkbook

Just to clarify

ThisWorkbook will always refer to the workbook the code resides in

ActiveWorkbook will refer to the workbook that is active

Be careful how you use this when dealing with multiple workbooks. It really depends on what you want to achieve as to which is the best option.

Sorting HashMap by values

found a solution but not sure the performance if the map has large size, useful for normal case.

   /**
     * sort HashMap<String, CustomData> by value
     * CustomData needs to provide compareTo() for comparing CustomData
     * @param map
     */

    public void sortHashMapByValue(final HashMap<String, CustomData> map) {
        ArrayList<String> keys = new ArrayList<String>();
        keys.addAll(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                CustomData val1 = map.get(lhs);
                CustomData val2 = map.get(rhs);
                if (val1 == null) {
                    return (val2 != null) ? 1 : 0;
                } else if (val1 != null) && (val2 != null)) {
                    return = val1.compareTo(val2);
                }
                else {
                    return 0;
                }
            }
        });

        for (String key : keys) {
            CustomData c = map.get(key);
            if (c != null) {
                Log.e("key:"+key+", CustomData:"+c.toString());
            } 
        }
    }

How do you get the contextPath from JavaScript, the right way?

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

<html>
    <head>
        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
    <body>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

main.js

var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

Android : How to read file in bytes?

here it's a simple:

File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
    buf.read(bytes, 0, bytes.length);
    buf.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Add permission in manifest.xml:

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

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

Just as a quick addition to this. I was having the same problem and while Webpack was compiling my tests and the application was running fine. When I was importing my component into the test file I was using the incorrect case on one of the imports and that was causing the same error.

import myComponent from '../../src/components/myComponent'

Should have been

import myComponent from '../../src/components/MyComponent'

Note that the import name myComponent depends on the name of the export inside the MyComponent file.

Convert Unicode data to int in python

In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.

So to convert string limit="100" to a number, you need to do

limit = int(limit) # will return new object (integer) and assign to "limit"

If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:

def int_in_place(mutable):
    mutable[0] = int(mutable[0])

mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer

But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).

Click event on select option element in chrome

The easy way to change the select, and update it is this.

// BY id
$('#select_element_selector').val('value').change();

another example:

//By tag
$('[name=selectxD]').val('value').change();

another example:

$("#select_element_selector").val('value').trigger('chosen:updated');

How do you split a list into evenly sized chunks?

Use list comprehensions:

l = [1,2,3,4,5,6,7,8,9,10,11,12]
k = 5 #chunk size
print [tuple(l[x:y]) for (x, y) in [(x, x+k) for x in range(0, len(l), k)]]

C++ compile time error: expected identifier before numeric constant

Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:

Attribute() : name(5),val(5,0) {}

adding onclick event to dynamically added button?

I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:

//Bad code.
var btn = document.createElement('button');
btn.onClick = function() {  console.log("hey");  }

to this:

//Working Code.  I don't like it, but it works. 
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);

document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){  console.log("hey");  }

I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.

Git - how delete file from remote repository

if you just commit your deleted file and push. It should then be removed from the remote repo.

Greyscale Background Css Images

Here you go:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(yourimagehere.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(yourimagehere.jpg);
    }
</style>
</head>
<body>
    <div class="nongrayscale">
        this is a non-grayscale of the bg image
    </div>
    <div class="grayscale">
        this is a grayscale of the bg image
    </div>
</body>
</html>

Tested it in FireFox, Chrome and IE. I've also attached an image to show my results of my implementation of this.Grayscale Background Image in DIV Sample

EDIT: Also, if you want the image to just toggle back and forth with jQuery, here's the page source for that...I've included the web link to jQuery and and image that's online so you should just be able to copy/paste to test it out:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
    }
</style>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#image").mouseover(function () {
                $(".nongrayscale").removeClass().fadeTo(400,0.8).addClass("grayscale").fadeTo(400, 1);
            });
            $("#image").mouseout(function () {
                $(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
            });
        });
</script>
</head>
<body>
    <div id="image" class="nongrayscale">
        rollover this image to toggle grayscale
    </div>
</body>
</html>

EDIT 2 (For IE10-11 Users): The solution above will not work with the changes Microsoft has made to the browser as of late, so here's an updated solution that will allow you to grayscale (or desaturate) your images.

_x000D_
_x000D_
<svg>_x000D_
  <defs>_x000D_
    <filter xmlns="http://www.w3.org/2000/svg" id="desaturate">_x000D_
      <feColorMatrix type="saturate" values="0" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image xlink:href="http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg" width="600" height="600" filter="url(#desaturate)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Code-first vs Model/Database-first

Quoting the relevant parts from http://www.itworld.com/development/405005/3-reasons-use-code-first-design-entity-framework

3 reasons to use code first design with Entity Framework

1) Less cruft, less bloat

Using an existing database to generate a .edmx model file and the associated code models results in a giant pile of auto generated code. You’re implored never to touch these generated files lest you break something, or your changes get overwritten on the next generation. The context and initializer are jammed together in this mess as well. When you need to add functionality to your generated models, like a calculated read only property, you need to extend the model class. This ends up being a requirement for almost every model and you end up with an extension for everything.

With code first your hand coded models become your database. The exact files that you’re building are what generate the database design. There are no additional files and there is no need to create a class extension when you want to add properties or whatever else that the database doesn't need to know about. You can just add them into the same class as long as you follow the proper syntax. Heck, you can even generate a Model.edmx file to visualize your code if you want.

2) Greater Control

When you go DB first, you’re at the mercy of what gets generated for your models for use in your application. Occasionally the naming convention is undesirable. Sometimes the relationships and associations aren't quite what you want. Other times non transient relationships with lazy loading wreak havoc on your API responses.

While there is almost always a solution for model generation problems you might run into, going code first gives you complete and fine grained control from the get go. You can control every aspect of both your code models and your database design from the comfort of your business object. You can precisely specify relationships, constraints, and associations. You can simultaneously set property character limits and database column sizes. You can specify which related collections are to be eager loaded, or not be serialized at all. In short, you are responsible for more stuff but you’re in full control of your app design.

3)Database Version Control

This is a big one. Versioning databases is hard, but with code first and code first migrations, it’s much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database. You’re responsible for controlling your context initialization which can help you do things like seed fixed business data. You’re also responsible for creating code first migrations.

When you first enable migrations, a configuration class and an initial migration are generated. The initial migration is your current schema or your baseline v1.0. From that point on you will add migrations which are timestamped and labeled with a descriptor to help with ordering of versions. When you call add-migration from the package manager, a new migration file will be generated containing everything that has changed in your code model automatically in both an UP() and DOWN() function. The UP function applies the changes to the database, the DOWN function removes those same changes in the event you want to rollback. What’s more, you can edit these migration files to add additional changes such as new views, indexes, stored procedures, and whatever else. They will become a true versioning system for your database schema.

Neither BindingResult nor plain target object for bean name available as request attr

Try adding a BindingResult parameter to methods annotated with @RequestMapping which have a @ModelAttribute annotated parameters. After each @ModelAttribute parameter, Spring looks for a BindingResult in the next parameter position (order is important).

So try changing:

@RequestMapping(method = RequestMethod.POST)
public String loadCharts(HttpServletRequest request, ModelMap model, @ModelAttribute("sideForm") Chart chart) 
...

To:

@RequestMapping(method = RequestMethod.POST)
public String loadCharts(@ModelAttribute("sideForm") Chart chart, BindingResult bindingResult, HttpServletRequest request, ModelMap model) 
...

MVC Razor @foreach

a reply to @DarinDimitrov for a case where i have used foreach in a razor view.

<li><label for="category">Category</label>
        <select id="category">
            <option value="0">All</option>
            @foreach(Category c in Model.Categories)
            {
                <option title="@c.Description" value="@c.CategoryID">@c.Name</option>
            }
        </select>
</li>

Copying from one text file to another using Python

The oneliner:

open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

Recommended with with:

with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:
        f1.writelines(lines)

Using less memory:

with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:
                f1.write(line) 

How can I create an object and add attributes to it?

Other way i see, this way:

import maya.cmds

def getData(objets=None, attrs=None):
    di = {}
    for obj in objets:
        name = str(obj)
        di[name]=[]
        for at in attrs:
            di[name].append(cmds.getAttr(name+'.'+at)[0])
    return di

acns=cmds.ls('L_vest_*_',type='aimConstraint')
attrs=['offset','aimVector','upVector','worldUpVector']

getData(acns,attrs)

Convert IQueryable<> type object to List<T> type?

Here's a couple of extension methods I've jury-rigged together to convert IQueryables and IEnumerables from one type to another (i.e. DTO). It's mainly used to convert from a larger type (i.e. the type of the row in the database that has unneeded fields) to a smaller one.

The positive sides of this approach are:

  • it requires almost no code to use - a simple call to .Transform<DtoType>() is all you need
  • it works just like .Select(s=>new{...}) i.e. when used with IQueryable it produces the optimal SQL code, excluding Type1 fields that DtoType doesn't have.

LinqHelper.cs:

public static IQueryable<TResult> Transform<TResult>(this IQueryable source)
{
    var resultType = typeof(TResult);
    var resultProperties = resultType.GetProperties().Where(p => p.CanWrite);

    ParameterExpression s = Expression.Parameter(source.ElementType, "s");

    var memberBindings =
        resultProperties.Select(p =>
            Expression.Bind(typeof(TResult).GetMember(p.Name)[0], Expression.Property(s, p.Name))).OfType<MemberBinding>();

    Expression memberInit = Expression.MemberInit(
        Expression.New(typeof(TResult)),
        memberBindings
        );

    var memberInitLambda = Expression.Lambda(memberInit, s);

    var typeArgs = new[]
        {
            source.ElementType, 
            memberInit.Type
        };

    var mc = Expression.Call(typeof(Queryable), "Select", typeArgs, source.Expression, memberInitLambda);

    var query = source.Provider.CreateQuery<TResult>(mc);

    return query;
}

public static IEnumerable<TResult> Transform<TResult>(this IEnumerable source)
{
    return source.AsQueryable().Transform<TResult>();
}

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

Clear icon inside input text

You could use a reset button styled with an image...

<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="type here" />
   <input type="reset" value="" alt="clear" />
</form>

<style>
   input[type="text"]
   {
      height: 38px;
      font-size: 15pt;
   }

   input[type="text"]:invalid + input[type="reset"]{
     display: none;
   } 

   input[type="reset"]
   {
      background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
      background-position: center center;
      background-repeat: no-repeat;
      height: 38px;
      width: 38px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -9px;
      left: -44px;
   }
</style>

See it in action here: http://jsbin.com/uloli3/63

jQuery creating objects

I actually found a better way using the jQuery approach

var box = {

config:{
 color: 'red'
},

init:function(config){
 $.extend(this.config,config);
}

};

var myBox = box.init({
 color: blue
});

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

How to delete/remove nodes on Firebase

Firebase.remove() like probably most Firebase methods is asynchronous, thus you have to listen to events to know when something happened:

parent = ref.parent()
parent.on('child_removed', function (snapshot) {
    // removed!
})
ref.remove()

According to Firebase docs it should work even if you lose network connection. If you want to know when the change has been actually synchronized with Firebase servers, you can pass a callback function to Firebase.remove method:

ref.remove(function (error) {
    if (!error) {
        // removed!
    }
}

Function or sub to add new row and data to table

This should help you.

Dim Ws As Worksheet
Set Ws = Sheets("Sheet-Name")
Dim tbl As ListObject
Set tbl = Ws.ListObjects("Table-Name")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add

With newrow

        .Range(1, Ws.Range("Table-Name[Table-Column-Name]").Column) = "Your Data"

End With

Validating parameters to a Bash script

The sh solution by Brian Campbell, while noble and well executed, has a few problems, so I thought I'd provide my own bash solution.

The problems with the sh one:

  • The tilde in ~/foo doesn't expand to your homedirectory inside heredocs. And neither when it's read by the read statement or quoted in the rm statement. Which means you'll get No such file or directory errors.
  • Forking off grep and such for basic operations is daft. Especially when you're using a crappy shell to avoid the "heavy" weight of bash.
  • I also noticed a few quoting issues, for instance around a parameter expansion in his echo.
  • While rare, the solution cannot cope with filenames that contain newlines. (Almost no solution in sh can cope with them - which is why I almost always prefer bash, it's far more bulletproof & harder to exploit when used well).

While, yes, using /bin/sh for your hashbang means you must avoid bashisms at all costs, you can use all the bashisms you like, even on Ubuntu or whatnot when you're honest and put #!/bin/bash at the top.

So, here's a bash solution that's smaller, cleaner, more transparent, probably "faster", and more bulletproof.

[[ -d $1 && $1 != *[^0-9]* ]] || { echo "Invalid input." >&2; exit 1; }
rm -rf ~/foo/"$1"/bar ...
  1. Notice the quotes around $1 in the rm statement!
  2. The -d check will also fail if $1 is empty, so that's two checks in one.
  3. I avoided regular expressions for a reason. If you must use =~ in bash, you should be putting the regular expression in a variable. In any case, globs like mine are always preferable and supported in far more bash versions.

xpath find if node exists

Patrick is correct, both in the use of the xsl:if, and in the syntax for checking for the existence of a node. However, as Patrick's response implies, there is no xsl equivalent to if-then-else, so if you are looking for something more like an if-then-else, you're normally better off using xsl:choose and xsl:otherwise. So, Patrick's example syntax will work, but this is an alternative:

<xsl:choose>
 <xsl:when test="/html/body">body node exists</xsl:when>
 <xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>

How can I schedule a daily backup with SQL Server Express?

We have used the combination of:

  1. Cobian Backup for scheduling/maintenance

  2. ExpressMaint for backup

Both of these are free. The process is to script ExpressMaint to take a backup as a Cobian "before Backup" event. I usually let this overwrite the previous backup file. Cobian then takes a zip/7zip out of this and archives these to the backup folder. In Cobian you can specify the number of full copies to keep, make multiple backup cycles etc.

ExpressMaint command syntax example:

expressmaint -S HOST\SQLEXPRESS -D ALL_USER -T DB -R logpath -RU WEEKS -RV 1 -B backuppath -BU HOURS -BV 3 

How to simulate key presses or a click with JavaScript?

For simulating keyboard events in Chrome:

There is a related bug in webkit that keyboard events when initialized with initKeyboardEvent get an incorrect keyCode and charCode of 0: https://bugs.webkit.org/show_bug.cgi?id=16735

A working solution for it is posted in this SO answer.

cd into directory without having permission

Alternatively, you can do:

sudo -s
cd directory

Python Brute Force algorithm

Use itertools.product, combined with itertools.chain to put the various lengths together:

from itertools import chain, product
def bruteforce(charset, maxlength):
    return (''.join(candidate)
        for candidate in chain.from_iterable(product(charset, repeat=i)
        for i in range(1, maxlength + 1)))

Demonstration:

>>> list(bruteforce('abcde', 2))
['a', 'b', 'c', 'd', 'e', 'aa', 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db', 'dc', 'dd', 'de', 'ea', 'eb', 'ec', 'ed', 'ee']

This will efficiently produce progressively larger words with the input sets, up to length maxlength.

Do not attempt to produce an in-memory list of 26 characters up to length 10; instead, iterate over the results produced:

for attempt in bruteforce(string.ascii_lowercase, 10):
    # match it against your password, or whatever
    if matched:
        break

Change UITableView height dynamically

Lots of the answers here don't honor changes of the table or are way too complicated. Using a subclass of UITableView that will properly set intrinsicContentSize is a far easier solution when using autolayout. No height constraints etc. needed.

class UIDynamicTableView: UITableView
{
    override var intrinsicContentSize: CGSize {
        self.layoutIfNeeded()
        return CGSize(width: UIViewNoIntrinsicMetric, height: self.contentSize.height)
    }

    override func reloadData() {
        super.reloadData()
        self.invalidateIntrinsicContentSize()
    }
} 

Set the class of your TableView to UIDynamicTableView in the interface builder and watch the magic as this TableView will change it's size after a call to reloadData().

Changing background color of selected item in recyclerview

in the Kotlin you can do this simply: all you need is to create a static variable like this:

companion object {
     var last_position = 0
}

then in your onBindViewHolder add this code:

holder.item.setOnClickListener{
        holder.item.setBackgroundResource(R.drawable.selected_item)
        notifyItemChanged(last_position)
        last_position=position
    }

which item is the child of recyclerView which you want to change its background after clicking on it.

Adding n hours to a date in Java?

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();

bootstrap 4 file input doesn't show the file name

Johann-S solution works great. (And it looks like he created the awesome plugin)

The Bootstrap 4.3 documentation example page uses this plugin to modify the filename: https://github.com/Johann-S/bs-custom-file-input

Use the Bootstrap custom file input classes. Add the plugin to your project, and add this code in your script file on the page.

$(document).ready(function () {
  bsCustomFileInput.init()
})

'Property does not exist on type 'never'

I had the same error and replaced the dot notation with bracket notation to suppress it.

e.g.: obj.name -> obj['name']

Get file content from URL?

Don't forget: to get HTTPS contents, your OPENSSL extension should be enabled in your php.ini. (how to get contents of site use HTTPS)

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

How do I get an element to scroll into view, using jQuery?

Simple 2 steps for scrolling down to end or bottom.

Step1: get the full height of scrollable(conversation) div.

Step2: apply scrollTop on that scrollable(conversation) div using the value obtained in step1.

var fullHeight = $('#conversation')[0].scrollHeight;

$('#conversation').scrollTop(fullHeight);

Above steps must be applied for every append on the conversation div.

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

Show Youtube video source into HTML5 video tag?

Step 1: add &html5=True to your favorite youtube url

Step 2: Find <video/> tag in source

Step 3: Add controls="controls" to video tag: <video controls="controls"..../>

Example:

_x000D_
_x000D_
<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&amp;itag=43&amp;ipbits=0&amp;signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&amp;sver=3&amp;ratebypass=yes&amp;expire=1300417200&amp;key=yt1&amp;ip=0.0.0.0&amp;id=37da319914f6616c"></video>
_x000D_
_x000D_
_x000D_

Note there seems to some expire stuff. I don't know how long the src string will work.

Still testing myself.

Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.

Counting the Number of keywords in a dictionary in python

Some modifications were made on posted answer UnderWaterKremlin to make it python3 proof. A surprising result below as answer.

System specs:

  • python =3.7.4,
  • conda = 4.8.0
  • 3.6Ghz, 8 core, 16gb.
import timeit

d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000

print (len(d.keys()))
# 1000

print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000))        # 1

print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2

Result:

1) = 37.0100378

2) = 37.002148899999995

So it seems that len(d.keys()) is currently faster than just using len().

Undo git update-index --assume-unchanged <file>

If you are using Git Extensions, then follow below steps:

  1. Go to commit window.
  2. Click on the dropdown named Working directory changes.
  3. Select Show assummed-unchanged files option.
  4. Right click on the file you want to unassumme.
  5. Select Do no assumme unchanged.

You are done.

Exposing the current state name with ui router

this is how I do it

JAVASCRIPT:

var module = angular.module('yourModuleName', ['ui.router']);

module.run( ['$rootScope', '$state', '$stateParams',
                      function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams; 
}
]);

HTML:

<pre id="uiRouterInfo">
      $state = {{$state.current.name}}
      $stateParams = {{$stateParams}}
      $state full url = {{ $state.$current.url.source }}    
</pre>

EXAMPLE

http://plnkr.co/edit/LGMZnj?p=preview

Asynchronously wait for Task<T> to complete with timeout

You can use Task.WaitAny to wait the first of multiple tasks.

You could create two additional tasks (that complete after the specified timeouts) and then use WaitAny to wait for whichever completes first. If the task that completed first is your "work" task, then you're done. If the task that completed first is a timeout task, then you can react to the timeout (e.g. request cancellation).

Random number c++ in some range

Use the rand function:

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Quote:

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014

How to set min-font-size in CSS

CSS has a clamp() function that holds the value between the upper and lower bound. The clamp() function enables the selection of the middle value in the range of values between the defined minimum and maximum values.

It simply takes three dimensions:

  1. Minimum value.
  2. List item
  3. Preferred value Maximum allowed value.

try with the code below, and check the window resize, which will change the font size you see in the console. i set maximum value 150px and minimum value 100px.

_x000D_
_x000D_
$(window).resize(function(){_x000D_
    console.log($('#element').css('font-size'));_x000D_
});_x000D_
console.log($('#element').css('font-size'));
_x000D_
h1{_x000D_
    font-size: 10vw; /* Browsers that do not support "MIN () - MAX ()" and "Clamp ()" functions will take this value.*/_x000D_
    font-size: max(100px, min(10vw, 150px)); /* Browsers that do not support the "clamp ()" function will take this value. */_x000D_
    font-size: clamp(100px, 10vw, 150px);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<center>_x000D_
  <h1 id="element">THIS IS TEXT</h1>_x000D_
</center>
_x000D_
_x000D_
_x000D_

T-SQL split string based on delimiter

May be this will help you.

SELECT SUBSTRING(myColumn, 1, CASE CHARINDEX('/', myColumn)
            WHEN 0
                THEN LEN(myColumn)
            ELSE CHARINDEX('/', myColumn) - 1
            END) AS FirstName
    ,SUBSTRING(myColumn, CASE CHARINDEX('/', myColumn)
            WHEN 0
                THEN LEN(myColumn) + 1
            ELSE CHARINDEX('/', myColumn) + 1
            END, 1000) AS LastName
FROM MyTable

How to run Gulp tasks sequentially one after the other

The only good solution to this problem can be found in the gulp documentation:

var gulp = require('gulp');

// takes in a callback so the engine knows when it'll be done
gulp.task('one', function(cb) {
  // do stuff -- async or otherwise
  cb(err); // if err is not null and not undefined, the orchestration will stop, and 'two' will not run
});

// identifies a dependent task must be complete before this one begins
gulp.task('two', ['one'], function() {
  // task 'one' is done now
});

gulp.task('default', ['one', 'two']);
// alternatively: gulp.task('default', ['two']);

Rounded Corners Image in Flutter

you can use ClipRRect like this :

  Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(25),
                    child: Image.asset(
                      'assets/images/pic13.jpeg',
                      fit: BoxFit.cover,
                    ),
                  ),
                )

you can set your radius, or user for only for topLeft or bottom left like :

Padding(
              padding: const EdgeInsets.all(8.0),
              child: ClipRRect(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(25)
                ,bottomLeft: Radius.circular(25)),
                child: Image.asset(
                  'assets/images/pic13.jpeg',
                  fit: BoxFit.cover,
                ),
              ),
            )

How to sleep for five seconds in a batch file/cmd

I'm very surprised no one has mentioned:

C:\> timeout 5

N.B. Please note however (thanks Dan!) that timeout 5 means:

Sleep anywhere between 4 and 5 seconds

This can be verified empirically by putting the following into a batch file, running it repeatedly and calculating the time differences between the first and second echos:

@echo off
echo %time%
timeout 5 > NUL
echo %time%

How to disable copy/paste from/to EditText

@Zain Ali, your answer works on API 11. I just wanted to suggest a way to do in on API 10 as well. Since I had to maintain my project API on that version, I was constantly playing with the functions available in 2.3.3 and got a possibility to do it. I have share the snippet below. I tested the code and it was working for me. I did this snippet on an urgency. Feel free to improve the code if there are any changes that can be done..

// A custom TouchListener is being implemented which will clear out the focus 
// and gain the focus for the EditText, in few milliseconds so the selection 
// will be cleared and hence the copy paste option wil not pop up.
// the respective EditText should be set with this listener 
// tmpEditText.setOnTouchListener(new MyTouchListener(tmpEditText, tmpImm));

public class MyTouchListener implements View.OnTouchListener {

    long click = 0;
    EditText mEtView;
    InputMethodManager imm;

    public MyTouchListener(EditText etView, InputMethodManager im) {
        mEtView = etView;
        imm = im;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            long curr = System.currentTimeMillis();
            if (click !=0 && ( curr - click) < 30) {

                mEtView.setSelected(false);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mEtView.setSelected(true);
                        mEtView.requestFocusFromTouch();
                        imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                    }
                },25);

            return true;
            }
            else {
                if (click == 0)
                    click = curr;
                else
                    click = 0;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mEtView.requestFocusFromTouch();
                        mEtView.requestFocusFromTouch();
                        imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                    }
                },25);
            return true;
            }

        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            mEtView.setSelected(false);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mEtView.setSelected(true);
                    mEtView.requestFocusFromTouch();
                    mEtView.requestFocusFromTouch();
                    imm.showSoftInput(mEtView, InputMethodManager.RESULT_SHOWN);
                }
            },25);
            return true;
        }
        return false;
    }

Django optional url parameters

Django = 2.2

urlpatterns = [
    re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]

'nuget' is not recognized but other nuget commands working

In [Package Manager Console] try the below

Install-Package NuGet.CommandLine

TypeError: 'builtin_function_or_method' object is not subscriptable

Can't believe this thread was going on for so long. You would get this error if you got distracted and used [] instead of (), at least my case.

Pop is a method on the list data type, https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Therefore, you shouldn't be using pop as if it was a list itself, pop[0]. It's a method that takes an optional parameter representing an index, so as Tushar Palawat pointed out in one of the answers that didn't get approved, the correct adjustment which will fix the example above is:

listb.pop(0)

If you don't believe, run a sample such as:

if __name__ == '__main__':
  listb = ["-test"]
  if( listb[0] == "-test"):
    print(listb.pop(0))

Other adjustments would work as well, but it feels as they are abusing the Python language. This thread needs to get fixed, not to confuse users.

Addition, a.pop() removes and returns the last item in the list. As a result, a.pop()[0] will get the first character of that last element. It doesn't seem that is what the given code snippet is aiming to achieve.

Git update submodules recursively

git submodule update --recursive

You will also probably want to use the --init option which will make it initialize any uninitialized submodules:

git submodule update --init --recursive

Note: in some older versions of Git, if you use the --init option, already-initialized submodules may not be updated. In that case, you should also run the command without --init option.

Discard all and get clean copy of latest revision?

hg up -C

This will remove all the changes and update to the latest head in the current branch.

And you can turn on purge extension to be able to remove all unversioned files too.

Inline functions in C#?

Do you mean inline functions in the C++ sense? In which the contents of a normal function are automatically copied inline into the callsite? The end effect being that no function call actually happens when calling a function.

Example:

inline int Add(int left, int right) { return left + right; }

If so then no, there is no C# equivalent to this.

Or Do you mean functions that are declared within another function? If so then yes, C# supports this via anonymous methods or lambda expressions.

Example:

static void Example() {
  Func<int,int,int> add = (x,y) => x + y;
  var result = add(4,6);  // 10
}

Get push notification while App in foreground iOS

In your app delegate use bellow code

import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
 var currentToken: String?
 var window: UIWindow?
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        application.registerForRemoteNotifications()
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in

            // Enable or disable features based on authorization.
            if granted == true
            {
                print("Allow")
                UIApplication.shared.registerForRemoteNotifications()
            }
            else
            {
                print("Don't Allow")
            }
        }
        UNUserNotificationCenter.current().delegate = self

        return true
    }
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenParts.joined()
        currentToken = token  //get device token to delegate variable

    }
 public class var shared: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
         completionHandler([.alert, .badge, .sound])
    }
}

internet explorer 10 - how to apply grayscale filter?

IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.

However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

svg {
    background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}

(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)

Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/

More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

How to zoom in/out an UIImage object when user pinches screen?

Another easy way to do this is to place your UIImageView within a UIScrollView. As I describe here, you need to set the scroll view's contentSize to be the same as your UIImageView's size. Set your controller instance to be the delegate of the scroll view and implement the viewForZoomingInScrollView: and scrollViewDidEndZooming:withView:atScale: methods to allow for pinch-zooming and image panning. This is effectively what Ben's solution does, only in a slightly more lightweight manner, as you don't have the overhead of a full web view.

One issue you may run into is that the scaling within the scroll view comes in the form of transforms applied to the image. This may lead to blurriness at high zoom factors. For something that can be redrawn, you can follow my suggestions here to provide a crisper display after the pinch gesture is finished. hniels' solution could be used at that point to rescale your image.

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

Find the number of columns in a table

SELECT COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE 
   TABLE_NAME = 'table_name';

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

I know this is old, but I had a similar problem and found a fix:

I had the same issue with a module I ported from Excel into Access, in an unrelated UDF I was dimming 'As Range' but ranges don't exist in Access. You may be using a variable type without having the proper reference library turned on.

If you have any non-standard dims google them and see if you're missing the reference to that library under tools.

-E

applying css to specific li class

I believe it's because #ID styles trump .class styles when computing the final style of an element. Try changing your li from class to id, or you can try adding !important to your class, like this:

li.sub-navigation-home-news
{
    color: #C1C1C1; !important

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

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

Path to Powershell.exe (v 2.0)

I think $PsHome has the information you're after?

PS .> $PsHome
C:\Windows\System32\WindowsPowerShell\v1.0

PS .> Get-Help about_automatic_variables

TOPIC
    about_Automatic_Variables ...

How to delete a file from SD card?

File file = new File(selectedFilePath);
boolean deleted = file.delete();

where selectedFilePath is the path of the file you want to delete - for example:

/sdcard/YourCustomDirectory/ExampleFile.mp3

Javascript swap array elements

what about Destructuring_assignment

var arr = [1, 2, 3, 4]
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]

which can also be extended to

[src order elements] => [dest order elements]

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

Online Internet Explorer Simulators

You could try Firebug Lite

It's a pure JavaScript-implementation of Firebug that runs directly in any browser (at least in all major ones: IE6+, Firefox, Opera, Safari and Chrome)

You'll still need the VM to actually run IE, but at least you'll get a quicker testing cycle.

How do I check for null values in JavaScript?

Firstly, you have a return statement without a function body. Chances are that that will throw an error.

A cleaner way to do your check would be to simply use the ! operator:

if (!pass || !cpass || !email || !cemail || !user) {

    alert("fill all columns");

}

What does the construct x = x || y mean?

To add some explanation to all said before me, I should give you some examples to understand logical concepts.

var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true

It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.

And operator have the opposite structure like below.

var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh

ComboBox.SelectedText doesn't give me the SelectedText

From the documentation:

You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction. For example, if you retrieve the SelectedText value in a button Click event handler, the value will be an empty string. This is because the selection is automatically cleared when the input focus moves from the combo box to the button.

When the combo box loses focus, the selection point moves to the beginning of the text and any selected text becomes unselected. In this case, getting the SelectedText property retrieves an empty string, and setting the SelectedText property adds the specified value to the beginning of the text.

Git merge two local branches

If I understood your question, you want to merge branchB into branchA. To do so, first checkout branchA like below,

git checkout branchA

Then execute the below command to merge branchB into branchA:

git merge branchB

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

My VirtualHost's ServerName was commented out by default. It worked after uncommenting.

Angularjs $q.all

In javascript there are no block-level scopes only function-level scopes:

Read this article about javaScript Scoping and Hoisting.

See how I debugged your code:

var deferred = $q.defer();
deferred.count = i;

console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects

// some code

.success(function(data){
   console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
   deferred.resolve(data);
})
  • When you write var deferred= $q.defer(); inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop.
  • With each loop, the last deferred is overriding the previous one, there is no block-level scope to save a reference to that object.
  • When asynchronous callbacks (success / error) are invoked, they reference only the last deferred object and only it gets resolved, so $q.all is never resolved because it still waits for other deferred objects.
  • What you need is to create an anonymous function for each item you iterate.
  • Since functions do have scopes, the reference to the deferred objects are preserved in a closure scope even after functions are executed.
  • As #dfsq commented: There is no need to manually construct a new deferred object since $http itself returns a promise.

Solution with angular.forEach:

Here is a demo plunker: http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview

UploadService.uploadQuestion = function(questions){

    var promises = [];

    angular.forEach(questions , function(question) {

        var promise = $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

        promises.push(promise);

    });

    return $q.all(promises);
}

My favorite way is to use Array#map:

Here is a demo plunker: http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview

UploadService.uploadQuestion = function(questions){

    var promises = questions.map(function(question) {

        return $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

    });

    return $q.all(promises);
}

Sending event when AngularJS finished loading

Angular hasn't provided a way to signal when a page finished loading, maybe because "finished" depends on your application. For example, if you have hierarchical tree of partials, one loading the others. "Finish" would mean that all of them have been loaded. Any framework would have a hard time analyzing your code and understanding that everything is done, or still waited upon. For that, you would have to provide application-specific logic to check and determine that.

Difference Between ViewResult() and ActionResult()

In the Controller , one could use the below syntax

public ViewResult EditEmployee() {
    return View();
}

public ActionResult EditEmployee() {
    return View();
}

In the above example , only the return type varies . one returns ViewResult whereas the other one returns ActionResult.

ActionResult is an abstract class . It can accept:

ViewResult , PartialViewResult, EmptyResult , RedirectResult , RedirectToRouteResult , JsonResult , JavaScriptResult , ContentResult, FileContentResult , FileStreamResult , FilePathResult etc.

The ViewResult is a subclass of ActionResult.

Adding a line break in MySQL INSERT INTO text

In SQL or MySQL you can use the char or chr functions to enter in an ASCII 13 for carriage return line feed, the \n equivilent. But as @David M has stated, you are most likely looking to have the HTML show this break and a br is what will work.

What is the Maximum Size that an Array can hold?

Here is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html

You may want to mention which version of .NET you are using and your memory size.

You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.

How to Get JSON Array Within JSON Object?

Solved, use array list of string to get name from Ingredients. Use below code:

JSONObject jsonObj = new JSONObject(jsonStr);

//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = ja_data.length();

//loop to get all json objects from data json array
for(int i=0; i<length; i++){
    JSONObject jObj = ja_data.getJSONObject(i);
    Toast.makeText(this, jObj.getString("Name"), Toast.LENGTH_LONG).show();
    // getting inner array Ingredients
    JSONArray ja = jObj.getJSONArray("Ingredients");
    int len = ja.length();
    ArrayList<String> Ingredients_names = new ArrayList<>();
    for(int j=0; j<len; j++){
        JSONObject json = ja.getJSONObject(j);
        Ingredients_names.add(json.getString("name"));
    }
}

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

CSS-Only Scrollable Table with fixed headers

This answer will be used as a placeholder for the not fully supported position: sticky and will be updated over time. It is currently advised to not use the native implementation of this in a production environment.

See this for the current support: https://caniuse.com/#feat=css-sticky


Use of position: sticky

An alternative answer would be using position: sticky. As described by W3C:

A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.

This described exactly the behavior of a relative static header. It would be easy to assign this to the <thead> or the first <tr> HTML-tag, as this should be supported according to W3C. However, both Chrome, IE and Edge have problems assigning a sticky position property to these tags. There also seems to be no priority in solving this at the moment.

What does seem to work for a table element is assigning the sticky property to a table-cell. In this case the <th> cells.

Because a table is not a block-element that respects the static size you assign to it, it is best to use a wrapper element to define the scroll-overflow.

The code

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  height: 150px;_x000D_
  overflow: auto_x000D_
}_x000D_
_x000D_
table th {_x000D_
  position: -webkit-sticky;_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
_x000D_
/* == Just general styling, not relevant :) == */_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th {_x000D_
  background-color: #1976D2;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
  padding: 1em .5em;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
  color: #212121;_x000D_
}_x000D_
_x000D_
table tr:nth-child(odd) {_x000D_
  background-color: #BBDEFB;_x000D_
}
_x000D_
<div>_x000D_
  <table border="0">_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>head1</th>_x000D_
        <th>head2</th>_x000D_
        <th>head3</th>_x000D_
        <th>head4</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tr>_x000D_
      <td>row 1, cell 1</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>row 2, cell 1</td>_x000D_
      <td>row 2, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
      <td>row 1, cell 2</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In this example I use a simple <div> wrapper to define the scroll-overflow done with a static height of 150px. This can of course be any size. Now that the scrolling box has been defined, the sticky <th> elements will corespondent "to the nearest ancestor with a scrolling box", which is the div-wrapper.


Use of a position: sticky polyfill

Non-supported devices can make use of a polyfill, which implements the behavior through code. An example is stickybits, which resembles the same behavior as the browser's implemented position: sticky.

Example with polyfill: http://jsfiddle.net/7UZA4/6957/

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

equivalent of rm and mv in windows .cmd

move and del ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move command. And the same thing applies with del.

The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.

mv and rm are in the CoreUtils package and they work wonderfully!

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I just had to delete and reinstall my google-services.json and then restart Android Studio.

How to call on a function found on another file?

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out

How should I pass an int into stringWithFormat?

Do this:

label.text = [NSString stringWithFormat:@"%d", count];

"Could not find a valid gem in any repository" (rubygame and others)

For what it is worth I came to this page because I had the same problem. I never got anywhere except some IMAP stuff that I don't understand. Then I remembered I had uninstalled privoxy on my ubuntu (because of some weird runtime error that mentioned 127.0.0.1:8118 when I used Daniel Kehoe's Rails template, https://github.com/RailsApps/rails3-application-templates [never discovered what it was]) and I hadn't changed my terminal to the state of no system wide proxy, under network proxy.

I know this may not be on-point but if I wound up here maybe other privoxy users can benefit too.

/bin/sh: pushd: not found

Note that each line executed by a make file is run in its own shell anyway. If you change directory, it won't affect subsequent lines. So you probably have little use for pushd and popd, your problem is more the opposite, that of getting the directory to stay changed for as long as you need it!

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_

Convert a string to a datetime

You should have to use Date.ParseExact or Date.TryParseExact with correct format string.

 Dim edate = "10/12/2009"
 Dim expenddt As Date = Date.ParseExact(edate, "dd/MM/yyyy", 
            System.Globalization.DateTimeFormatInfo.InvariantInfo)

OR

 Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
 Dim expenddt As Date = Date.ParseExact(edate, format,  
     System.Globalization.DateTimeFormatInfo.InvariantInfo, 
     Globalization.DateTimeStyles.None)

OR

Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
Dim expenddt As Date
Date.TryParseExact(edate, format, 
    System.Globalization.DateTimeFormatInfo.InvariantInfo, 
    Globalization.DateTimeStyles.None, expenddt)

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

I had the same its because of version incompatibility check for version or remove version if using spring boot

How to destroy JWT Tokens on logout?

On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.

But, What if you want to destroy the token on the Node server -

The problem with JWT package is that it doesn't provide any method or way to destroy the token.

So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

it works in this way :

1) Install jwt-redis from npm

2) To Create -

var redis = require('redis');
var JWTR =  require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);

jwtr.sign(payload, secret)
    .then((token)=>{
            // your code
    })
    .catch((error)=>{
            // error handling
    });

3) To verify -

jwtr.verify(token, secret);

4) To Destroy -

jwtr.destroy(token)

Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

How to set the opacity/alpha of a UIImage?

If you're experimenting with Metal rendering & you're extracting the CGImage generated by imageByApplyingAlpha in the first reply, you may end up with a Metal rendering that's larger than you expect. While experimenting with Metal, you may want to change one line of code in imageByApplyingAlpha:

    UIGraphicsBeginImageContextWithOptions (self.size, NO, 1.0f);
//  UIGraphicsBeginImageContextWithOptions (self.size, NO, 0.0f);

If you're using a device with a scale factor of 3.0, like the iPhone 11 Pro Max, the 0.0 scale factor shown above will give you an CGImage that's three times larger than you're expecting. Changing the scale factor to 1.0 should avoid any scaling.

Hopefully, this reply will save beginners a lot of aggravation.

Executing another application from Java

The Runtime.getRuntime().exec() approach is quite troublesome, as you'll find out shortly.

Take a look at the Apache Commons Exec project. It abstracts you way of a lot of the common problems associated with using the Runtime.getRuntime().exec() and ProcessBuilder API.

It's as simple as:

String line = "myCommand.exe";
CommandLine commandLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
int exitValue = executor.execute(commandLine);

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

My site configuration file is example.conf in sites-available folder So you can create a symbolic link as

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

SQL Server Pivot Table with multiple column aggregates

I would do this slightly different by applying both the UNPIVOT and the PIVOT functions to get the final result. The unpivot takes the values from both the totalcount and totalamount columns and places them into one column with multiple rows. You can then pivot on those results.:

select chardate,
  Australia_totalcount as [Australia # of Transactions], 
  Australia_totalamount as [Australia Total $ Amount],
  Austria_totalcount as [Austria # of Transactions], 
  Austria_totalamount as [Austria Total $ Amount]
from
(
  select 
    numericmonth, 
    chardate,
    country +'_'+col col, 
    value
  from
  (
    select numericmonth, 
      country, 
      chardate,
      cast(totalcount as numeric(10, 2)) totalcount,
      cast(totalamount as numeric(10, 2)) totalamount
    from mytransactions
  ) src
  unpivot
  (
    value
    for col in (totalcount, totalamount)
  ) unpiv
) s
pivot
(
  sum(value)
  for col in (Australia_totalcount, Australia_totalamount,
              Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth

See SQL Fiddle with Demo.

If you have an unknown number of country names, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @colsName AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col) 
                      from mytransactions
                      cross apply 
                      (
                        select 'TotalCount' col
                        union all
                        select 'TotalAmount'
                      ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsName 
    = STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col) 
               +' as ['
               + country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
             from mytransactions
             cross apply 
             (
                select 'TotalCount' col
                union all
                select 'TotalAmount'
             ) c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'SELECT chardate, ' + @colsName + ' 
     from 
     (
      select 
        numericmonth, 
        chardate,
        country +''_''+col col, 
        value
      from
      (
        select numericmonth, 
          country, 
          chardate,
          cast(totalcount as numeric(10, 2)) totalcount,
          cast(totalamount as numeric(10, 2)) totalamount
        from mytransactions
      ) src
      unpivot
      (
        value
        for col in (totalcount, totalamount)
      ) unpiv
     ) s
     pivot 
     (
       sum(value)
       for col in (' + @cols + ')
     ) p 
     order by numericmonth'

execute(@query)

See SQL Fiddle with Demo

Both give the result:

|             CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12               |                          36 |                   699.96 |                        11 |                 257.82 |
| Aug-12               |                          44 |                  1368.71 |                         5 |                 126.55 |
| Sep-12               |                          52 |                  1161.33 |                         7 |                  92.11 |
| Oct-12               |                          50 |                  1099.84 |                        12 |                 103.56 |
| Nov-12               |                          38 |                  1078.94 |                        21 |                 377.68 |
| Dec-12               |                          63 |                  1668.23 |                         3 |                  14.35 |

Difference between window.location.href and top.location.href

top refers to the window object which contains all the current frames ( father of the rest of the windows ). window is the current window.

http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific

so top.location.href can contain the "master" page link containing all the frames, while window.location.href just contains the "current" page link.

Logical operators ("and", "or") in DOS batch

An alternative is to look for a unix shell which does give you logical operators and a whole lot more. You can get a native win32 implementation of a Bourne shell here if you don't want to go the cygwin route. A native bash can be found here. I'm quite certain you could easily google other good alternatives such as zsh or tcsh.

K

How to show a running progress bar while page is loading

I have copied the relevant code below from This page. Hope this might help you.

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data) {
    //Do something success-ish
  }
});

How do I copy a string to the clipboard?

You can use winclip32 module! install:

pip install winclip32

to copy:

import winclip32
winclip32.set_clipboard_data(winclip32.UNICODE_STD_TEXT, "some text")

to get:

import winclip32
print(winclip32.get_clipboard_data(winclip32.UNICODE_STD_TEXT))

for more informations: https://pypi.org/project/winclip32/

Equivalent to AssemblyInfo in dotnet core/csproj

As you've already noticed, you can control most of these settings in .csproj.

If you'd rather keep these in AssemblyInfo.cs, you can turn off auto-generated assembly attributes.

<PropertyGroup>
   <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup> 

If you want to see what's going on under the hood, checkout Microsoft.NET.GenerateAssemblyInfo.targets inside of Microsoft.NET.Sdk.

keypress, ctrl+c (or some combo like that)

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
    var ctrlMode = false; // if true the ctrl key is down
    ///this works
    $(document).keydown(function(e){
    if(e.ctrlKey){
        ctrlMode = true;
    };
    });
    $(document).keyup(function(e){
    ctrlMode = false;
    });
</script>

c# search string in txt file

You have to use while since foreach does not know about index. Below is an example code.

int counter = 0;
string line;

Console.Write("Input your search text: ");
var text = Console.ReadLine();

System.IO.StreamReader file =
    new System.IO.StreamReader("SampleInput1.txt");

while ((line = file.ReadLine()) != null)
{
    if (line.Contains(text))
    {
        break;
    }

    counter++;
}

Console.WriteLine("Line number: {0}", counter);

file.Close();

Console.ReadLine();

Is it possible to apply CSS to half of a character?

How about something like this for shorter text?

It could even work for longer text if you did something with a loop, repeating the characters with JavaScript. Anyway, the result is something like this:

Is it possible to apply CSS to half of a character?

_x000D_
_x000D_
p.char {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  font-size: 60px;_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
p.char:before {_x000D_
  position: absolute;_x000D_
  content: attr(char);_x000D_
  width: 50%;_x000D_
  overflow: hidden;_x000D_
  color: black;_x000D_
}
_x000D_
<p class="char" char="S">S</p>_x000D_
<p class="char" char="t">t</p>_x000D_
<p class="char" char="a">a</p>_x000D_
<p class="char" char="c">c</p>_x000D_
<p class="char" char="k">k</p>_x000D_
<p class="char" char="o">o</p>_x000D_
<p class="char" char="v">v</p>_x000D_
<p class="char" char="e">e</p>_x000D_
<p class="char" char="r">r</p>_x000D_
<p class="char" char="f">f</p>_x000D_
<p class="char" char="l">l</p>_x000D_
<p class="char" char="o">o</p>_x000D_
<p class="char" char="w">w</p>
_x000D_
_x000D_
_x000D_

Detect click outside React component

The Ez way...

const componentRef = useRef();

useEffect(() => {
    document.addEventListener("click", handleClick);
    return () => document.removeEventListener("click", handleClick);
    function handleClick(e: any) {
        if(componentRef && componentRef.current){
            const ref: any = componentRef.current
            if(!ref.contains(e.target)){
                // put your action here
            }
        }
    }
}, []);

then put the ref on your component

<div ref={componentRef as any}> My Component </div>

Showing an image from an array of images - Javascript

This is a simple example and try to combine it with yours using some modifications. I prefer you set all the images in one array in order to make your code easier to read and shorter:

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg",
  "_images/image4.jpg","_images/image5.jpg","_images/image6.jpg"];

var imageIndex = 0; 

function changeImage() {
  myImage.setAttribute("src",imageArray[imageIndex]);
  imageIndex = (imageIndex + 1) % imageArray.length;
}

setInterval(changeImage, 5000);

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Instantly detect client disconnection from server socket

i had same problem , try this :

void client_handler(Socket client) // set 'KeepAlive' true
{
    while (true)
    {
        try
        {
            if (client.Connected)
            {

            }
            else
            { // client disconnected
                break;
            }
        }
        catch (Exception)
        {
            client.Poll(4000, SelectMode.SelectRead);// try to get state
        }
    }
}

How do I divide so I get a decimal value?

Check this out: http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

You just need to wrap your int or long variable in a BigDecimal object, then invoke the divideAndRemainder method on it. The returned array will contain the quotient and the remainder (in that order).

write multiple lines in a file in python

It can be done like this as well:

target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")

Using context in a fragment

getContext() method helps to use the Context of the class in a fragment activity.

Apache shows PHP code instead of executing it

Some times if you have php version conflicts it happens To overcome that please follow the below steps

Step 1 : Yum list installed | grep 'php'

if you have multiple versions of php like php 5.6 and php 7.0 this confilict will happens

Step 2 : yum remove **your php version **

Step 3 : Then restart the apapche /etc/init.d/httpd restart or service apache2 restart

Bound method error

I think you meant print test.sorted_word_list instead of print test.sort_word_list.

In addition list.sort() sorts a list in place and returns None, so you probably want to change sort_word_list() to do the following:

self.sorted_word_list = sorted(self.word_list)

You should also consider either renaming your num_words() function, or changing the attribute that the function assigns to, because currently you overwrite the function with an integer on the first call.

Closing WebSocket correctly (HTML5, Javascript)

By using close method of web socket, where you can write any function according to requirement.

var connection = new WebSocket('ws://127.0.0.1:1337');
    connection.onclose = () => {
            console.log('Web Socket Connection Closed');
        };

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

How do I set <table> border width with CSS?

<table style="border: 5px solid black">

This only adds a border around the table.

If you want same border through CSS then add this rule:

table tr td { border: 5px solid black; }

and one thing for HTML table to avoid spaces

<table cellspacing="0" cellpadding="0">

Send POST request using NSURLSession

If you are using Swift, the Just library does this for you. Example from it's readme file:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}

Comparing two input values in a form validation with AngularJS

I need to do this just in one form in my entire application and i see a directive like a super complicate for my case, so i use the ng-patter like some has point, but have some problems, when the string has special characters like .[\ this broke, so i create a function for scape special characters.

$scope.escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

and in the view

<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required ng-pattern="escapeRegExp(password)"/>  
</form>

Nodemailer with Gmail and NodeJS

See nodemailer's official guide to connecting Gmail:

https://community.nodemailer.com/using-gmail/

-

It works for me after doing this:

  1. Enable less secure apps - https://www.google.com/settings/security/lesssecureapps
  2. Disable Captcha temporarily so you can connect the new device/server - https://accounts.google.com/b/0/displayunlockcaptcha

How do I get the full path to a Perl script that is executing?

All the library-free solutions don't actually work for more than a few ways to write a path (think ../ or /bla/x/../bin/./x/../ etc. My solution looks like below. I have one quirk: I don't have the faintest idea why I have to run the replacements twice. If I don't, I get a spurious "./" or "../". Apart from that, it seems quite robust to me.

  my $callpath = $0;
  my $pwd = `pwd`; chomp($pwd);

  # if called relative -> add pwd in front
  if ($callpath !~ /^\//) { $callpath = $pwd."/".$callpath; }  

  # do the cleanup
  $callpath =~ s!^\./!!;                          # starts with ./ -> drop
  $callpath =~ s!/\./!/!g;                        # /./ -> /
  $callpath =~ s!/\./!/!g;                        # /./ -> /        (twice)

  $callpath =~ s!/[^/]+/\.\./!/!g;                # /xxx/../ -> /
  $callpath =~ s!/[^/]+/\.\./!/!g;                # /xxx/../ -> /   (twice)

  my $calldir = $callpath;
  $calldir =~ s/(.*)\/([^\/]+)/$1/;

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

If you don't want to bother with the keystore file, then just remove the package altogether for all users.

Connect your device with Mac/PC and run adb uninstall <package>

Worked for me.

Ref: https://android.stackexchange.com/questions/92025/how-to-completely-uninstall-an-app-on-android-lollipop

How to prevent text in a table cell from wrapping

I came to this question needing to prevent text wrapping at the hyphen.

This is how I did it:

<td><nobr>Table Text</nobr></td>

Reference:

How to prevent line break at hyphens on all browsers

How can I use delay() with show() and hide() in Jquery

Why don't you try the fadeIn() instead of using a show() with delay(). I think what you are trying to do can be done with this. Here is the jQuery code for fadeIn and FadeOut() which also has inbuilt method for delaying the process.

$(document).ready(function(){
   $('element').click(function(){
      //effects take place in 3000ms
      $('element_to_hide').fadeOut(3000);
      $('element_to_show').fadeIn(3000);
   });
}

IsNull function in DB2 SQL?

hope this might help someone else out there

  SELECT 
.... FROM XXX XX
WHERE
....
AND(
       param1 IS NULL
       OR XX.param1 = param1
       )

Update query PHP MySQL

you must write single quotes then double quotes then dot before name of field and after like that

mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

git recover deleted file where no commit was made after the delete

Use git ls-files to checkout deleted(-d) or modified(-m) files.

git checkout $(git ls-files -d)

see How can I restore only the modified files on a git checkout?

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

Groovy built-in REST/HTTP client?

I don't think http-builder is a Groovy module, but rather an external API on top of apache http-client so you do need to import classes and download a bunch of APIs. You are better using Gradle or @Grab to download the jar and dependencies:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

Note: since the CodeHaus site went down, you can find the JAR at (https://mvnrepository.com/artifact/org.codehaus.groovy.modules.http-builder/http-builder)

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

You can convert between the two like this:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

To read a dictionary from a file, there's a corresponding method:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

If you want to read the file as an NSMutableDictionary, simply use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];

Removing fields from struct or hiding them in JSON Response

Here is how I defined my structure.

type User struct {
    Username string  `json:"username" bson:"username"`
    Email    string  `json:"email" bson:"email"`
    Password *string `json:"password,omitempty" bson:"password"`
    FullName string  `json:"fullname" bson:"fullname"`
}

And inside my function set user.Password = nil for not to be Marshalled.

Multiple actions were found that match the request in Web Api

Have you tried like:

[HttpGet("Summary")]
public HttpResponseMessage Summary(MyVm vm)
{
    return null;
}

[HttpGet("FullDetails")]
public HttpResponseMessage FullDetails()
{
    return null;
}

Convert generic List/Enumerable to DataTable?

Marc Gravell's answer but in VB.NET

Public Shared Function ToDataTable(Of T)(data As IList(Of T)) As DataTable
    Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
    Dim table As New DataTable()
    For i As Integer = 0 To props.Count - 1
            Dim prop As PropertyDescriptor = props(i)
            table.Columns.Add(prop.Name, prop.PropertyType)
    Next
    Dim values As Object() = New Object(props.Count - 1) {}
    For Each item As T In data
            For i As Integer = 0 To values.Length - 1
                    values(i) = props(i).GetValue(item)
            Next
            table.Rows.Add(values)
    Next
    Return table
End Function

What is "origin" in Git?

I was also confused by this, and below is what I have learned.

When you clone a repository, for example from GitHub:

  • origin is the alias for the URL from which you cloned the repository. Note that you can change this alias.

  • There is one master branch in the remote repository (aliased by origin). There is also another master branch created locally.

Further information can be found from this SO question: Git branching: master vs. origin/master vs. remotes/origin/master

javascript - Create Simple Dynamic Array

var arr = [];
for(var i=1; i<=mynumber; i++) {
   arr.push(i.toString());
}

How to make System.out.println() shorter

Some interesting alternatives:

OPTION 1

PrintStream p = System.out;
p.println("hello");

OPTION 2

PrintWriter p = new PrintWriter(System.out, true);
p.println("Hello");

Drop all duplicate rows across multiple columns in Python Pandas

Just want to add to Ben's answer on drop_duplicates:

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Drop duplicates except for the first occurrence.

  • last : Drop duplicates except for the last occurrence.

  • False : Drop all duplicates.

So setting keep to False will give you desired answer.

DataFrame.drop_duplicates(*args, **kwargs) Return DataFrame with duplicate rows removed, optionally only considering certain columns

Parameters: subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns keep : {‘first’, ‘last’, False}, default ‘first’ first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates. take_last : deprecated inplace : boolean, default False Whether to drop duplicates in place or to return a copy cols : kwargs only argument of subset [deprecated] Returns: deduplicated : DataFrame

SQL Server after update trigger

You should be able to access the INSERTED table and retrieve ID or table's primary key. Something similar to this example ...

CREATE TRIGGER [dbo].[after_update] ON [dbo].[MYTABLE]
AFTER UPDATE AS 
BEGIN
    DECLARE @id AS INT
    SELECT @id = [IdColumnName]
    FROM INSERTED

    UPDATE MYTABLE 
    SET mytable.CHANGED_ON = GETDATE(),
    CHANGED_BY=USER_NAME(USER_ID())
    WHERE [IdColumnName] = @id

Here's a link on MSDN on the INSERTED and DELETED tables available when using triggers: http://msdn.microsoft.com/en-au/library/ms191300.aspx

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

npm - how to show the latest version of a package

If you're looking for the current and the latest versions of all your installed packages, you can also use:

npm outdated

Are there any Open Source alternatives to Crystal Reports?

How about i-net Clear Reports (used to be i-net Crystal-Clear).

Though not free, you should also consider this low-cost, non-free, non-open-source reporting solution that can fully compete with Crystal Reports - and is Java-based.

I think it's even more cost efficient than "free ones". A small company may have to think closely about free things, but will then have to invest into manpower to find out how everything works and so on. Large companies will for sure subscribe to premium support services that cost a lot. See this article for reference

i-net Clear Reports has a very low price tag with great support for free and even better premium support via yearly subscriptions.

Disclosure: Yeah, I work for the company who built this, so I'm biased. But I honestly believe in what I just wrote.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Append values to a set in Python

keep.update(yoursequenceofvalues)

e.g, keep.update(xrange(11)) for your specific example. Or, if you have to produce the values in a loop for some other reason,

for ...whatever...:
  onemorevalue = ...whatever...
  keep.add(onemorevalue)

But, of course, doing it in bulk with a single .update call is faster and handier, when otherwise feasible.

Find duplicate records in MongoDB

db.getCollection('orders').aggregate([  
    {$group: { 
            _id: {name: "$name"},
            uniqueIds: {$addToSet: "$_id"},
            count: {$sum: 1}
        } 
    },
    {$match: { 
        count: {"$gt": 1}
        }
    }
])

First Group Query the group according to the fields.

Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

How to use a table type in a SELECT FROM statement?

Thanks for all help at this issue. I'll post here my solution:

Package Header

CREATE OR REPLACE PACKAGE X IS
  TYPE exch_row IS RECORD(
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);
  TYPE exch_tbl IS TABLE OF X.exch_row;

  FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;

Package Body

CREATE OR REPLACE PACKAGE BODY X IS
  FUNCTION GetExchangeRate RETURN X.exch_tbl
    PIPELINED AS
    exch_rt_usd NUMBER := 1.0; --todo
    rw exch_row;
  BEGIN

    FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
                 FROM exch e, currency c
                WHERE c.currency_key = e.currency_key
                  ) LOOP
      PIPE ROW(rw);
    END LOOP;
  END;


  PROCEDURE DoIt IS
  BEGIN
    DECLARE
      CURSOR c0 IS
        SELECT i.DOC,
               i.doc_currency,
               i.net_value,
               i.net_value / rt.exch_rt_usd AS net_value_in_usd,
               i.net_value / rt.exch_rt_eur AS net_value_in_euro,
          FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
         WHERE i.doc_currency = rt.currency_cd;

      TYPE c0_type IS TABLE OF c0%ROWTYPE;

      items c0_type;
    BEGIN
      OPEN c0;

      LOOP
        FETCH c0 BULK COLLECT
          INTO items LIMIT batchsize;

        EXIT WHEN items.COUNT = 0;
        FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
          INSERT INTO detail_items VALUES items (i);

      END LOOP;

      CLOSE c0;

      COMMIT;

    EXCEPTION
      WHEN OTHERS THEN
        RAISE;
    END;
  END;

END X;

Please review.

Set value for particular cell in pandas DataFrame using index

Update: The .set_value method is going to be deprecated. .iat/.at are good replacements, unfortunately pandas provides little documentation


The fastest way to do this is using set_value. This method is ~100 times faster than .ix method. For example:

df.set_value('C', 'x', 10)

jQuery Validate - Enable validation for hidden fields

The validation was working for me on form submission, but it wasn't doing the reactive event driven validation on input to the chosen select lists.

To fix this I added the following to manually trigger the jquery validation event that gets added by the library:

$(".chosen-select").each(function() {
  $(this).chosen().on("change", function() {
    $(this).parents(".form-group").find("select.form-control").trigger("focusout.validate");
  });
});

jquery.validate will now add the .valid class to the underlying select list.

Caveat: This does require a consistent html pattern for your form inputs. In my case, each input filed is wrapped in a div.form-group, and each input has .form-control.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

Difference between Node object and Element object?

Element inherits from Node, in the same way that Dog inherits from Animal.

An Element object "is-a" Node object, in the same way that a Dog object "is-a" Animal object.

Node is for implementing a tree structure, so its methods are for firstChild, lastChild, childNodes, etc. It is more of a class for a generic tree structure.

And then, some Node objects are also Element objects. Element inherits from Node. Element objects actually represents the objects as specified in the HTML file by the tags such as <div id="content"></div>. The Element class define properties and methods such as attributes, id, innerHTML, clientWidth, blur(), and focus().

Some Node objects are text nodes and they are not Element objects. Each Node object has a nodeType property that indicates what type of node it is, for HTML documents:

1: Element node
3: Text node
8: Comment node
9: the top level node, which is document

We can see some examples in the console:

> document instanceof Node
  true

> document instanceof Element
  false

> document.firstChild
  <html>...</html>

> document.firstChild instanceof Node
  true

> document.firstChild instanceof Element
  true

> document.firstChild.firstChild.nextElementSibling
  <body>...</body>

> document.firstChild.firstChild.nextElementSibling === document.body
  true

> document.firstChild.firstChild.nextSibling
  #text

> document.firstChild.firstChild.nextSibling instanceof Node
  true

> document.firstChild.firstChild.nextSibling instanceof Element
  false

> Element.prototype.__proto__ === Node.prototype
  true

The last line above shows that Element inherits from Node. (that line won't work in IE due to __proto__. Will need to use Chrome, Firefox, or Safari).

By the way, the document object is the top of the node tree, and document is a Document object, and Document inherits from Node as well:

> Document.prototype.__proto__ === Node.prototype
  true

Here are some docs for the Node and Element classes:
https://developer.mozilla.org/en-US/docs/DOM/Node
https://developer.mozilla.org/en-US/docs/DOM/Element

Excel VBA: Copying multiple sheets into new workbook

Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):

Sub NewWBandPasteSpecialALLSheets()
   MyBook = ActiveWorkbook.Name ' Get name of this book
   Workbooks.Add ' Open a new workbook
   NewBook = ActiveWorkbook.Name ' Save name of new book

   Workbooks(MyBook).Activate ' Back to original book

   Set WB = ActiveWorkbook

   Dim SH As Worksheet

   For Each SH In WB.Worksheets

       SH.Range("WholePrintArea").Copy

       Workbooks(NewBook).Activate

       With SH.Range("A1")
        .PasteSpecial (xlPasteColumnWidths)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlValues)

       End With

     Next

End Sub

But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:

Sub NewWBandPasteSpecialALLSheets()
   Dim wb As Workbook
   Dim wbNew As Workbook
   Dim sh As Worksheet
   Dim shNew As Worksheet

   Set wb = ThisWorkbook
   Workbooks.Add ' Open a new workbook
   Set wbNew = ActiveWorkbook

   On Error Resume Next

   For Each sh In wb.Worksheets
      sh.Range("WholePrintArea").Copy

      'add new sheet into new workbook with the same name
      With wbNew.Worksheets

          Set shNew = Nothing
          Set shNew = .Item(sh.Name)

          If shNew Is Nothing Then
              .Add After:=.Item(.Count)
              .Item(.Count).Name = sh.Name
              Set shNew = .Item(.Count)
          End If
      End With

      With shNew.Range("A1")
          .PasteSpecial (xlPasteColumnWidths)
          .PasteSpecial (xlFormats)
          .PasteSpecial (xlValues)
      End With
   Next
End Sub

Are multiple `.gitignore`s frowned on?

I can think of at least two situations where you would want to have multiple .gitignore files in different (sub)directories.

  • Different directories have different types of file to ignore. For example the .gitignore in the top directory of your project ignores generated programs, while Documentation/.gitignore ignores generated documentation.

  • Ignore given files only in given (sub)directory (you can use /sub/foo in .gitignore, though).

Please remember that patterns in .gitignore file apply recursively to the (sub)directory the file is in and all its subdirectories, unless pattern contains '/' (so e.g. pattern name applies to any file named name in given directory and all its subdirectories, while /name applies to file with this name only in given directory).

Duplicate line in Visual Studio Code

The duplicate can be achieved by CTRL+C and CTRL+V with cursor in the line without nothing selected.

How do you convert a byte array to a hexadecimal string, and vice versa?

Either:

public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

or:

public static string ByteArrayToString(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-","");
}

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}

Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

Setting dynamic scope variables in AngularJs - scope.<some_string>

Just to add into alread given answers, the following worked for me:

HTML:

<div id="div{{$index+1}}" data-ng-show="val{{$index}}">

Where $index is the loop index.

Javascript (where value is the passed parameter to the function and it will be the value of $index, current loop index):

var variable = "val"+value;
if ($scope[variable] === undefined)
{
    $scope[variable] = true;
}else {
    $scope[variable] = !$scope[variable];
}

<script> tag vs <script type = 'text/javascript'> tag

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

In HTML 4.01 and XHTML 1(.1), the type attribute for <script> elements is required.

switch case statement error: case expressions must be constant expression

I would like to mention that, I came across the same situation when I tried adding a library into my project. All of a sudden all switch statements started to show errors!

Now I tried to remove the library which I added, even then it did not work. how ever "when I cleaned the project" all the errors just went off !

Request is not available in this context

This worked for me - if you have to log in Application_Start, do it before you modify the context. You will get a log entry, just with no source, like:

2019-03-12 09:35:43,659 INFO (null) - Application Started

I generally log both the Application_Start and Session_Start, so I see more detail in the next message

2019-03-12 09:35:45,064 INFO ~/Leads/Leads.aspx - Session Started (Local)

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Application Started");
            GlobalContext.Properties["page"] = new GetCurrentPage();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Globals._Environment = WebAppConfig.getEnvironment(Request.Url.AbsoluteUri, Properties.Settings.Default.LocalOverride);
            log.Info(string.Format("Session Started ({0})", Globals._Environment));
        }


Can multiple different HTML elements have the same ID if they're different elements?

We can use class name instead of using id. html id are should be unique but classes are not. when retrieving data using class name can reduce number of code lines in your js files.

_x000D_
_x000D_
$(document).ready(function ()_x000D_
{_x000D_
    $(".class_name").click(function ()_x000D_
    {_x000D_
        //code_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

Which Ruby version am I really running?

Run this command:

rvm get stable --auto-dotfiles

and make sure to read all the output. RVM will tell you if something is wrong, which in your case might be because GEM_HOME is set to something different then PATH.

Calculate distance between two points in google maps V3

It's Quite easy using Google Distance Matrix service

First step is to activate Distance Matrix service from google API console. it returns distances between a set of locations. And apply this simple function

function initMap() {
        var bounds = new google.maps.LatLngBounds;
        var markersArray = [];

        var origin1 = {lat:23.0203, lng: 72.5562};
        //var origin2 = 'Ahmedabad, India';
        var destinationA = {lat:23.0436503, lng: 72.55008939999993};
        //var destinationB = {lat: 23.2156, lng: 72.6369};

        var destinationIcon = 'https://chart.googleapis.com/chart?' +
            'chst=d_map_pin_letter&chld=D|FF0000|000000';
        var originIcon = 'https://chart.googleapis.com/chart?' +
            'chst=d_map_pin_letter&chld=O|FFFF00|000000';
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 55.53, lng: 9.4},
          zoom: 10
        });
        var geocoder = new google.maps.Geocoder;

        var service = new google.maps.DistanceMatrixService;
        service.getDistanceMatrix({
          origins: [origin1],
          destinations: [destinationA],
          travelMode: 'DRIVING',
          unitSystem: google.maps.UnitSystem.METRIC,
          avoidHighways: false,
          avoidTolls: false
        }, function(response, status) {
          if (status !== 'OK') {
            alert('Error was: ' + status);
          } else {
            var originList = response.originAddresses;
            var destinationList = response.destinationAddresses;
            var outputDiv = document.getElementById('output');
            outputDiv.innerHTML = '';
            deleteMarkers(markersArray);

            var showGeocodedAddressOnMap = function(asDestination) {
              var icon = asDestination ? destinationIcon : originIcon;
              return function(results, status) {
                if (status === 'OK') {
                  map.fitBounds(bounds.extend(results[0].geometry.location));
                  markersArray.push(new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    icon: icon
                  }));
                } else {
                  alert('Geocode was not successful due to: ' + status);
                }
              };
            };

            for (var i = 0; i < originList.length; i++) {
              var results = response.rows[i].elements;
              geocoder.geocode({'address': originList[i]},
                  showGeocodedAddressOnMap(false));
              for (var j = 0; j < results.length; j++) {
                geocoder.geocode({'address': destinationList[j]},
                    showGeocodedAddressOnMap(true));
                //outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] + ': ' + results[j].distance.text + ' in ' +                    results[j].duration.text + '<br>';
                outputDiv.innerHTML += results[j].distance.text + '<br>';
              }
            }

          }
        });
      }

Where origin1 is your location and destinationA is destindation location.you can add above two or more data.

Rad Full Documentation with an example

How can I stop the browser back button using JavaScript?

Just set location.hash="Something". On pressing the back button, the hash will get removed from the URL, but the page won't go back.

This method is good for preventing going back accidentally, but for security purposes you should design your backend for preventing reanswering.

How to set time to midnight for current day?

Using some of the above recommendations, the following function and code is working for search a date range:

Set date with the time component set to 00:00:00

public static DateTime GetDateZeroTime(DateTime date)
{
    return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0);
}

Usage

var modifieddatebegin = Tools.Utilities.GetDateZeroTime(form.modifieddatebegin);

var modifieddateend = Tools.Utilities.GetDateZeroTime(form.modifieddateend.AddDays(1));

iOS8 Beta Ad-Hoc App Download (itms-services)

If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me

Login to website, via C#

You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.

There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").


POSTing to the login form

Form posts are easy to simulate, it's just a case of formatting your post data as follows:

field1=value1&field2=value2

Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:

string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
    os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];

Here's an example of what you should see in the Set-cookie header for your login form:

PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-

GETting the page behind the login form

Now you can perform your GET request to a page that you need to be logged in for.

string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

EDIT:

If you need to view the results of the first POST, you can recover the HTML it returned with:

using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    pageSource = sr.ReadToEnd();
}

Place this directly below cookieHeader = resp.Headers["Set-cookie"]; and then inspect the string held in pageSource.

Server did not recognize the value of HTTP Header SOAPAction

I had similar issue. To debug the problem, I've run Wireshark and capture request generated by my code. Then I used XML Spy trial to create a SOAP request (assuming you have WSDL) and compared those two.

This should give you a hint what goes wrong.

Default username password for Tomcat Application Manager

The admin and manager apps are two separate things. Here's a snapshot of a tomcat-users.xml file that works, try this:

<?xml version='1.0' encoding='utf-8'?>  
<tomcat-users>  
    <role rolename="tomcat"/>  
    <role rolename="role1"/>  
    <role rolename="manager"/>  
    <user username="tomcat" password="tomcat" roles="tomcat"/>  
    <user username="both" password="tomcat" roles="tomcat,role1"/>  
    <user username="role1" password="tomcat" roles="role1"/>  
    <user username="USERNAME" password="PASSWORD" roles="manager,tomcat,role1"/>  
</tomcat-users>  

It works for me very well

How to close form

Why not use the DialogResult method to close the form?

if(DialogSettingsCancel.ShowDialog() == DialogResult.Yes)
{
     //this will close the form but will keep application open if your 
     //application type is "console" in the properties of the project
     this.Close();
}

For this to work however you will need to do it inside your "WindowSettings" form while you call the DialogSettingsCancel form. Much the same way you would call the OpenFileDialog, or any other Dialog form.

How to set commands output as a variable in a batch file

If you don't want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:

FOR /F %i IN ('findstr testing') DO set VARIABLE=%i
echo %VARIABLE%

If you want to enclose search string in double quotes:

FOR /F %i IN ('findstr "testing"') DO set VARIABLE=%i

If you want to store this code in a batch file, add an extra % symbol:

FOR /F %%i IN ('findstr "testing"') DO set VARIABLE=%%i

A useful example to count the number of files in a directory & store in a variable: (illustrates piping)

FOR /F %i IN ('dir /b /a-d "%cd%" ^| find /v /c "?"') DO set /a count=%i

Note the use of single quotes instead of double quotes " or grave accent ` in the command brackets. This is cleaner alternative to delims, tokens or usebackq in for loop.

Tested on Win 10 CMD.

C++ Object Instantiation

There is an additional reason, which no one else has mentioned, why you might choose to create your object dynamically. Dynamic, heap based objects allow you to make use of polymorphism.

How to left align a fixed width string?

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

on a side note you can make the width variable with *-s

>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple                    something                     '

Git Clone - Repository not found

On macOS it's possible that the cached credentials in the Keychain that git is retrieving are wrong. It can be an outdated password or that it used the wrong credentials.

To update the credentials stored in OS X Keychain

Follow the instructions at:

https://help.github.com/articles/updating-credentials-from-the-osx-keychain/

If you want to verify this is the problem you can run clone with tracing.

$ GIT_CURL_VERBOSE=1 git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY

Look for the header line "Authorization: Basic BASE64STRING" .
Take the base64 string and decode it to check what username:password was used.

$ echo <the key> | base64 --decode

Verify it's the right username password you expected to use.

How to find sum of several integers input by user using do/while, While statement or For statement

#include<iostream>
int main()
{//initialize variables
    int limit;
    int num;
    int sum=0;
    int counter=0;

    cout<<"Enter limit of numbers you wish to see"<<" ";
    cin>>limit;
    cout<<endl;

while(counter<limit)
{

   cout<<"Enter number "<<endl;
  cin>>num;

  sum=sum+num;
  counter++;
}
cout<<"The sum of numbers is "<<" "<<endl

return 0;
}

Get counts of all tables in a schema

select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;

This is the fastest way to retrieve the row counts but there are a few important caveats:

  1. NUM_ROWS is only 100% accurate if statistics were gathered in 11g and above with ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE (the default), or in earlier versions with ESTIMATE_PERCENT => 100. See this post for an explanation of how the AUTO_SAMPLE_SIZE algorithm works in 11g.
  2. Results were generated as of LAST_ANALYZED, the current results may be different.

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Optional Parameters in Go?

Go does not have optional parameters nor does it support method overloading:

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

How to find Port number of IP address?

Use of the netstat -a command will give you a list of connections to your system/server where you are executing the command.

For example it will display as below, where 35070 is the port number

 TCP    10.144.0.159:**52121**    sd-s-fgh:35070   ESTABLISHED

Get event listeners attached to node using addEventListener

Since there is no native way to do this ,Here is less intrusive solution i found (dont add any 'old' prototype methods):

var ListenerTracker=new function(){
    var is_active=false;
    // listener tracking datas
    var _elements_  =[];
    var _listeners_ =[];
    this.init=function(){
        if(!is_active){//avoid duplicate call
            intercep_events_listeners();
        }
        is_active=true;
    };
    // register individual element an returns its corresponding listeners
    var register_element=function(element){
        if(_elements_.indexOf(element)==-1){
            // NB : split by useCapture to make listener easier to find when removing
            var elt_listeners=[{/*useCapture=false*/},{/*useCapture=true*/}];
            _elements_.push(element);
            _listeners_.push(elt_listeners);
        }
        return _listeners_[_elements_.indexOf(element)];
    };
    var intercep_events_listeners = function(){
        // backup overrided methods
        var _super_={
            "addEventListener"      : HTMLElement.prototype.addEventListener,
            "removeEventListener"   : HTMLElement.prototype.removeEventListener
        };

        Element.prototype["addEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["addEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;

            if(!listeners[useCapture][type])listeners[useCapture][type]=[];
            listeners[useCapture][type].push(listener);
        };
        Element.prototype["removeEventListener"]=function(type, listener, useCapture){
            var listeners=register_element(this);
            // add event before to avoid registering if an error is thrown
            _super_["removeEventListener"].apply(this,arguments);
            // adapt to 'elt_listeners' index
            useCapture=useCapture?1:0;
            if(!listeners[useCapture][type])return;
            var lid = listeners[useCapture][type].indexOf(listener);
            if(lid>-1)listeners[useCapture][type].splice(lid,1);
        };
        Element.prototype["getEventListeners"]=function(type){
            var listeners=register_element(this);
            // convert to listener datas list
            var result=[];
            for(var useCapture=0,list;list=listeners[useCapture];useCapture++){
                if(typeof(type)=="string"){// filtered by type
                    if(list[type]){
                        for(var id in list[type]){
                            result.push({"type":type,"listener":list[type][id],"useCapture":!!useCapture});
                        }
                    }
                }else{// all
                    for(var _type in list){
                        for(var id in list[_type]){
                            result.push({"type":_type,"listener":list[_type][id],"useCapture":!!useCapture});
                        }
                    }
                }
            }
            return result;
        };
    };
}();
ListenerTracker.init();

Setting different color for each series in scatter plot on matplotlib

You can always use the plot() function like so:

import matplotlib.pyplot as plt

import numpy as np

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
    plt.plot(x, y, 'o')
plt.show()

plot as scatter but changes colors

Where does Android app package gets installed on phone

You will find the application folder at:

/data/data/"your package name"

you can access this folder using the DDMS for your Emulator. you can't access this location on a real device unless you have a rooted device.

How to Determine the Screen Height and Width in Flutter

How to access screen size or pixel density or aspect ratio in flutter ?

We can access screen size and other like pixel density, aspect ration etc. with helps of MediaQuery.

syntex : MediaQuery.of(context).size.height

better way to drop nan rows in pandas

To remove rows based on Nan value of particular column:

d= pd.DataFrame([[2,3],[4,None]])   #creating data frame
d
Output:
    0   1
0   2   3.0
1   4   NaN
d = d[np.isfinite(d[1])]  #Select rows where value of 1st column is not nan
d

Output:
    0   1
0   2   3.0

Google Play app description formatting

Title, Short Description and Developer Name

  • HTML formatting is not supported in these fields, but you can include UTF-8 symbols and Emoji: ??

Full Description and What’s New:

  • For the Long Description and What’s New Section, there is a wider variety of HTML codes you can apply to format and structure your text. However, they will look slightly different in Google Play Store app and web.
  • Here is a table with codes that you can use for formatting Description and What’s New fields for your app on Google Play (originally appeared on ASO Stack blog):

enter image description here

Also you can refer this..

https://thetool.io/2020/html-emoji-google-play

How to read a single character at a time from a file in Python?

To make a supplement, if you are reading file that contains a line that is vvvvery huge, which might break your memory, you might consider read them into a buffer then yield the each char

def read_char(inputfile, buffersize=10240):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(buffersize)
            if not buf:
                break
            for char in buf:
                yield char
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_char('./very_large_file.txt'):
        process(char)

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table