Programs & Examples On #Paint.net

Paint.net is freeware raster graphics editor for Microsoft Windows supporting layers and effects extendable by plugins

How can I save a screenshot directly to a file in Windows?

Thanks to TheSoftwareJedi for providing useful information about snapping tool in Windows 7. Shortcut to open Snipping tool : Go to Start, type sni And you will find the name in the list "Snipping Tool"

enter image description here

Regex date format validation on Java

Putting it all together:

  • REGEX doesn't validate values (like "2010-19-19")
  • SimpleDateFormat does not check format ("2010-1-2", "1-0002-003" are accepted)

it's necessary to use both to validate format and value:

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    df.setLenient(false);
    try {
        df.parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}



A ThreadLocal can be used to avoid the creation of a new SimpleDateFormat for each call.
It is needed in a multithread context since the SimpleDateFormat is not thread safe:

private static final ThreadLocal<SimpleDateFormat> format = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        System.out.println("created");
        return df;
    }
};

public static boolean isValid(String text) {
    if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
        return false;
    try {
        format.get().parse(text);
        return true;
    } catch (ParseException ex) {
        return false;
    }
}

(same can be done for a Matcher, that also is not thread safe)

How can I check if character in a string is a letter? (Python)

I found a good way to do this with using a function and basic code. This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.

def check(count):

    lowercase = 0
    uppercase = 0
    other = 0

    low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
    upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'



    for n in count:
        if n in low:
            lowercase += 1
        elif n in upper:
            uppercase += 1
        else:
            other += 1

    print("There are " + str(lowercase) + " lowercase letters.")
    print("There are " + str(uppercase) + " uppercase letters.")
    print("There are " + str(other) + " other elements to this sentence.")

Get file name from URI string in C#

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(hrefLink.Replace("/", "\\"));
}

THis assumes, of course, that you've parsed out the file name.

EDIT #2:

using System.IO;

private String GetFileName(String hrefLink)
{
    return Path.GetFileName(Uri.UnescapeDataString(hrefLink).Replace("/", "\\"));
}

This should handle spaces and the like in the file name.

Python datetime to string without microsecond component

I found this to be the simplest way.

>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>> 

Vue Js - Loop via v-for X times (in a range)

You can use an index in a range and then access the array via its index:

<ul>
  <li v-for="index in 10" :key="index">
    {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
  </li>
</ul>

You can also check the Official Documentation for more information.

Efficient way to Handle ResultSet in Java

i improved the solutions of RHTs/Brad Ms and of Lestos answer.

i extended both solutions in leaving the state there, where it was found. So i save the current ResultSet position and restore it after i created the maps.

The rs is the ResultSet, its a field variable and so in my solutions-snippets not visible.

I replaced the specific Map in Brad Ms solution to the gerneric Map.

    public List<Map<String, Object>> resultAsListMap() throws SQLException
    {
        var md = rs.getMetaData();
        var columns = md.getColumnCount();
        var list = new ArrayList<Map<String, Object>>();

        var currRowIndex = rs.getRow();
        rs.beforeFirst();

        while (rs.next())
        {
            HashMap<String, Object> row = new HashMap<String, Object>(columns);
            for (int i = 1; i <= columns; ++i)
            {
                row.put(md.getColumnName(i), rs.getObject(i));
            }

            list.add(row);
        }

        rs.absolute(currRowIndex);

        return list;
    }

In Lestos solution, i optimized the code. In his code he have to lookup the Maps each iteration of that for-loop. I reduced that to only one array-acces each for-loop iteration. So the program must not seach each iteration step for that string-key.

    public Map<String, List<Object>> resultAsMapList() throws SQLException
    {
        var md = rs.getMetaData();
        var columns = md.getColumnCount();
        var tmp = new ArrayList[columns];
        var map = new HashMap<String, List<Object>>(columns);

        var currRowIndex = rs.getRow();
        rs.beforeFirst();

        for (int i = 1; i <= columns; ++i)
        {
            tmp[i - 1] = new ArrayList<>();
            map.put(md.getColumnName(i), tmp[i - 1]);
        }

        while (rs.next())
        {
            for (int i = 1; i <= columns; ++i)
            {
                tmp[i - 1].add(rs.getObject(i));
            }
        }

        rs.absolute(currRowIndex);

        return map;
    }

ab load testing

Load testing your API by using just ab is not enough. However, I think it's a great tool to give you a basic idea how your site is performant.

If you want to use the ab command in to test multiple API endpoints, with different data, all at the same time in background, you need to use "nohup" command. It runs any command even when you close the terminal.

I wrote a simple script that automates the whole process, feel free to use it: http://blog.ikvasnica.com/entry/load-test-multiple-api-endpoints-concurrently-use-this-simple-shell-script

SQL get the last date time record

If you want one row for each filename, reflecting a specific states and listing the most recent date then this is your friend:

select filename ,
       status   ,
       max_date = max( dates )
from some_table t
group by filename , status
having status = '<your-desired-status-here>'

Easy!

nodeJs callbacks simple example

Here is an example of copying text file with fs.readFile and fs.writeFile:

var fs = require('fs');

var copyFile = function(source, destination, next) {
  // we should read source file first
  fs.readFile(source, function(err, data) {
    if (err) return next(err); // error occurred
    // now we can write data to destination file
    fs.writeFile(destination, data, next);
  });
};

And that's an example of using copyFile function:

copyFile('foo.txt', 'bar.txt', function(err) {
  if (err) {
    // either fs.readFile or fs.writeFile returned an error
    console.log(err.stack || err);
  } else {
    console.log('Success!');
  }
});

Common node.js pattern suggests that the first argument of the callback function is an error. You should use this pattern because all control flow modules rely on it:

next(new Error('I cannot do it!')); // error

next(null, results); // no error occurred, return result

Installing Numpy on 64bit Windows 7 with Python 2.7.3

The (unofficial) binaries (http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy) worked for me.
I've tried Mingw, Cygwin, all failed due to varies reasons. I am on Windows 7 Enterprise, 64bit.

Twitter Bootstrap: Print content of modal window

_x000D_
_x000D_
@media print{_x000D_
 body{_x000D_
  visibility: hidden; /* no print*/_x000D_
 }_x000D_
 .print{_x000D_
  _x000D_
  visibility:visible; /*print*/_x000D_
 }_x000D_
}
_x000D_
<body>_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="noprint"> <!---no print--->_x000D_
  <div class="print">   <!---print--->_x000D_
  <div class="print">   <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

Build unsigned APK file with Android Studio

You can click the dropdown near the run button on toolbar,

  1. Select "Edit Configurations"
  2. Click the "+"
  3. Select "Gradle"
  4. Choose your module as Gradle project
  5. In Tasks: enter assemble

Now press ok,

all you need to do is now select your configuration from the dropdown and press run button. It will take some time. Your unsigned apk is now located in

Project\app\build\outputs\apk

jQuery: Slide left and slide right

If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations

For you, blindLeftToggle and blindRightToggle is the appropriate choice.

http://jsfiddle.net/ARTsinn/65QsU/

How to generate a Dockerfile from an image?

To understand how a docker image was built, use the docker history --no-trunc command.

You can build a docker file from an image, but it will not contain everything you would want to fully understand how the image was generated. Reasonably what you can extract is the MAINTAINER, ENV, EXPOSE, VOLUME, WORKDIR, ENTRYPOINT, CMD, and ONBUILD parts of the dockerfile.

The following script should work for you:

#!/bin/bash
docker history --no-trunc "$1" | \
sed -n -e 's,.*/bin/sh -c #(nop) \(MAINTAINER .*[^ ]\) *0 B,\1,p' | \
head -1
docker inspect --format='{{range $e := .Config.Env}}
ENV {{$e}}
{{end}}{{range $e,$v := .Config.ExposedPorts}}
EXPOSE {{$e}}
{{end}}{{range $e,$v := .Config.Volumes}}
VOLUME {{$e}}
{{end}}{{with .Config.User}}USER {{.}}{{end}}
{{with .Config.WorkingDir}}WORKDIR {{.}}{{end}}
{{with .Config.Entrypoint}}ENTRYPOINT {{json .}}{{end}}
{{with .Config.Cmd}}CMD {{json .}}{{end}}
{{with .Config.OnBuild}}ONBUILD {{json .}}{{end}}' "$1"

I use this as part of a script to rebuild running containers as images: https://github.com/docbill/docker-scripts/blob/master/docker-rebase

The Dockerfile is mainly useful if you want to be able to repackage an image.

The thing to keep in mind, is a docker image can actually just be the tar backup of a real or virtual machine. I have made several docker images this way. Even the build history shows me importing a huge tar file as the first step in creating the image...

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

For me I had to make sure I was using the correct version of cryptography. pip.freeze had and older version and once I used the latest the problem when away.

How to parse a query string into a NameValueCollection in .NET

If you don't want the System.Web dependency, just paste this source code from HttpUtility class.

I just whipped this together from the source code of Mono. It contains the HttpUtility and all it's dependencies (like IHtmlString, Helpers, HttpEncoder, HttpQSCollection).

Then use HttpUtility.ParseQueryString.

https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c

How to use a TRIM function in SQL Server

TRIM all SPACE's TAB's and ENTER's:

DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
          '

DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
      CHAR(13) + CHAR(10) -- ENTER
    + CHAR(9) -- TAB
    + ' ' -- SPACE

;WITH Split(Chr, Pos) AS (
    SELECT
          SUBSTRING(@Str, 1, 1) AS Chr
        , 1 AS Pos
    UNION ALL
    SELECT
          SUBSTRING(@Str, Pos, 1) AS Chr
        , Pos + 1 AS Pos
    FROM Split
    WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
    Pos >= (
        SELECT MIN(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )
    AND Pos <= (
        SELECT MAX(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )

SELECT '"' + @NewStr + '"'

As Function

CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
    DECLARE @NewStr VARCHAR(MAX) = NULL

    IF (@Str IS NOT NULL) BEGIN
        SET @NewStr = ''

        DECLARE @WhiteChars VARCHAR(4) =
              CHAR(13) + CHAR(10) -- ENTER
            + CHAR(9) -- TAB
            + ' ' -- SPACE

        IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN

            ;WITH Split(Chr, Pos) AS (
                SELECT
                      SUBSTRING(@Str, 1, 1) AS Chr
                    , 1 AS Pos
                UNION ALL
                SELECT
                      SUBSTRING(@Str, Pos, 1) AS Chr
                    , Pos + 1 AS Pos
                FROM Split
                WHERE Pos <= LEN(@Str)
            )
            SELECT @NewStr = @NewStr + Chr
            FROM Split
            WHERE
                Pos >= (
                    SELECT MIN(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
                AND Pos <= (
                    SELECT MAX(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
        END
    END

    RETURN @NewStr
END

Example

-- Test
DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
              '

SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim('      ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'

Result

+-------+----------------+
| Test  | Result         |
+-------+----------------+
| EMPTY | ""             |
| EMTPY | ""             |
| NULL  | NULL           |
| Str   | "[   Foo    ]" |
+-------+----------------+

How to grey out a button?

You should create a XML file for the disabled button (drawable/btn_disable.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/grey" />
    <corners android:radius="6dp" />
</shape>

And create a selector for the button (drawable/btn_selector.xml)

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_disable" android:state_enabled="false"/>
    <item android:drawable="@drawable/btn_default" android:state_enabled="true"/>
    <item android:drawable="@drawable/btn_default" android:state_pressed="false" />

</selector>

Add the selector to your button

<style name="srp_button" parent="@android:style/Widget.Button">
    <item name="android:background">@drawable/btn_selector</item>
</style>

How to display all methods of an object?

Math has static method where you can call directly like Math.abs() while Date has static method like Date.now() and also instance method where you need to create new instance first var time = new Date() to call time.getHours().

// The instance method of Date can be found on `Date.prototype` so you can just call:
var keys = Object.getOwnPropertyNames(Date.prototype);

// And for the static method
var keys = Object.getOwnPropertyNames(Date);

// But if the instance already created you need to
// pass its constructor
var time = new Date();
var staticKeys = Object.getOwnPropertyNames(time.constructor);
var instanceKeys = Object.getOwnPropertyNames(time.constructor.prototype);

Of course you will need to filter the obtained keys for the static method to get actual method names, because you can also get length, name that aren't a function on the list.

But how if we want to obtain all available method from class that extend another class?
Of course you will need to scan through the root of prototype like using __proto__. For saving your time you can use script below to get static method and deep method instance.

_x000D_
_x000D_
// var keys = new Set();_x000D_
function getStaticMethods(keys, clas){_x000D_
    var keys2 = Object.getOwnPropertyNames(clas);_x000D_
_x000D_
    for(var i = 0; i < keys2.length; i++){_x000D_
        if(clas[keys2[i]].constructor === Function)_x000D_
            keys.add(keys2[i]);_x000D_
    }_x000D_
}_x000D_
_x000D_
function getPrototypeMethods(keys, clas){_x000D_
    if(clas.prototype === void 0)_x000D_
        return;_x000D_
_x000D_
    var keys2 = Object.getOwnPropertyNames(clas.prototype);_x000D_
    for (var i = keys2.length - 1; i >= 0; i--) {_x000D_
        if(keys2[i] !== 'constructor')_x000D_
            keys.add(keys2[i]);_x000D_
    }_x000D_
_x000D_
    var deep = Object.getPrototypeOf(clas);_x000D_
    if(deep.prototype !== void 0)_x000D_
        getPrototypeMethods(keys, deep);_x000D_
}_x000D_
_x000D_
// ====== Usage example ======_x000D_
// To avoid duplicate on deeper prototype we use `Set`_x000D_
var keys = new Set();_x000D_
getStaticMethods(keys, Date);_x000D_
getPrototypeMethods(keys, Date);_x000D_
_x000D_
console.log(Array.from(keys));
_x000D_
_x000D_
_x000D_

If you want to obtain methods from created instance, don't forget to pass the constructor of it.

How to return JSON with ASP.NET & jQuery

Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.

Of course, it's then up to you to do what you need to do on the client side.

I would be thinking something like this:

[WebMethod]
public static List GetProducts()
{
   var products  = context.GetProducts().ToList();   
   return products;
}

There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data

SSH to Elastic Beanstalk instance

I found it to be a 2-step process. This assumes that you've already set up a keypair to access EC2 instances in the relevant region.

Configure Security Group

  1. In the AWS console, open the EC2 tab.

  2. Select the relevant region and click on Security Group.

  3. You should have an elasticbeanstalk-default security group if you have launched an Elastic Beanstalk instance in that region.

  4. Edit the security group to add a rule for SSH access. The below will lock it down to only allow ingress from a specific IP address.

    SSH | tcp | 22 | 22 | 192.168.1.1/32
    

Configure the environment of your Elastic Beanstalk Application

  1. If you haven't made a key pair yet, make one by clicking Key Pairs below Security Group in the ec2 tab.
  2. In the AWS console, open the Elastic Beanstalk tab.
  3. Select the relevant region.
  4. Select relevant Environment
  5. Select Configurations in left pane.
  6. Select Security.
  7. Under "EC2 key pair:", select the name of your keypair in the Existing Key Pair field.

If after these steps you see that the Health is set Degraded

enter image description here

that's normal and it just means that the EC2 instance is being updated. Just wait on a few seconds it'll be Ok again

enter image description here

Once the instance has relaunched, you need to get the host name from the AWS Console EC2 instances tab, or via the API. You should then be able to ssh onto the server.

$ ssh -i path/to/keypair.pub [email protected]

Note: For adding a keypair to the environment configuration, the instances' termination protection must be off as Beanstalk would try to terminate the current instances and start new instances with the KeyPair.

Note: If something is not working, check the "Events" tab in the Beanstalk application / environments and find out what went wrong.

Unicode via CSS :before

The code points used in icon font tricks are usually Private Use code points, which means that they have no generally defined meaning and should not be used in open information interchange, only by private agreement between interested parties. However, Private Use code points can be represented as any other Unicode value, e.g. in CSS using a notation like \f066, as others have answered. You can even enter the code point as such, if your document is UTF-8 encoded and you know how to type an arbitrary Unicode value by its number in your authoring environment (but of course it would normally be displayed using a symbol for an unknown character).

However, this is not the normal way of using icon fonts. Normally you use a CSS file provided with the font and use constructs like <span class="icon-resize-small">foo</span>. The CSS code will then take care of inserting the symbol at the start of the element, and you don’t need to know the code point number.

Microsoft Excel ActiveX Controls Disabled?

The best source of information and updates on this issue I could find is in the TechNet Blogs » The Microsoft Excel Support Team Blog (as mentioned):

Form Controls stop working after December 2014 Updates (Updated March 10, 2015)

On March 2015 a hotfix was released in addition to the automated fix-it and manual instructions, and it's available on Windows Update as well.

The latest update and fix from Microsoft: 3025036 "Cannot insert object" error in an ActiveX custom Office solution after you install the MS14-082 security update

STATUS: Update March 10, 2015:

Hotfixes for this issue have been released in the March 2015 Updates for Office 2007, 2010 & 2013.

General info about the problem:

For some users, Form Controls (FM20.dll) are no longer working as expected after installing MS14-082 Microsoft Office Security Updates for December 2014. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.

https://technet.microsoft.com/en-us/library/security/ms14-082.aspx

You may receive errors such as: "Cannot insert object"; "Object library invalid or contains references to object definitions that could not be found"; "The program used to create this object is Forms. That program is either not installed on your computer or it is not responding. To edit this object, install Forms or ensure that any dialog boxes in Forms are closed." [...] Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code.

Manual and additional solutions:

Scripting solution:

Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.

del %temp%\vbe\*.exd
del %temp%\excel8.0\*.exd
del %appdata%\microsoft\forms\*.exd
del %appdata%\microsoft\local\*.exd
del %temp%\word8.0\*.exd
del %temp%\PPT11.0\*.exd

Additional step:

If the steps above do not resolve your issue, another step that can be tested (see warning below):

  1. On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.

  2. Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.

  3. Save and reopen the file. Test for resolution.

If resolved, provide this updated project to additional users.

Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.

Could not connect to React Native development server on Android

In my case, my emulator has a proxy setting, after turning it off everything works fine.

Combine two columns of text in pandas dataframe

As many have mentioned previously, you must convert each column to string and then use the plus operator to combine two string columns. You can get a large performance improvement by using NumPy.

%timeit df['Year'].values.astype(str) + df.quarter
71.1 ms ± 3.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df['Year'].astype(str) + df['quarter']
565 ms ± 22.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

How to disable all div content

I would use an improved version of Cletus' function:

 $.fn.disable = function() {
    return this.each(function() {          
      if (typeof this.disabled != "undefined") {
        $(this).data('jquery.disabled', this.disabled);

        this.disabled = true;
      }
    });
};

$.fn.enable = function() {
    return this.each(function() {
      if (typeof this.disabled != "undefined") {
        this.disabled = $(this).data('jquery.disabled');
      }
    });
};

Which stores the original 'disabled' property of the element.

$('#myDiv *').disable();

How to copy file from HDFS to the local file system

you can accomplish in both these ways.

1.hadoop fs -get <HDFS file path> <Local system directory path>
2.hadoop fs -copyToLocal <HDFS file path> <Local system directory path>

Ex:

My files are located in /sourcedata/mydata.txt I want to copy file to Local file system in this path /user/ravi/mydata

hadoop fs -get /sourcedata/mydata.txt /user/ravi/mydata/

GROUP BY to combine/concat a column

A good question. Should tell you it took some time to crack this one. Here is my result.

DECLARE @TABLE TABLE
(  
ID INT,  
USERS VARCHAR(10),  
ACTIVITY VARCHAR(10),  
PAGEURL VARCHAR(10)  
)

INSERT INTO @TABLE  
VALUES  (1, 'Me', 'act1', 'ab'),
        (2, 'Me', 'act1', 'cd'),
        (3, 'You', 'act2', 'xy'),
        (4, 'You', 'act2', 'st')


SELECT T1.USERS, T1.ACTIVITY,   
        STUFF(  
        (  
        SELECT ',' + T2.PAGEURL  
        FROM @TABLE T2  
        WHERE T1.USERS = T2.USERS  
        FOR XML PATH ('')  
        ),1,1,'')  
FROM @TABLE T1  
GROUP BY T1.USERS, T1.ACTIVITY

MAMP mysql server won't start. No mysql processes are running

I was running MAMP 4.1 on windows and MYSQL 5.7 .Was having this problem many times and found out a fix for this: For me deleting the log files was not working then just delete

  • mysql-bin.index
  • YOUR_PC_NAME.pid

and boom it starts working again. If this also doesn't work for your, remember to delete each file one by one and keep checking if any works for you. Make sure to backup always.

How do I set environment variables from Java?

Like most people who have found this thread, I was writing some unit tests and needed to modify the environment variables to set the correct conditions for the test to run. However, I found the most upvoted answers had some issues and/or were very cryptic or overly complicated. Hopefully this will help others to sort out the solution more quickly.

First off, I finally found @Hubert Grzeskowiak's solution to be the simplest and it worked for me. I wish I would have come to that one first. It's based on @Edward Campbell's answer, but without the complicating for loop search.

However, I started with @pushy's solution, which got the most upvotes. It is a combo of @anonymous and @Edward Campbell's. @pushy claims both approaches are needed to cover both Linux and Windows environments. I'm running under OS X and find that both work (once an issue with @anonymous approach is fixed). As others have noted, this solution works most of the time, but not all.

I think the source of most of the confusion comes from @anonymous's solution operating on the 'theEnvironment' field. Looking at the definition of the ProcessEnvironment structure, 'theEnvironment' is not a Map< String, String > but rather it is a Map< Variable, Value >. Clearing the map works fine, but the putAll operation rebuilds the map a Map< String, String >, which potentially causes problems when subsequent operations operate on the data structure using the normal API that expects Map< Variable, Value >. Also, accessing/removing individual elements is a problem. The solution is to access 'theEnvironment' indirectly through 'theUnmodifiableEnvironment'. But since this is a type UnmodifiableMap the access must be done through the private variable 'm' of the UnmodifiableMap type. See getModifiableEnvironmentMap2 in code below.

In my case I needed to remove some of the environment variables for my test (the others should be unchanged). Then I wanted to restore the environment variables to their prior state after the test. The routines below make that straight forward to do. I tested both versions of getModifiableEnvironmentMap on OS X, and both work equivalently. Though based on comments in this thread, one may be a better choice than the other depending on the environment.

Note: I did not include access to the 'theCaseInsensitiveEnvironmentField' since that seems to be Windows specific and I had no way to test it, but adding it should be straight forward.

private Map<String, String> getModifiableEnvironmentMap() {
    try {
        Map<String,String> unmodifiableEnv = System.getenv();
        Class<?> cl = unmodifiableEnv.getClass();
        Field field = cl.getDeclaredField("m");
        field.setAccessible(true);
        Map<String,String> modifiableEnv = (Map<String,String>) field.get(unmodifiableEnv);
        return modifiableEnv;
    } catch(Exception e) {
        throw new RuntimeException("Unable to access writable environment variable map.");
    }
}

private Map<String, String> getModifiableEnvironmentMap2() {
    try {
        Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        Field theUnmodifiableEnvironmentField = processEnvironmentClass.getDeclaredField("theUnmodifiableEnvironment");
        theUnmodifiableEnvironmentField.setAccessible(true);
        Map<String,String> theUnmodifiableEnvironment = (Map<String,String>)theUnmodifiableEnvironmentField.get(null);

        Class<?> theUnmodifiableEnvironmentClass = theUnmodifiableEnvironment.getClass();
        Field theModifiableEnvField = theUnmodifiableEnvironmentClass.getDeclaredField("m");
        theModifiableEnvField.setAccessible(true);
        Map<String,String> modifiableEnv = (Map<String,String>) theModifiableEnvField.get(theUnmodifiableEnvironment);
        return modifiableEnv;
    } catch(Exception e) {
        throw new RuntimeException("Unable to access writable environment variable map.");
    }
}

private Map<String, String> clearEnvironmentVars(String[] keys) {

    Map<String,String> modifiableEnv = getModifiableEnvironmentMap();

    HashMap<String, String> savedVals = new HashMap<String, String>();

    for(String k : keys) {
        String val = modifiableEnv.remove(k);
        if (val != null) { savedVals.put(k, val); }
    }
    return savedVals;
}

private void setEnvironmentVars(Map<String, String> varMap) {
    getModifiableEnvironmentMap().putAll(varMap);   
}

@Test
public void myTest() {
    String[] keys = { "key1", "key2", "key3" };
    Map<String, String> savedVars = clearEnvironmentVars(keys);

    // do test

    setEnvironmentVars(savedVars);
}

Error sending json in POST to web API service

I had all my settings covered in the accepted answer. The problem I had was that I was trying to update the Entity Framework entity type "Task" like:

public IHttpActionResult Post(Task task)

What worked for me was to create my own entity "DTOTask" like:

public IHttpActionResult Post(DTOTask task)

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

Changing color of Twitter bootstrap Nav-Pills

I use this snipped to change the active class for all pills in the same ul (applied at document ready):

$('ul.nav.nav-pills li a').click(function() {           
    $(this).parent().addClass('active').siblings().removeClass('active');           
});

Checking if a variable is defined?

Try "unless" instead of "if"

a = "apple"
# Note that b is not declared
c = nil

unless defined? a
    puts "a is not defined"
end

unless defined? b
    puts "b is not defined"
end

unless defined? c
    puts "c is not defined"
end

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

How to make a div have a fixed size?

<div class="ai">a b c d e f</div> // something like ~100px
<div class="ai">a b c d e</div> // ~80
<div class="ai">a b c d</div> // ~60 

<script>

function _reWidthAll_div(classname) {

var _maxwidth = 0;

    $(classname).each(function(){

    var _width = $(this).width();

    _maxwidth = (_width >= _maxwidth) ? _width : _maxwidth; // define max width
    });    

$(classname).width(_maxwidth); // return all div same width

}

_reWidthAll_div('.ai');

</script>

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

How to fix docker: Got permission denied issue

you can follow these steps and this will work for you:

  1. create a docker group sudo groupadd docker
  2. add your user to this group sudo usermod -aG docker $USER
  3. list the groups to make sure that docker group created successfully by running this command groups
  4. run the following command also to change the session for docker group newgrp docker
  5. change the group ownership for file docker.socksudo chown root:docker /var/run/docker.sock
  6. change the ownership for .docker directory sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
  7. finally sudo chmod g+rwx "$HOME/.docker" -R

After that test you can run docker ps -a

Reset the database (purge all), then seed a database

You can use rake db:reset when you want to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following: Drop the database: rake db:drop Load the schema: rake db:schema:load Seed the data: rake db:seed

But if you want to completely drop your database you can use rake db:drop. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.

This is a detailed article about the most important rake database commands.

Download a single folder or directory from a GitHub repo

try it.

https://github.com/twfb/git-directory-download

usage: gitd [-h] [-u URL] [-r] [-p] [--proxy PROXY]

optional arguments:
  -h, --help         show this help message and exit
  -u URL, --url URL  github url, split by ",", example: "https://x, http://y"
  -r, --raw          download from raw url
  -p, --parse        download by parsing html
  --proxy PROXY      proxy config, example "socks5://127.0.0.1:7891"

Example:
  1. download by raw url: gitd -u "https://github.com/twfb/git-directory-download"
  2. download by raw url: gitd -r -u "https://github.com/twfb/git-directory-download"
  3. dowmload by parsing: gitd -p -u "https://github.com/twfb/git-directory-download"
  4. download by raw url with proxy: gitd -r -u "https://github.com/twfb/git-directory-download" --proxy "socks5://127.0.0.1:7891"

Why use a ReentrantLock if one can use synchronized(this)?

Synchronized locks does not offer any mechanism of waiting queue in which after the execution of one thread any thread running in parallel can acquire the lock. Due to which the thread which is there in the system and running for a longer period of time never gets chance to access the shared resource thus leading to starvation.

Reentrant locks are very much flexible and has a fairness policy in which if a thread is waiting for a longer time and after the completion of the currently executing thread we can make sure that the longer waiting thread gets the chance of accessing the shared resource hereby decreasing the throughput of the system and making it more time consuming.

Add border-bottom to table row <tr>

Use border-collapse:collapse on table and border-bottom: 1pt solid black; on the tr

Distinct() with lambda?

This will do what you want but I don't know about performance:

var distinctValues =
    from cust in myCustomerList
    group cust by cust.CustomerId
    into gcust
    select gcust.First();

At least it's not verbose.

Toggle button using two image on different state

Do this:

<ToggleButton 
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/check"   <!--check.xml-->
        android:layout_margin="10dp"
        android:textOn=""
        android:textOff=""
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"/>

create check.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
        android:state_checked="false"/>

 </selector>

using awk with column value conditions

This is more readable for me

awk '{if ($2 ~ /findtext/) print $3}' <infile>

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

How to round the minute of a datetime object

General function to round a datetime at any time lapse in seconds:

def roundTime(dt=None, roundTo=60):
   """Round a datetime object to any time lapse in seconds
   dt : datetime.datetime object, default now.
   roundTo : Closest number of seconds to round to, default 1 minute.
   Author: Thierry Husson 2012 - Use it as you want but don't blame me.
   """
   if dt == None : dt = datetime.datetime.now()
   seconds = (dt.replace(tzinfo=None) - dt.min).seconds
   rounding = (seconds+roundTo/2) // roundTo * roundTo
   return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)

Samples with 1 hour rounding & 30 minutes rounding:

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00

print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=30*60)
2012-12-31 23:30:00

Change the selected value of a drop-down list with jQuery

Another option is to set the control param ClientID="Static" in .net and then you can access the object in JQuery by the ID you set.

Pass Arraylist as argument to function

Define it as

<return type> AnalyzeArray(ArrayList<Integer> list) {

How to specify multiple conditions in an if statement in javascript

I am currently checking a large number of conditions, which becomes unwieldy using the if statement method beyond say 4 conditions. Just to share a clean looking alternative for future viewers... which scales nicely, I use:

var a = 0;
var b = 0;

a += ("condition 1")? 1 : 0; b += 1;
a += ("condition 2")? 1 : 0; b += 1;
a += ("condition 3")? 1 : 0; b += 1;
a += ("condition 4")? 1 : 0; b += 1;
a += ("condition 5")? 1 : 0; b += 1;
a += ("condition 6")? 1 : 0; b += 1;
// etc etc

if(a == b) {
    //do stuff
}

What's the regular expression that matches a square bracket?

If you're looking to find both variations of the square brackets at the same time, you can use the following pattern which defines a range of either the [ sign or the ] sign: /[\[\]]/

List all of the possible goals in Maven 2?

Lets make it very simple:

Maven Lifecycles: 1. Clean 2. Default (build) 3. Site

Maven Phases of the Default Lifecycle: 1. Validate 2. Compile 3. Test 4. Package 5. Verify 6. Install 7. Deploy

Note: Don't mix or get confused with maven goals with maven lifecycle.

See Maven Build Lifecycle Basics1

AJAX POST and Plus Sign ( + ) -- How to Encode?

In JavaScript try:

encodeURIComponent() 

and in PHP:

urldecode($_POST['field']);

What is the best way to compare 2 folder trees on windows?

SyncToy is a free application from Microsoft with a "Preview" mode for comparing two paths. For example:

SyncToy Preview screenshot (source: https://maketecheasier-2d0f.kxcdn.com/assets/uploads/2010/06/synctoy-preview.png)

You can then choose one of three modes ("Synchronize", "Echo" and "Contribute") to resolve the differences.

Lastly, it comes with SyncToyCmd for creating and synchronizing folder pairs from the CLI or a Scheduled Task.

How to throw RuntimeException ("cannot find symbol")

you will have to instantiate it before you throw it

throw new RuntimeException(arg0) 

PS: Intrestingly enough the Netbeans IDE should have already pointed out that compile time error

How do I make HttpURLConnection use a proxy?

Set following before you openConnection,

System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port_number");

If proxy requires authentication,

System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");

Difference between Key, Primary Key, Unique Key and Index in MySQL

The primary key is used to work with different tables. This is the foundation of relational databases. If you have a book database it's better to create 2 tables - 1) books and 2) authors with INT primary key "id". Then you use id in books instead of authors name.

The unique key is used if you don't want to have repeated entries. For example you may have title in your book table and want to be sure there is only one entry for each title.

iOS download and save image inside app

Here is code to download an image asynchronously from url and then save where you want in objective-c:->

    + (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
        {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            [NSURLConnection sendAsynchronousRequest:request
                                               queue:[NSOperationQueue mainQueue]
                                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                       if ( !error )
                                       {
                                           UIImage *image = [[UIImage alloc] initWithData:data];
                                           completionBlock(YES,image);
                                       } else{
                                           completionBlock(NO,nil);
                                       }
                                   }];
        }

How to stop (and restart) the Rails Server?

I had to restart the rails application on the production so I looked for an another answer. I have found it below:

http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger

Find Active Tab using jQuery and Twitter Bootstrap

First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.

  <ul class='nav nav-tabs'>
    <li class='active'><a href='#home'>Home</a></li>
    <li><a href='#menu1'>Menu 1</a></li>
    <li><a href='#menu2'>Menu 2</a></li>
    <li><a href='#menu3'>Menu 3</a></li>
  </ul>

  <div class='tab-content'>
    <div id='home' class='tab-pane fade in active'>
      <h3>HOME</h3>
    <div id='menu1' class='tab-pane fade'>
      <h3>Menu 1</h3>
    </div>
    <div id='menu2' class='tab-pane fade'>
      <h3>Menu 2</h3>
    </div>
    <div id='menu3' class='tab-pane fade'>
      <h3>Menu 3</h3>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
// Handling data-toggle manually
    $('.nav-tabs a').click(function(){
        $(this).tab('show');
    });
// The on tab shown event
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        alert('Hello from the other siiiiiide!');
        var current_tab = e.target;
        var previous_tab = e.relatedTarget;
    });
});
</script>

Angular 2 two way binding using ngModel is not working

Angular 2 Beta

This answer is for those who use Javascript for angularJS v.2.0 Beta.

To use ngModel in your view you should tell the angular's compiler that you are using a directive called ngModel.

How?

To use ngModel there are two libraries in angular2 Beta, and they are ng.common.FORM_DIRECTIVES and ng.common.NgModel.

Actually ng.common.FORM_DIRECTIVES is nothing but group of directives which are useful when you are creating a form. It includes NgModel directive also.

app.myApp = ng.core.Component({
    selector: 'my-app',
    templateUrl: 'App/Pages/myApp.html',
    directives: [ng.common.NgModel] // specify all your directives here
}).Class({
    constructor: function () {
        this.myVar = {};
        this.myVar.text = "Testing";
    },

});

Creating NSData from NSString in Swift

Swift 4 & 3

Creating Data object from String object has been changed in Swift 3. Correct version now is:

let data = "any string".data(using: .utf8)

Get checkbox list values with jQuery

You can try this...

$(document).ready(function() {
        $("button").click(function(){
            var checkBoxValues = [];
            $.each($("input[name='check_name']:checked"), function(){
                checkBoxValues.push($(this).val());
            });

            console.log(checkBoxValues);

        });
    });

Add alternating row color to SQL Server Reporting services report

Using IIF(RowNumber...) can lead to some issues when rows are being grouped and another alternative is to use a simple VBScript function to determine the color.

It's a little more effort but when the basic solution does not suffice, it's a nice alternative.

Basically, you add code to the Report as follows...

Private bOddRow As Boolean
'*************************************************************************
' -- Display green-bar type color banding in detail rows
' -- Call from BackGroundColor property of all detail row textboxes
' -- Set Toggle True for first item, False for others.
'*************************************************************************
Function AlternateColor(ByVal OddColor As String, _
         ByVal EvenColor As String, ByVal Toggle As Boolean) As String
    If Toggle Then bOddRow = Not bOddRow
    If bOddRow Then
        Return OddColor
    Else
        Return EvenColor
    End If
End Function

Then on each cell, set the BackgroundColor as follows:

=Code.AlternateColor("AliceBlue", "White", True)

Full details are on this Wrox article

How do I load an url in iframe with Jquery

$("#button").click(function () { 
    $("#frame").attr("src", "http://www.example.com/");
});

HTML:

 <div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

Append values to a set in Python

The way I like to do this is to convert both the original set and the values I'd like to add into lists, add them, and then convert them back into a set, like this:

setMenu = {"Eggs", "Bacon"}
print(setMenu)
> {'Bacon', 'Eggs'}
setMenu = set(list(setMenu) + list({"Spam"}))
print(setMenu)
> {'Bacon', 'Spam', 'Eggs'}
setAdditions = {"Lobster", "Sausage"}
setMenu = set(list(setMenu) + list(setAdditions))
print(setMenu)
> {'Lobster', 'Spam', 'Eggs', 'Sausage', 'Bacon'}

This way I can also easily add multiple sets using the same logic, which gets me an TypeError: unhashable type: 'set' if I try doing it with the .update() method.

How can I protect my .NET assemblies from decompilation?

I know this is old but, Themida is the most advanced anti-cracking software I've ever used.
It's not free, though.

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

Using Chrome, how to find to which events are bound to an element

findEventHandlers is a jquery plugin, the raw code is here: https://raw.githubusercontent.com/ruidfigueiredo/findHandlersJS/master/findEventHandlers.js

Steps

  1. Paste the raw code directely into chrome's console(note:must have jquery loaded already)

  2. Use the following function call: findEventHandlers(eventType, selector);
    to find the corresponding's selector specified element's eventType handler.

Example:

findEventHandlers("click", "#clickThis");

Then if any, the available event handler will show bellow, you need to expand to find the handler, right click the function and select show function definition

See: https://blinkingcaret.wordpress.com/2014/01/17/quickly-finding-and-debugging-jquery-event-handlers/

List Directories and get the name of the Directory

You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()

For example, as explained here: [x[0] for x in os.walk(directory)] should give you all of the subdirectories, recursively.

How to print Unicode character in Python?

In Python 2, you declare unicode strings with a u, as in u"?" and use decode() and encode() to translate to and from unicode, respectively.

It's quite a bit easier in Python 3. A very good overview can be found here. That presentation clarified a lot of things for me.

Enable/Disable a dropdownbox in jquery

try this

 <script type="text/javascript">
        $(document).ready(function () {
            $("#chkdwn2").click(function () {
                if (this.checked)
                    $('#dropdown').attr('disabled', 'disabled');
                else
                    $('#dropdown').removeAttr('disabled');
            });
        });
    </script>

Execute method on startup in Spring

If you are using spring-boot, this is the best answer.

I feel that @PostConstruct and other various life cycle interjections are round-about ways. These can lead directly to runtime issues or cause less than obvious defects due to unexpected bean/context lifecycle events. Why not just directly invoke your bean using plain Java? You still invoke the bean the 'spring way' (eg: through the spring AoP proxy). And best of all, it's plain java, can't get any simpler than that. No need for context listeners or odd schedulers.

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext app = SpringApplication.run(DemoApplication.class, args);

        MyBean myBean = (MyBean)app.getBean("myBean");

        myBean.invokeMyEntryPoint();
    }
}

How to make a Bootstrap accordion collapse when clicking the header div?

Simple solution would be to remove padding from .panel-heading and add to .panel-title a.

.panel-heading {
    padding: 0;
}
.panel-title a {
    display: block;
    padding: 10px 15px;
}

This solution is similar to the above one posted by calfzhou, slightly different.

Using CSS how to change only the 2nd column of a table

You can use the :nth-child pseudo class like this:

.countTable table table td:nth-child(2)

Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.

Angular 4 img src is not found

Try This:

<img class="img-responsive" src="assets/img/google-body-ads.png">

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

Correct path for img on React.js

If you used create-react-app to create your project then your public folder is accessible. So you need to add your image folder inside the public folder.

public/images/

<img src="/images/logo.png" />

PDO's query vs execute

No, they're not the same. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution. Which means you can do:

$sth = $db->prepare("SELECT * FROM table WHERE foo = ?");
$sth->execute(array(1));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

$sth->execute(array(2));
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

They generally will give you a performance improvement, although not noticeable on a small scale. Read more on prepared statements (MySQL version).

How to make HTML code inactive with comments

Use:

<!-- This is a comment for an HTML page and it will not display in the browser -->

For more information, I think 3 On SGML and HTML may help you.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

In addition to all of the great answers, there is a concept called lazy loading:

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed.

Using it properly, you can reduce the loading time of your application. And Kotlin way of it's implementation is by lazy() which loads the needed value to your variable whenever it's needed.

But lateinit is used when you are sure a variable won't be null or empty and will be initialized before you use it -e.g. in onResume() method for android- and so you don't want to declare it as a nullable type.

Getting the class name of an instance?

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:

x.__class__.__name__

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

The solution is very simple! Put this line before curl_exec:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

For me it works.

installing requests module in python 2.7 windows

  1. Download the source code(zip or rar package).
  2. Run the setup.py inside.

What is the email subject length limit?

RFC2322 states that the subject header "has no length restriction"

but to produce long headers but you need to split it across multiple lines, a process called "folding".

subject is defined as "unstructured" in RFC 5322

here's some quotes ([...] indicate stuff i omitted)

3.6.5. Informational Fields
  The informational fields are all optional.  The "Subject:" and
  "Comments:" fields are unstructured fields as defined in section
  2.2.1, [...]

2.2.1. Unstructured Header Field Bodies
  Some field bodies in this specification are defined simply as
  "unstructured" (which is specified in section 3.2.5 as any printable
  US-ASCII characters plus white space characters) with no further
  restrictions.  These are referred to as unstructured field bodies.
  Semantically, unstructured field bodies are simply to be treated as a
  single line of characters with no further processing (except for
  "folding" and "unfolding" as described in section 2.2.3).

2.2.3  [...]  An unfolded header field has no length restriction and
  therefore may be indeterminately long.

A server with the specified hostname could not be found

Turn off the push notification. Then,Restart your XCode and Turn back ON the Push Notification. It works for me.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

how do I print an unsigned char as hex in c++ using ostream?

I think we are missing an explanation of how these type conversions work.

char is platform dependent signed or unsigned. In x86 char is equivalent to signed char.

When an integral type (char, short, int, long) is converted to a larger capacity type, the conversion is made by adding zeros to the left in case of unsigned types and by sign extension for signed ones. Sign extension consists in replicating the most significant (leftmost) bit of the original number to the left till we reach the bit size of the target type.

Hence if I am in a signed char by default system and I do this:

char a = 0xF0; // Equivalent to the binary: 11110000
std::cout << std::hex << static_cast<int>(a);

We would obtain F...F0 since the leading 1 bit has been extended.

If we want to make sure that we only print F0 in any system we would have to make an additional intermediate type cast to an unsigned char so that zeros are added instead and, since they are not significant for a integer with only 8-bits, not printed:

char a = 0xF0; // Equivalent to the binary: 11110000
std::cout << std::hex << static_cast<int>(static_cast<unsigned char>(a));

This produces F0

What is the difference between canonical name, simple name and class name in Java Class?

Adding local classes, lambdas and the toString() method to complete the previous two answers. Further, I add arrays of lambdas and arrays of anonymous classes (which do not make any sense in practice though):

package com.example;

public final class TestClassNames {
    private static void showClass(Class<?> c) {
        System.out.println("getName():          " + c.getName());
        System.out.println("getCanonicalName(): " + c.getCanonicalName());
        System.out.println("getSimpleName():    " + c.getSimpleName());
        System.out.println("toString():         " + c.toString());
        System.out.println();
    }

    private static void x(Runnable r) {
        showClass(r.getClass());
        showClass(java.lang.reflect.Array.newInstance(r.getClass(), 1).getClass()); // Obtains an array class of a lambda base type.
    }

    public static class NestedClass {}

    public class InnerClass {}

    public static void main(String[] args) {
        class LocalClass {}
        showClass(void.class);
        showClass(int.class);
        showClass(String.class);
        showClass(Runnable.class);
        showClass(SomeEnum.class);
        showClass(SomeAnnotation.class);
        showClass(int[].class);
        showClass(String[].class);
        showClass(NestedClass.class);
        showClass(InnerClass.class);
        showClass(LocalClass.class);
        showClass(LocalClass[].class);
        Object anonymous = new java.io.Serializable() {};
        showClass(anonymous.getClass());
        showClass(java.lang.reflect.Array.newInstance(anonymous.getClass(), 1).getClass()); // Obtains an array class of an anonymous base type.
        x(() -> {});
    }
}

enum SomeEnum {
   BLUE, YELLOW, RED;
}

@interface SomeAnnotation {}

This is the full output:

getName():          void
getCanonicalName(): void
getSimpleName():    void
toString():         void

getName():          int
getCanonicalName(): int
getSimpleName():    int
toString():         int

getName():          java.lang.String
getCanonicalName(): java.lang.String
getSimpleName():    String
toString():         class java.lang.String

getName():          java.lang.Runnable
getCanonicalName(): java.lang.Runnable
getSimpleName():    Runnable
toString():         interface java.lang.Runnable

getName():          com.example.SomeEnum
getCanonicalName(): com.example.SomeEnum
getSimpleName():    SomeEnum
toString():         class com.example.SomeEnum

getName():          com.example.SomeAnnotation
getCanonicalName(): com.example.SomeAnnotation
getSimpleName():    SomeAnnotation
toString():         interface com.example.SomeAnnotation

getName():          [I
getCanonicalName(): int[]
getSimpleName():    int[]
toString():         class [I

getName():          [Ljava.lang.String;
getCanonicalName(): java.lang.String[]
getSimpleName():    String[]
toString():         class [Ljava.lang.String;

getName():          com.example.TestClassNames$NestedClass
getCanonicalName(): com.example.TestClassNames.NestedClass
getSimpleName():    NestedClass
toString():         class com.example.TestClassNames$NestedClass

getName():          com.example.TestClassNames$InnerClass
getCanonicalName(): com.example.TestClassNames.InnerClass
getSimpleName():    InnerClass
toString():         class com.example.TestClassNames$InnerClass

getName():          com.example.TestClassNames$1LocalClass
getCanonicalName(): null
getSimpleName():    LocalClass
toString():         class com.example.TestClassNames$1LocalClass

getName():          [Lcom.example.TestClassNames$1LocalClass;
getCanonicalName(): null
getSimpleName():    LocalClass[]
toString():         class [Lcom.example.TestClassNames$1LocalClass;

getName():          com.example.TestClassNames$1
getCanonicalName(): null
getSimpleName():    
toString():         class com.example.TestClassNames$1

getName():          [Lcom.example.TestClassNames$1;
getCanonicalName(): null
getSimpleName():    []
toString():         class [Lcom.example.TestClassNames$1;

getName():          com.example.TestClassNames$$Lambda$1/1175962212
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212
getSimpleName():    TestClassNames$$Lambda$1/1175962212
toString():         class com.example.TestClassNames$$Lambda$1/1175962212

getName():          [Lcom.example.TestClassNames$$Lambda$1;
getCanonicalName(): com.example.TestClassNames$$Lambda$1/1175962212[]
getSimpleName():    TestClassNames$$Lambda$1/1175962212[]
toString():         class [Lcom.example.TestClassNames$$Lambda$1;

So, here are the rules. First, lets start with primitive types and void:

  1. If the class object represents a primitive type or void, all the four methods simply returns its name.

Now the rules for the getName() method:

  1. Every non-lambda and non-array class or interface (i.e, top-level, nested, inner, local and anonymous) has a name (which is returned by getName()) that is the package name followed by a dot (if there is a package), followed by the name of its class-file as generated by the compiler (whithout the suffix .class). If there is no package, it is simply the name of the class-file. If the class is an inner, nested, local or anonymous class, the compiler should generate at least one $ in its class-file name. Note that for anonymous classes, the class name would end with a dollar-sign followed by a number.
  2. Lambda class names are generally unpredictable, and you shouldn't care about they anyway. Exactly, their name is the name of the enclosing class, followed by $$Lambda$, followed by a number, followed by a slash, followed by another number.
  3. The class descriptor of the primitives are Z for boolean, B for byte, S for short, C for char, I for int, J for long, F for float and D for double. For non-array classes and interfaces the class descriptor is L followed by what is given by getName() followed by ;. For array classes, the class descriptor is [ followed by the class descriptor of the component type (which may be itself another array class).
  4. For array classes, the getName() method returns its class descriptor. This rule seems to fail only for array classes whose the component type is a lambda (which possibly is a bug), but hopefully this should not matter anyway because there is no point even on the existence of array classes whose component type is a lambda.

Now, the toString() method:

  1. If the class instance represents an interface (or an annotation, which is a special type of interface), the toString() returns "interface " + getName(). If it is a primitive, it returns simply getName(). If it is something else (a class type, even if it is a pretty weird one), it returns "class " + getName().

The getCanonicalName() method:

  1. For top-level classes and interfaces, the getCanonicalName() method returns just what the getName() method returns.
  2. The getCanonicalName() method returns null for anonymous or local classes and for array classes of those.
  3. For inner and nested classes and interfaces, the getCanonicalName() method returns what the getName() method would replacing the compiler-introduced dollar-signs by dots.
  4. For array classes, the getCanonicalName() method returns null if the canonical name of the component type is null. Otherwise, it returns the canonical name of the component type followed by [].

The getSimpleName() method:

  1. For top-level, nested, inner and local classes, the getSimpleName() returns the name of the class as written in the source file.
  2. For anonymous classes the getSimpleName() returns an empty String.
  3. For lambda classes the getSimpleName() just returns what the getName() would return without the package name. This do not makes much sense and looks like a bug for me, but there is no point in calling getSimpleName() on a lambda class to start with.
  4. For array classes the getSimpleName() method returns the simple name of the component class followed by []. This have the funny/weird side-effect that array classes whose component type is an anonymous class have just [] as their simple names.

How to clear the entire array?

It is as simple as :

Erase aFirstArray

How do I tell a Python script to use a particular version

You can add a shebang line the to the top of the script:

#!/usr/bin/env python2.7

But that will only work when executing as ./my_program.py.

If you execute as python my_program.py, then the whatever Python version that which python returns will be used.

In re: to virtualenv use: virtualenv -p /usr/bin/python3.2 or whatever to set it up to use that Python executable.

Get month and year from a datetime in SQL Server 2005

( Month(Created) + ',' + Year(Created) ) AS Date

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

Have tried for many times, the above answers don't solve my quesiton, but this command helped me:

sudo apt-get install php-mbstring

How do I change the JAVA_HOME for ant?

You will need to change JAVA_HOME path to the Java SDK directory instead of the Java RE directory. In Windows you can do this using the set command in a command prompt.

e.g.

set JAVA_HOME="C:\Program Files\Java\jdk1.6.0_14"

Programmatically close aspx page from code behind

 protected void btnOK_Click(object sender, EventArgs e)
        {

          // Your code goes here.
          if(isSuccess)
          {
                  string  close =    @"<script type='text/javascript'>
                                window.returnValue = true;
                                window.close();
                                </script>";
            base.Response.Write(close);
            }

        }

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

Best way to do this is to use a function:

<div ng-repeat="product in products | filter: myFilter">

$scope.myFilter = function (item) { 
    return item === 'red' || item === 'blue'; 
};

Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.

Batch file script to zip files

I like PodTech.io's answer to achieve this without additional tools. For me, it did not run out of the box, so I had to slightly change it. I am not sure if the command wScript.Sleep 12000 (12 sec delay) in the original script is required or not, so I kept it.

Here's the modified script Zip.cmd based on his answer, which works fine on my end:

@echo off   
if "%1"=="" goto end

setlocal
set TEMPDIR=%TEMP%\ZIP
set FILETOZIP=%1
set OUTPUTZIP=%2.zip
if "%2"=="" set OUTPUTZIP=%1.zip

:: preparing VBS script
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo Set fso = WScript.CreateObject("Scripting.FileSystemObject") >> _zipIt.vbs
echo Set objZipFile = fso.CreateTextFile(ZipFile, True) >> _zipIt.vbs
echo objZipFile.Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo objZipFile.Close >> _zipIt.vbs
echo Set objShell = WScript.CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo Set objZip = objShell.NameSpace(fso.GetAbsolutePathName(ZipFile)) >> _zipIt.vbs
echo if not (objZip is nothing) then  >> _zipIt.vbs
echo    objZip.CopyHere(source) >> _zipIt.vbs
echo    wScript.Sleep 12000 >> _zipIt.vbs
echo end if >> _zipIt.vbs

@ECHO Zipping, please wait...
mkdir %TEMPDIR%
xcopy /y /s %FILETOZIP% %TEMPDIR%
WScript _zipIt.vbs  %TEMPDIR%  %OUTPUTZIP%
del _zipIt.vbs
rmdir /s /q  %TEMPDIR%

@ECHO ZIP Completed.
:end

Usage:

  • One parameter (no wildcards allowed here):

    Zip FileToZip.txt

    will create FileToZip.txt.zip in the same folder containing the zipped file FileToZip.txt.

  • Two parameters (optionally with wildcards for the first parameter), e.g.

    Zip *.cmd Scripts

    creates Scripts.zip in the same folder containing all matching *.cmd files.


Note: If you want to debug the VBS script, check out this hint, it describes how to activate the debugger to go through it step by step.

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Cannot add a project to a Tomcat server in Eclipse

Steps I used to resolve it:

  1. Double click on Tomcat Server in the Servers tab.
  2. In a dropdown next to Runtime Environment:, select Apache Tomcat your version
  3. Click on save.

Now, you should be able to add to server on right click "Add and Remove".

Note: Additionally, when on clear/run, you get an error for multiple instances, open server.xml and ensure that it contains a single instance of each application and not multiple.

How to cast List<Object> to List<MyClass>

you can always cast any object to any type by up-casting it to Object first. in your case:

(List<Customer>)(Object)list; 

you must be sure that at runtime the list contains nothing but Customer objects.

Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

The excellent JavaScript library KeyboardJS handles all types of key presses including the SHIFT key. It even allows specifying key combinations such as first pressing CTRL+x and then a.

KeyboardJS.on('shift', function() { ...handleDown... }, function() { ...handleUp... });

If you want a simple version, head to the answer by @tonycoupland):

var shiftHeld = false;
$('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

I got this error when there was not enough disk space to restore Db. Cleaning some space solved it.

Avoid web.config inheritance in child web application using inheritInChildApplications

It needs to go directly under the root <configuration> node and you need to set a path like this:

<?xml version="1.0"?>
<configuration>
    <location path="." inheritInChildApplications="false"> 
        <!-- Stuff that shouldn't be inherited goes in here -->
    </location>
</configuration>

A better way to handle configuration inheritance is to use a <clear/> in the child config wherever you don't want to inherit. So if you didn't want to inherit the parent config's connection strings you would do something like this:

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <clear/>
        <!-- Child config's connection strings -->
    </connectionStrings>
</configuration>

Polling the keyboard (detect a keypress) in python

From the comments:

import msvcrt # built-in module

def kbfunc():
    return ord(msvcrt.getch()) if msvcrt.kbhit() else 0

Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:

#include <conio.h>

int kb_inkey () {
   int rc;
   int key;

   key = _kbhit();

   if (key == 0) {
      rc = 0;
   } else {
      rc = _getch();
   }

   return rc;
}

And I access it in python using the ctypes module (built into python 2.5):

import ctypes
import time

#
# first, load the DLL
#


try:
    kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
    raise ("Error Loading PyKeyboardAccess.dll")


#
# now, find our function
#

try:
    kbfunc = kblib.kb_inkey
except:
    raise ("Could not find the kb_inkey function in the dll!")


#
# Ok, now let's demo the capability
#

while 1:
    x = kbfunc()

    if x != 0:
        print "Got key: %d" % x
    else:
        time.sleep(.01)

Swift do-try-catch syntax

I suspect this just hasn’t been implemented properly yet. The Swift Programming Guide definitely seems to imply that the compiler can infer exhaustive matches 'like a switch statement'. It doesn’t make any mention of needing a general catch in order to be exhaustive.

You'll also notice that the error is on the try line, not the end of the block, i.e. at some point the compiler will be able to pinpoint which try statement in the block has unhandled exception types.

The documentation is a bit ambiguous though. I’ve skimmed through the ‘What’s new in Swift’ video and couldn’t find any clues; I’ll keep trying.

Update:

We’re now up to Beta 3 with no hint of ErrorType inference. I now believe if this was ever planned (and I still think it was at some point), the dynamic dispatch on protocol extensions probably killed it off.

Beta 4 Update:

Xcode 7b4 added doc comment support for Throws:, which “should be used to document what errors can be thrown and why”. I guess this at least provides some mechanism to communicate errors to API consumers. Who needs a type system when you have documentation!

Another update:

After spending some time hoping for automatic ErrorType inference, and working out what the limitations would be of that model, I’ve changed my mind - this is what I hope Apple implements instead. Essentially:

// allow us to do this:
func myFunction() throws -> Int

// or this:
func myFunction() throws CustomError -> Int

// but not this:
func myFunction() throws CustomErrorOne, CustomErrorTwo -> Int

Yet Another Update

Apple’s error handling rationale is now available here. There have also been some interesting discussions on the swift-evolution mailing list. Essentially, John McCall is opposed to typed errors because he believes most libraries will end up including a generic error case anyway, and that typed errors are unlikely to add much to the code apart from boilerplate (he used the term 'aspirational bluff'). Chris Lattner said he’s open to typed errors in Swift 3 if it can work with the resilience model.

TLS 1.2 not working in cURL

You must use an integer value for the CURLOPT_SSLVERSION value, not a string as listed above

Try this:

curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 6); //Integer NOT string TLS v1.2

http://php.net/manual/en/function.curl-setopt.php

value should be an integer for the following values of the option parameter: CURLOPT_SSLVERSION

One of

CURL_SSLVERSION_DEFAULT (0)
CURL_SSLVERSION_TLSv1 (1)
CURL_SSLVERSION_SSLv2 (2)
CURL_SSLVERSION_SSLv3 (3)
CURL_SSLVERSION_TLSv1_0 (4)
CURL_SSLVERSION_TLSv1_1 (5)
CURL_SSLVERSION_TLSv1_2 (6).

Android image caching

This is a good catch by Joe. The code example above has two problems - one - the response object isn't an instance of Bitmap (when my URL references a jpg, like http:\website.com\image.jpg, its a

org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl$LimitedInputStream).

Second, as Joe points out, no caching occurs without a response cache being configured. Android developers are left to roll their own cache. Here's an example for doing so, but it only caches in memory, which really isn't the full solution.

http://codebycoffee.com/2010/06/29/using-responsecache-in-an-android-app/

The URLConnection caching API is described here:

http://download.oracle.com/javase/6/docs/technotes/guides/net/http-cache.html

I still think this is an OK solution to go this route - but you still have to write a cache. Sounds like fun, but I'd rather write features.

Node.js version on the command line? (not the REPL)

If you are windows user and using command line to check following versions then:

  1. Check node version

    node -v

  2. Check npm version

    npm -v

Hello World in Python

Unfortunately the xkcd comic isn't completely up to date anymore.

https://imgs.xkcd.com/comics/python.png

Since Python 3.0 you have to write:

print("Hello world!")

And someone still has to write that antigravity library :(

How to import load a .sql or .csv file into SQLite?

Import your csv or sql to sqlite with phpLiteAdmin, it is excellent.

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

Synchronous XMLHttpRequest warning and <script>

UPDATE: This has been fixed in jQuery 3.x. If you have no possibility to upgrade to any version above 3.0, you could use following snippet BUT be aware that now you will lose sync behaviour of script loading in the targeted content.

You could fix it, setting explicitly async option of xhr request to true:

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

Can we call the function written in one JavaScript in another JS file?

As long as both are referenced by the web page, yes.

You simply call the functions as if they are in the same JS file.

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

The most compact version:

<input type="submit" onclick="return confirm('Are you sure?')" />

The key thing to note is the return

-

Because there are many ways to skin a cat, here is another alternate method:

HTML:

<input type="submit" onclick="clicked(event)" />

Javascript:

<script>
function clicked(e)
{
    if(!confirm('Are you sure?')) {
        e.preventDefault();
    }
}
</script>

Connect over ssh using a .pem file

To connect from Terminal to AWS AMI:

chmod 400 mykey.pem

ssh -i mykey.pem [email protected]

What do the terms "CPU bound" and "I/O bound" mean?

CPU Bound means the rate at which process progresses is limited by the speed of the CPU. A task that performs calculations on a small set of numbers, for example multiplying small matrices, is likely to be CPU bound.

I/O Bound means the rate at which a process progresses is limited by the speed of the I/O subsystem. A task that processes data from disk, for example, counting the number of lines in a file is likely to be I/O bound.

Memory bound means the rate at which a process progresses is limited by the amount memory available and the speed of that memory access. A task that processes large amounts of in memory data, for example multiplying large matrices, is likely to be Memory Bound.

Cache bound means the rate at which a process progress is limited by the amount and speed of the cache available. A task that simply processes more data than fits in the cache will be cache bound.

I/O Bound would be slower than Memory Bound would be slower than Cache Bound would be slower than CPU Bound.

The solution to being I/O bound isn't necessarily to get more Memory. In some situations, the access algorithm could be designed around the I/O, Memory or Cache limitations. See Cache Oblivious Algorithms.

Adding a favicon to a static HTML page

Convert your image file to Base64 string with a tool like this and then replace the YourBase64StringHere placeholder in the below snippet with your string and put the line in your HTML head section:

<link href="data:image/x-icon;base64,YourBase64StringHere" rel="icon" type="image/x-icon" />

This will work 100% in browsers.

What is the relative performance difference of if/else versus switch statement in Java?

According to Cliff Click in his 2009 Java One talk A Crash Course in Modern Hardware:

Today, performance is dominated by patterns of memory access. Cache misses dominate – memory is the new disk. [Slide 65]

You can get his full slides here.

Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.

So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP ? XML ? DOM ? SQL ? …" which "passes all the data through the cache".

How do I run a terminal inside of Vim?

Split the screen and run command term ++curwin to run the terminal inside the Vim buffer. Following command does both and worked for me:

:bo 10sp | term ++curwin

Waiting for background processes to finish before exiting script

Even if you do not have the pid, you can trigger 'wait;' after triggering all background processes. For. eg. in commandfile.sh-

bteq < input_file1.sql > output_file1.sql &
bteq < input_file2.sql > output_file2.sql &
bteq < input_file3.sql > output_file3.sql &
wait

Then when this is triggered, as -

subprocess.call(['sh', 'commandfile.sh'])
print('all background processes done.')

This will be printed only after all the background processes are done.

Get Locale Short Date Format using javascript

If your question about <input type="date"> field, here is script for getting filed value="" attribute:

(new Date()).toISOString().split('T')[0]

You can use the Intl object (ecma-402) to get data-date-pattern="":

(new Intl.DateTimeFormat()).resolved.pattern // "M/d/y" for "en-US" in Google Chrome

And finnaly, to format date in current l10n, data-date="":

(new Intl.DateTimeFormat()).format(new Date());

Polyfill: https://github.com/andyearnshaw/Intl.js/issues/129

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Checkbox value true/false

Checkboxes can be really weird in JS. You're best off checking for the presence of the checked attribute. (I've had older jQuery versions return true even if checked is set to 'false'.) Once you've determined that something is checked then you can get the value from the value attribute.

ERROR: Google Maps API error: MissingKeyMapError

The same issue i was facing couple of months back and that is because end of free google map usage effective from i think June 11, 2018. Google does not provide free google maps now. You need to have a valid API key and valid billing used, which may give you 200$ of free usage.

Refer link for more details: Google map pricing

Follow the process here to get your api key.

If you are upto using only maps with specific user, you can try other map tools.

Count number of occurrences by month

Recommend you use FREQUENCY rather than using COUNTIF.

In your front sheet; enter 01/04/2014 into E5, 01/05/2014 into E6 etc.

Select the range of adjacent cells you want to populate. Enter:

=FREQUENCY(2013!!$A$2:$A$50,'2013 Metrics'!E5:EN)

(where N is the final row reference in your range)

Hit Ctrl + Shift + Enter

Check if a String contains a special character

This worked for me:

String s = "string";
if (Pattern.matches("[a-zA-Z]+", s)) {
 System.out.println("clear");
} else {
 System.out.println("buzz");
}

display html page with node.js

If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.

at the command line

:\> cd <path you wish your server to reside>
:\> npm install connect

Then in a file (I named) Server.js

var connect = require('connect'),
   http = require('http');
connect()
   .use(connect.static('<pathyouwishtoserve>'))
   .use(connect.directory('<pathyouwishtoserve>'))
   .listen(8080);

Finally

:\>node Server.js

Caveats:

If you don't want to display the directory contents, exclude the .use(connect.directory line.

So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.

If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.

Update 1/28/2014:

I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.

End Update

Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.

Commands I used (for better or worse):

Create a new file called node

:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$@"

sudo chmod -x /usr/local/bin/node

That ought to make

node Server.js 

work just fine

How to combine two or more querysets in a Django view?

In case you want to chain a lot of querysets, try this:

from itertools import chain
result = list(chain(*docs))

where: docs is a list of querysets

.NET DateTime to SqlDateTime Conversion

Also please remember resolutions [quantum of time] are different.

http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx

SQL one is 3.33 ms and .net one is 100 ns.

How to increase Java heap space for a tomcat app

Easiest way of doing is: (In Linux/Ububuntu e.t.c)

Go to tomcat bin directory:

cd /opt/tomcat8.5/bin

create new file under bin directory "setenv.sh" and save below mention entries in it.

export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx2048m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxPermSize=256m"

and issue command:

./catalina.sh run

In your catalina log file you can see entry like this:

INFO [main] VersionLoggerListener.log Command line argument: -Xms512m
INFO [main] VersionLoggerListener.log Command line argument: -Xmx2048m
INFO [main] VersionLoggerListener.log Command line argument: -XX:MaxPermSize=256m

Which confirms that above changes took place.

Also, the value of "Xms512m" and "-Xmx2048m" can be modified accordingly in the setenv.sh file.

Startup of tomcat could be done in two steps as well. cd /opt/tomcat8.5/bin

Step #1
run ./setenv.sh 
Step #2
./startup.sh

If you're using systemd edit:

/usr/lib/systemd/system/tomcat8.service

and set

Environment=CATALINA_OPTS="-Xms512M -Xmx2048M -XX:MaxPermSize=256m"

Convert a string into an int

How about

[@"7" intValue];

Additionally if you want an NSNumber you could do

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];

How to move Docker containers between different hosts?

From Docker documentation:

docker export does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container, docker export will export the contents of the underlying directory, not the contents of the volume. Refer to Backup, restore, or migrate data volumes in the user guide for examples on exporting data in a volume.

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

When should I use mmap for file access?

mmap is great if you have multiple processes accessing data in a read only fashion from the same file, which is common in the kind of server systems I write. mmap allows all those processes to share the same physical memory pages, saving a lot of memory.

mmap also allows the operating system to optimize paging operations. For example, consider two programs; program A which reads in a 1MB file into a buffer creating with malloc, and program B which mmaps the 1MB file into memory. If the operating system has to swap part of A's memory out, it must write the contents of the buffer to swap before it can reuse the memory. In B's case any unmodified mmap'd pages can be reused immediately because the OS knows how to restore them from the existing file they were mmap'd from. (The OS can detect which pages are unmodified by initially marking writable mmap'd pages as read only and catching seg faults, similar to Copy on Write strategy).

mmap is also useful for inter process communication. You can mmap a file as read / write in the processes that need to communicate and then use synchronization primitives in the mmap'd region (this is what the MAP_HASSEMAPHORE flag is for).

One place mmap can be awkward is if you need to work with very large files on a 32 bit machine. This is because mmap has to find a contiguous block of addresses in your process's address space that is large enough to fit the entire range of the file being mapped. This can become a problem if your address space becomes fragmented, where you might have 2 GB of address space free, but no individual range of it can fit a 1 GB file mapping. In this case you may have to map the file in smaller chunks than you would like to make it fit.

Another potential awkwardness with mmap as a replacement for read / write is that you have to start your mapping on offsets of the page size. If you just want to get some data at offset X you will need to fixup that offset so it's compatible with mmap.

And finally, read / write are the only way you can work with some types of files. mmap can't be used on things like pipes and ttys.

CSS text-decoration underline color

As far as I know it's not possible... but you can try something like this:

_x000D_
_x000D_
.underline _x000D_
{_x000D_
    color: blue;_x000D_
    border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <span class="underline">hello world</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

What does it mean when Statement.executeUpdate() returns -1?

I haven't seen this anywhere, either, but my instinct would be that this means that the IF prevented the whole statement from executing.

Try to run the statement with a database where the IF passes.

Also check if there are any triggers involved which might change the result.

[EDIT] When the standard says that this function should never return -1, that doesn't enforce this. Java doesn't have pre and post conditions. A JDBC driver could return a random number and there was no way to stop it.

If it's important to know why this happens, run the statement against different database until you have tried all execution paths (i.e. one where the IF returns false and one where it returns true).

If it's not that important, mark it off as a "clever trick" by a Microsoft engineer and remember how much you liked it when you feel like being clever yourself next time.

C++ for each, pulling from vector elements

The for each syntax is supported as an extension to native c++ in Visual Studio.

The example provided in msdn

#include <vector>
#include <iostream>

using namespace std;

int main() 
{
  int total = 0;

  vector<int> v(6);
  v[0] = 10; v[1] = 20; v[2] = 30;
  v[3] = 40; v[4] = 50; v[5] = 60;

  for each(int i in v) {
    total += i;
  }

  cout << total << endl;
}

(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each.

The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.

How to clear the canvas for redrawing

If you use clearRect only, if you have it in a form to submit your drawing, you'll get a submit instead the clearing, or maybe it can be cleared first and then upload a void drawing, so you'll need to add a preventDefault at the beggining of the function:

   function clearCanvas(canvas,ctx) {
        event.preventDefault();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }


<input type="button" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">

Hope it helps someone.

Query error with ambiguous column name in SQL

it's because some of the fields (specifically InvoiceID on the Invoices table and on the InvoiceLineItems) are present on both table. The way to answer of question is to add an ALIAS on it.

SELECT 
    a.VendorName,  Invoices.InvoiceID, .. -- or use full tableName
FROM Vendors a   -- This is an `ALIAS` of table Vendors
JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
WHERE  
    Invoices.InvoiceID IN
        (SELECT InvoiceSequence 
         FROM InvoiceLineItems
         WHERE InvoiceSequence > 1)
ORDER BY 
    VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount

how to open an URL in Swift3

All you need is:

guard let url = URL(string: "http://www.google.com") else {
  return //be safe
}

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

How to call JavaScript function instead of href in HTML

<a href="#" onclick="javascript:ShowOld(2367,146986,2)">

How to provide animation when calling another activity in Android?

Since API 16 you can supply an activity options bundle when calling Context.startActivity(Intent, Bundle) or related methods. It is created via the ActivityOptions builder:

Intent myIntent = new Intent(context, MyActivity.class);
ActivityOptions options = 
   ActivityOptions.makeCustomAnimation(context, R.anim.fade_in, R.anim.fade_out);
context.startActivity(myIntent, options.toBundle());

Don't forget to check out the other methods of the ActivityOptions builder and the ActivityOptionsCompat if you are using the Support Library.



API 5+:

For apps targeting API level 5+ there is the Activities overridePendingTransition method. It takes two resource IDs for the incoming and outgoing animations. An id of 0 will disable the animations. Call this immediately after the startActivity call.

i.e.:

startActivity(new Intent(this, MyActivity.class));
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

API 3+:

You can prevent the default animation (Slide in from the right) with the Intent.FLAG_ACTIVITY_NO_ANIMATION flag in your intent.

i.e.:

Intent myIntent = new Intent(context, MyActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(myIntent);

then in your Activity you simply have to specify your own animation.

This also works for the 1.5 API (Level 3).

Is Python interpreted, or compiled, or both?

If ( You know Java ) {

Python code is converted into bytecode like java does.
That bytecode is executed again everytime you try to access it.

} else {

Python code is initially traslated into something called bytecode
that is quite close to machine language but not actual machine code
so each time we access or run it that bytecode is executed again

}

Cannot invoke an expression whose type lacks a call signature

TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple and Pear don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean member. Because of structural typing, you don' need to inherit Apple and Pear from such an interface.

There are different ways to assign such a compatible type:

Assign type during variable declaration

This statement is implicitly typed to Apple[] | Pear[]:

const fruits = fruitBasket[key];

You can simply use a compatible type explicitly in in your variable declaration:

const fruits: { isDecayed: boolean }[] = fruitBasket[key];

For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple and Pear interfaces don't need to be changed):

type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];

Cast to compatible type for the operation

The problem with the given solution is that it changes the type of the fruits variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits:

const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

Or with the reusable Fruit type:

type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

The advantage of this solution is that both, fruits and freshFruits will be of type Apple[] | Pear[].

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Chrome needs a user interaction for the video to be autoplayed or played via js (video.play()). But the interaction can be of any kind, in any moment. If you just click random on the page, the video will autoplay. I resolved then, adding a button (only on chrome browsers) that says "enable video autoplay". The button does nothing, but just clicking it, is the required user interaction for any further video.

Looking for a 'cmake clean' command to clear up CMake output

Maybe it's a little outdated, but since this is the first hit when you google cmake clean, I will add this:

Since you can start a build in the build dir with a specified target with

cmake --build . --target xyz

you can of course run

cmake --build . --target clean

to run the clean target in the generated build files.

MySQL timestamp select date range

SELECT * FROM table WHERE col >= '2010-10-01' AND col <= '2010-10-31'

What is the fastest way to compare two sets in Java?

firstSet.equals(secondSet)

It really depends on what you want to do in the comparison logic... ie what happens if you find an element in one set not in the other? Your method has a void return type so I assume you'll do the necessary work in this method.

More fine-grained control if you need it:

if (!firstSet.containsAll(secondSet)) {
  // do something if needs be
}
if (!secondSet.containsAll(firstSet)) {
  // do something if needs be
}

If you need to get the elements that are in one set and not the other.
EDIT: set.removeAll(otherSet) returns a boolean, not a set. To use removeAll(), you'll have to copy the set then use it.

Set one = new HashSet<>(firstSet);
Set two = new HashSet<>(secondSet);
one.removeAll(secondSet);
two.removeAll(firstSet);

If the contents of one and two are both empty, then you know that the two sets were equal. If not, then you've got the elements that made the sets unequal.

You mentioned that the number of records might be high. If the underlying implementation is a HashSet then the fetching of each record is done in O(1) time, so you can't really get much better than that. TreeSet is O(log n).

How do I format my oracle queries so the columns don't wrap?

set linesize 3000

set wrap off

set termout off

set pagesize 0 embedded on

set trimspool on

Try with all above values.

How to copy files from host to Docker container?

In a docker environment, all containers are found in the directory:

/var/lib/docker/aufs/required-docker-id/

To copy the source directory/file to any part of the container, type the given command:

sudo cp -r mydir/ /var/lib/docker/aufs/mnt/required-docker-id/mnt/

Adding local .aar files to Gradle build using "flatDirs" is not working

This solution is working with Android Studio 4.0.1.

Apart from creating a new module as suggested in above solution, you can try this solution.

If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.

In your root project build.gradle

add

repositories {
flatDir {
    dirs 'libs'
}}

Then in the module where you want to add the .aar file locally. simply add below lines of code.

dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')

}

Happy Coding :)

Create comma separated strings C#?

If you put all your values in an array, at least you can use string.Join.

string[] myValues = new string[] { ... };
string csvString = string.Join(",", myValues);

You can also use the overload of string.Join that takes params string as the second parameter like this:

string csvString = string.Join(",", value1, value2, value3, ...);

How do I copy a string to the clipboard?

The simplest way is with pyperclip. Works in python 2 and 3.

To install this library, use:

pip install pyperclip

Example usage:

import pyperclip

pyperclip.copy("your string")

If you want to get the contents of the clipboard:

clipboard_content = pyperclip.paste()

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

Mac & Big Sur. Python 3.8.6 w/vs code. While it should have been included in diagrams package, I had to manually install graphviz.

(mymltools) ?  infrastructure git:(master) pip list
Package    Version
---------- -------
diagrams   0.18.0
graphviz   0.13.2
Jinja2     2.11.2
MarkupSafe 1.1.1
pip        20.3.2
setuptools 51.0.0
wheel      0.36.2

Running diagrams failed. Then manually ran

pipenv install graphviz

Works like a charm.

ASP.NET MVC Global Variables

The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:

public static class GlobalVars
{
    private const string GlobalKey = "AllMyVars";

    static GlobalVars()
    {
        Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;

        if (table == null)
        {
            table = new Hashtable();
            HttpContext.Current.Application[GlobalKey] = table;
        }
    }

    public static Hashtable Vars
    {
        get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
    }

    public static IEnumerable<SomeClass> SomeCollection
    {
        get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
        set { WriteVar("SomeCollection", value); }
    }

    internal static DateTime SomeDate
    {
        get { return (DateTime)GetVar("SomeDate"); }
        set { WriteVar("SomeDate", value); }
    }

    private static object GetVar(string varName)
    {
        if (Vars.ContainsKey(varName))
        {
            return Vars[varName];
        }

        return null;
    }

    private static void WriteVar(string varName, object value)
    {
        if (value == null)
        {
            if (Vars.ContainsKey(varName))
            {
                Vars.Remove(varName);
            }
            return;
        }

        if (Vars[varName] == null)
        {
            Vars.Add(varName, value);
        }
        else
        {
            Vars[varName] = value;
        }
    }
}

Loop through files in a folder in matlab

Looping through all the files in the folder is relatively easy:

files = dir('*.csv');
for file = files'
    csv = load(file.name);
    % Do some stuff
end

Reverse HashMap keys and values in Java

private <A, B> Map<B, A> invertMap(Map<A, B> map) {
    Map<B, A> reverseMap = new HashMap<>();
    for (Map.Entry<A, B> entry : map.entrySet()) {
        reverseMap.put(entry.getValue(), entry.getKey());
    }
    return reverseMap;
}

It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

Run .php file in Windows Command Prompt (cmd)

It seems your question is very much older. But I just saw it. I searched(not in google) and found My Answer.

So I am writing its solution so that others may get help from it.

Here is my solution.

Unlike the other answers, you don't need to setup environments.

all you need is just to write php index.php if index.php is your file name.

then you will see that, the file compiled and showing it's desired output.

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

I think you should understand what delayed expansion is. The existing answers don't explain it (sufficiently) IMHO.

Typing SET /? explains the thing reasonably well:

Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed. The following example demonstrates the problem with immediate variable expansion:

set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "%VAR%" == "after" @echo If you see this, it worked
)

would never display the message, since the %VAR% in BOTH IF statements is substituted when the first IF statement is read, since it logically includes the body of the IF, which is a compound statement. So the IF inside the compound statement is really comparing "before" with "after" which will never be equal. Similarly, the following example will not work as expected:

set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%

in that it will NOT build up a list of files in the current directory, but instead will just set the LIST variable to the last file found. Again, this is because the %LIST% is expanded just once when the FOR statement is read, and at that time the LIST variable is empty. So the actual FOR loop we are executing is:

for %i in (*) do set LIST= %i

which just keeps setting LIST to the last file found.

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time. If delayed variable expansion is enabled, the above examples could be written as follows to work as intended:

set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "!VAR!" == "after" @echo If you see this, it worked
)

set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%

Another example is this batch file:

@echo off
setlocal enabledelayedexpansion
set b=z1
for %%a in (x1 y1) do (
 set b=%%a
 echo !b:1=2!
)

This prints x2 and y2: every 1 gets replaced by a 2.

Without setlocal enabledelayedexpansion, exclamation marks are just that, so it will echo !b:1=2! twice.

Because normal environment variables are expanded when a (block) statement is read, expanding %b:1=2% uses the value b has before the loop: z2 (but y2 when not set).

Remove an element from a Bash array

This answer is specific to the case of deleting multiple values from large arrays, where performance is important.

The most voted solutions are (1) pattern substitution on an array, or (2) iterating over the array elements. The first is fast, but can only deal with elements that have distinct prefix, the second has O(n*k), n=array size, k=elements to remove. Associative array are relative new feature, and might not have been common when the question was originally posted.

For the exact match case, with large n and k, possible to improve performance from O(nk) to O(n+klog(k)). In practice, O(n) assuming k much lower than n. Most of the speed up is based on using associative array to identify items to be removed.

Performance (n-array size, k-values to delete). Performance measure seconds of user time

   N     K     New(seconds) Current(seconds)  Speedup
 1000   10     0.005        0.033             6X
10000   10     0.070        0.348             5X
10000   20     0.070        0.656             9X
10000    1     0.043        0.050             -7%

As expected, the current solution is linear to N*K, and the fast solution is practically linear to K, with much lower constant. The fast solution is slightly slower vs the current solution when k=1, due to additional setup.

The 'Fast' solution: array=list of input, delete=list of values to remove.

        declare -A delk
        for del in "${delete[@]}" ; do delk[$del]=1 ; done
                # Tag items to remove, based on
        for k in "${!array[@]}" ; do
                [ "${delk[${array[$k]}]-}" ] && unset 'array[k]'
        done
                # Compaction
        array=("${array[@]}")

Benchmarked against current solution, from the most-voted answer.

    for target in "${delete[@]}"; do
        for i in "${!array[@]}"; do
            if [[ ${array[i]} = $target ]]; then
                unset 'array[i]'
            fi
        done
    done
    array=("${array[@]}")

Play a Sound with Python

After the play() command add a delay of say 10 secs or so, it'll work

import pygame

import time

pygame.init()

pygame.mixer.music.load("test.wav")

pygame.mixer.music.play()

time.sleep(10)

This also plays .mp3 files.

How to open a new window on form submit

In a web-based database application that uses a pop-up window to display print-outs of database data, this worked well enough for our needs (tested in Chrome 48):

<form method="post" 
      target="print_popup" 
      action="/myFormProcessorInNewWindow.aspx"
      onsubmit="window.open('about:blank','print_popup','width=1000,height=800');">

The trick is to match the target attribute on the <form> tag with the second argument in the window.open call in the onsubmit handler.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

You might also consider removing the need for duplicated parameter names in your Sql by changing your Sql to

table.Variable2 LIKE '%' || :VarB || '%'

and then getting your client to provide '%' for any value of VarB instead of null. In some ways I think this is more natural.

You could also change the Sql to

table.Variable2 LIKE '%' || IfNull(:VarB, '%') || '%'

Call a stored procedure with parameter in c#

It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.

Also, use a using for all disposable objects, so that you are sure that they are disposed properly:

private void button1_Click(object sender, EventArgs e) {
  using (SqlConnection con = new SqlConnection(dc.Con)) {
    using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
      cmd.CommandType = CommandType.StoredProcedure;

      cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
      cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

      con.Open();
      cmd.ExecuteNonQuery();
    }
  }
}

Pipenv: Command Not Found

I don't know what happened, but the following did the work (under mac os catalina)

$ brew install pipenv

$ brew update pipenv

after doing this i am able to use

$ pipenv install [package_name]

How to add an element at the end of an array?

As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.

For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.

Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.

Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).

python, sort descending dataframe with pandas

For pandas 0.17 and above, use this :

test = df.sort_values('one', ascending=False)

Since 'one' is a series in the pandas data frame, hence pandas will not accept the arguments in the form of a list.

Exporting data In SQL Server as INSERT INTO

You could also check out the "Data Scripter Add-In" for SQL Server Management Studio 2008 from:

http://www.mssql-vehicle-data.com/SSMS


Their features list:

  • It was developed on SSMS 2008 and is not supported on the 2005 version at this time (soon!)

  • Export data quickly to T-SQL for MSSQL and MySQL syntax

  • CSV, TXT, XML are also supported! Harness the full potential, power, and speed that SQL has to offer.

  • Don't wait for Access or Excel to do scripting work for you that could take several minutes to do -- let SQL Server do it for you and take all the guess work out of exporting your data!

  • Customize your data output for rapid backups, DDL manipulation, and more...

  • Change table names and database schemas to your needs, quickly and efficiently

  • Export column names or simply generate data without the names.

  • You can chose individual columns to script.

  • You can chose sub-sets of data (WHERE clause).

  • You can chose ordering of data (ORDER BY clause).

  • Great backup utility for those grungy database debugging operations that require data manipulation. Don't lose data while experimenting. Manipulate data on the fly!

Angular2, what is the correct way to disable an anchor element?

My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/

The remote server returned an error: (407) Proxy Authentication Required

Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.

If you're using httpClient then consider this.

HttpClientHandler handler = new HttpClientHandler();

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;

var client = new HttpClient(handler);
// your next steps...

And if you're using HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;

Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b

Associating existing Eclipse project with existing SVN repository

In case of SVN servers you have to creating a central repository with all projects. The contents of the repository can be uploaded with the Team/Share command; in case of the Subversive client it automatically runs a commit after the import, so you can upload your files.

This step cannot be circumvented in any way using a centralized version management system such as SVN.

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

How to open maximized window with Javascript?

var params = [
    'height='+screen.height,
    'width='+screen.width,
    'fullscreen=yes' // only works in IE, but here for completeness
].join(',');
     // and any other options from
     // https://developer.mozilla.org/en/DOM/window.open

var popup = window.open('http://www.google.com', 'popup_window', params); 
popup.moveTo(0,0);

Please refrain from opening the popup unless the user really wants it, otherwise they will curse you and blacklist your site. ;-)

edit: Oops, as Joren Van Severen points out in a comment, this may not take into account taskbars and window decorations (in a possibly browser-dependent way). Be aware. It seems that ignoring height and width (only param is fullscreen=yes) seems to work on Chrome and perhaps Firefox too; the original 'fullscreen' functionality has been disabled in Firefox for being obnoxious, but has been replaced with maximization. This directly contradicts information on the same page of https://developer.mozilla.org/en/DOM/window.open which says that window-maximizing is impossible. This 'feature' may or may not be supported depending on the browser.

How do I vertically align something inside a span tag?

Use line-height:50px; instead of height. That should do the trick ;)

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Another item check:

Make sure you component is added to the declarations array of @NgModule in app.module.ts

@NgModule({
declarations: [
    YourComponent,
],

When running the ng generate component command, it does not automatilly add it to app.module.

php convert datetime to UTC

alternatively you can try this:

<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>

this will output :

2017-10-25 17:13:20 Asia/Singapore

you can use this inside the value attribute of a text input box if you only want to display a read-only date.

remove the 'e' if you do not wish to show your region/country.

Fixing slow initial load for IIS

A good option to ping the site on a schedule is to use Microsoft Flow, which is free for up to 750 "runs" per month. It is very easy to create a Flow that hits your site every hour to keep it warm. You can even work around their limit of 750 by creating a single flow with delays separating multiple hits of your site.

https://flow.microsoft.com

Remove trailing zeros

Trying to do more friendly solution of DecimalToString (https://stackoverflow.com/a/34486763/3852139):

private static decimal Trim(this decimal value)
{
    var s = value.ToString(CultureInfo.InvariantCulture);
    return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
        ? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
        : value;
}

private static decimal? Trim(this decimal? value)
{
    return value.HasValue ? (decimal?) value.Value.Trim() : null;
}

private static void Main(string[] args)
{
    Console.WriteLine("=>{0}", 1.0000m.Trim());
    Console.WriteLine("=>{0}", 1.000000023000m.Trim());
    Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
    Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}

Output:

=>1
=>1.000000023
=>1.000000023
=>

Is it possible to compile a program written in Python?

python compile on the fly when you run it.

Run a .py file by(linux): python abc.py

How to convert int to NSString?

If this string is for presentation to the end user, you should use NSNumberFormatter. This will add thousands separators, and will honor the localization settings for the user:

NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];

In the US, for example, that would create a string 10,000, but in Germany, that would be 10.000.

Types in Objective-C on iOS

This is a good overview:

http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html

or run this code:

32 bit process:

  NSLog(@"Primitive sizes:");
  NSLog(@"The size of a char is: %d.", sizeof(char));
  NSLog(@"The size of short is: %d.", sizeof(short));
  NSLog(@"The size of int is: %d.", sizeof(int));
  NSLog(@"The size of long is: %d.", sizeof(long));
  NSLog(@"The size of long long is: %d.", sizeof(long long));
  NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
  NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
  NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
  NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
  NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
  NSLog(@"The size of a float is: %d.", sizeof(float));
  NSLog(@"The size of a double is %d.", sizeof(double));

  NSLog(@"Ranges:");
  NSLog(@"CHAR_MIN:   %c",   CHAR_MIN);
  NSLog(@"CHAR_MAX:   %c",   CHAR_MAX);
  NSLog(@"SHRT_MIN:   %hi",  SHRT_MIN);    // signed short int
  NSLog(@"SHRT_MAX:   %hi",  SHRT_MAX);
  NSLog(@"INT_MIN:    %i",   INT_MIN);
  NSLog(@"INT_MAX:    %i",   INT_MAX);
  NSLog(@"LONG_MIN:   %li",  LONG_MIN);    // signed long int
  NSLog(@"LONG_MAX:   %li",  LONG_MAX);
  NSLog(@"ULONG_MAX:  %lu",  ULONG_MAX);   // unsigned long int
  NSLog(@"LLONG_MIN:  %lli", LLONG_MIN);   // signed long long int
  NSLog(@"LLONG_MAX:  %lli", LLONG_MAX);
  NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX);  // unsigned long long int

When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:

Primitive sizes:
The size of a char is: 1.                
The size of short is: 2.                 
The size of int is: 4.                   
The size of long is: 4.                  
The size of long long is: 8.             
The size of a unsigned char is: 1.       
The size of unsigned short is: 2.        
The size of unsigned int is: 4.          
The size of unsigned long is: 4.         
The size of unsigned long long is: 8.    
The size of a float is: 4.               
The size of a double is 8.               
Ranges:                                  
CHAR_MIN:   -128                         
CHAR_MAX:   127                          
SHRT_MIN:   -32768                       
SHRT_MAX:   32767                        
INT_MIN:    -2147483648                  
INT_MAX:    2147483647                   
LONG_MIN:   -2147483648                  
LONG_MAX:   2147483647                   
ULONG_MAX:  4294967295                   
LLONG_MIN:  -9223372036854775808         
LLONG_MAX:  9223372036854775807          
ULLONG_MAX: 18446744073709551615 

64 bit process:

The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

Abstract methods in Python

You can't, with language primitives. As has been called out, the abc package provides this functionality in Python 2.6 and later, but there are no options for Python 2.5 and earlier. The abc package is not a new feature of Python; instead, it adds functionality by adding explicit "does this class say it does this?" checks, with manually-implemented consistency checks to cause an error during initialization if such declarations are made falsely.

Python is a militantly dynamically-typed language. It does not specify language primitives to allow you to prevent a program from compiling because an object does not match type requirements; this can only be discovered at run time. If you require that a subclass implement a method, document that, and then just call the method in the blind hope that it will be there.

If it's there, fantastic, it simply works; this is called duck typing, and your object has quacked enough like a duck to satisfy the interface. This works just fine even if self is the object you're calling such a method on, for the purposes of mandatory overrides due to base methods that need specific implementations of features (generic functions), because self is a convention, not anything actually special.

The exception is in __init__, because when your initializer is being called, the derived type's initializer hasn't, so it hasn't had the opportunity to staple its own methods onto the object yet.

If the method was't implemented, you'll get an AttributeError (if it's not there at all) or a TypeError (if something by that name is there but it's not a function or it didn't have that signature). It's up to you how you handle that- either call it programmer error and let it crash the program (and it "should" be obvious to a python developer what causes that kind of error there- an unmet duck interface), or catch and handle those exceptions when you discover that your object didn't support what you wish it did. Catching AttributeError and TypeError is important in a lot of situations, actually.

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

Make the first character Uppercase in CSS

There's a property for that:

a.m_title {
    text-transform: capitalize;
}

If your links can contain multiple words and you only want the first letter of the first word to be uppercase, use :first-letter with a different transform instead (although it doesn't really matter). Note that in order for :first-letter to work your a elements need to be block containers (which can be display: block, display: inline-block, or any of a variety of other combinations of one or more properties):

a.m_title {
    display: block;
}

a.m_title:first-letter {
    text-transform: uppercase;
}

$.focus() not working

You can try this id is tries

window.location.hash = '#tries';

Making TextView scrollable on Android

Make your textview just adding this

TextView textview= (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(new ScrollingMovementMethod());

How do I tell what type of value is in a Perl variable?

At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref or reftype is a bad idea. I don't recall who put the idea forward, or the link. Sorry.

The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie a filehandle so that it acts like a hash, the testing with reftype will tell you that you have a filehanle. It won't tell you that you need to use it like a hash.

So, the argument went, it is better to use duck typing to find out what a variable is.

Instead of:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;
    if( $type eq 'HASH' ) {
        $result = $var->{foo};
    }
    elsif( $type eq 'ARRAY' ) {
        $result = $var->[3];
    }
    else {
        $result = 'foo';
    }

    return $result;
}

You should do something like this:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;

    eval {
        $result = $var->{foo};
        1; # guarantee a true result if code works.
    }
    or eval { 
        $result = $var->[3];
        1;
    }
    or do {
        $result = 'foo';
    }

    return $result;
}

For the most part I don't actually do this, but in some cases I have. I'm still making my mind up as to when this approach is appropriate. I thought I'd throw the concept out for further discussion. I'd love to see comments.

Update

I realized I should put forward my thoughts on this approach.

This method has the advantage of handling anything you throw at it.

It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat 'WTF'.

I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.

I don't like this implementation.

word-wrap break-word does not work in this example

word-wrap property work's with display:inline-block:

display: inline-block;
word-wrap: break-word;
width: 100px;

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

How to run 'sudo' command in windows

There kind of is. I created Sudo for Windows back in 2007? 08? Here's the security paper I wrote about it - https://www.sans.org/reading-room/whitepapers/bestprac/sudo-windows-sudowin-1726. Pretty sure http://sudowin.sf.net still works too.

List all indexes on ElasticSearch server?

One of the best way to list indices + to display its status together with list : is by simply executing below query.

Note: preferably use Sense to get the proper output.

curl -XGET 'http://localhost:9200/_cat/shards'

The sample output is as below. The main advantage is, it basically shows index name and the shards it saved into, index size and shards ip etc

index1     0 p STARTED     173650  457.1mb 192.168.0.1 ip-192.168.0.1 
index1     0 r UNASSIGNED                                                 
index2     1 p STARTED     173435  456.6mb 192.168.0.1 ip-192.168.0.1 
index2     1 r UNASSIGNED                                                 
...
...
...