Programs & Examples On #Double pointer

The term "double pointer" is sometimes confusingly used to refer a data type which can point to another pointer. This name is confusing because it may mean a pointer to a `double` floating-point object. Please use [pointer-to-pointer] instead.

maven "cannot find symbol" message unhelpful

Even I am using Java 7, maven 2.2.1 and was getting the same error, I removed <scope>tests</scope> from my pom and used

mvn clean -DskipTests=true install to successfully build my projects, without upgrading my maven version.

Create timestamp variable in bash script

ISO 8601 format (2018-12-23T12:34:56) is more readable than UNIX timestamp. However on some OSs you cannot have : in the filenames. Therefore I recommend using something like this instead:

2018-12-23_12-34-56

You can use the following command to get the timestamp in this format:

TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`

This is the format I have seen many applications use. Another nice thing about this is that if your file names start with this, you can sort them alphabetically and they would be sorted by date.

How to monitor network calls made from iOS Simulator

Wireshark it

Select your interface

enter image description here

Add filter start the capture

enter image description here


Testing

Click on any action or button that would trigger a GET/POST/PUT/DELETE request

You will see it on listed in the wireshark

enter image description here

If you want to know more details about one specific packet, just select it and Follow > HTTP Stream.

enter image description here

hope this help others !!

How do I mock a class without an interface?

If you cannot change the class under test, then the only option I can suggest is using MS Fakes https://msdn.microsoft.com/en-us/library/hh549175.aspx. However, MS Fakes works only in a few editions of Visual Studio.

Is there an easy way to check the .NET Framework version?

        public static class DotNetHelper
{
    public static Version InstalledVersion
    {
        get
        {
            string framework = null;

            try
            {
                using (var ndpKey =
            Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
                {
                    if (ndpKey != null)
                    {
                        var releaseKey = ndpKey.GetValue("Release");
                        if (releaseKey != null)
                        {
                            framework = CheckFor45PlusVersion(Convert.ToInt32(releaseKey));
                        }
                        else
                        {
                            string[] versionNames = null;
                            using (var installedVersions =
                                Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP"))
                            {
                                if (installedVersions != null) versionNames = installedVersions.GetSubKeyNames();
                            }


                            try
                            {
                                if (versionNames != null && versionNames.Length > 0)
                                {
                                    framework = versionNames[versionNames.Length - 1].Remove(0, 1);
                                }
                            }
                            catch (FormatException)
                            {

                            }
                        }
                    }
                }
            }
            catch (SecurityException)
            {
            }

            return framework != null ? new Version(framework) : null;
        }
    }

    private static string CheckFor45PlusVersion(int releaseKey)
    {
        if (releaseKey >= 460798)
            return "4.7";
        if (releaseKey >= 394802)
            return "4.6.2";
        if (releaseKey >= 394254)
            return "4.6.1";
        if (releaseKey >= 393295)
            return "4.6";
        if (releaseKey >= 379893)
            return "4.5.2";
        if (releaseKey >= 378675)
            return "4.5.1";
        // This code should never execute. A non-null release key should mean
        // that 4.5 or later is installed.
        return releaseKey >= 378389 ? "4.5" : null;
    }
}

How can I include null values in a MIN or MAX?

Use IsNull

SELECT recordid, MIN(startdate), MAX(IsNull(enddate, Getdate()))
FROM tmp 
GROUP BY recordid

I've modified MIN in the second instruction to MAX

How to set time to a date object in java

I should like to contribute the modern answer. This involves using java.time, the modern Java date and time API, and not the old Date nor Calendar except where there’s no way to avoid it.

Your issue is very likely really a timezone issue. When it is Tue Aug 09 00:00:00 IST 2011, in time zones west of IST midnight has not yet been reached. It is still Aug 8. If for example your API for putting the date into Excel expects UTC, the date will be the day before the one you intended. I believe the real and good solution is to produce a date-time of 00:00 UTC (or whatever time zone or offset is expected and used at the other end).

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    ZonedDateTime utcDateDime = yourDate.atStartOfDay(ZoneOffset.UTC);
    System.out.println(utcDateDime);

This prints

2018-02-27T00:00Z

Z means UTC (think of it as offset zero from UTC or Zulu time zone). Better still, of course, if you could pass the LocalDate from the first code line to Excel. It doesn’t include time-of-day, so there is no confusion possible. On the other hand, if you need an old-fashioned Date object for that, convert just before handing the Date on:

    Date oldfashionedDate = Date.from(utcDateDime.toInstant());
    System.out.println(oldfashionedDate);

On my computer this prints

Tue Feb 27 01:00:00 CET 2018

Don’t be fooled, it is correct. My time zone (Central European Time) is at offset +01:00 from UTC in February (standard time), so 01:00:00 here is equal to 00:00:00 UTC. It’s just Date.toString() grabbing the JVMs time zone and using it for producing the string.

How can I set it to something like 5:30 pm?

To answer your direct question directly, if you have a ZonedDateTime, OffsetDateTime or LocalDateTime, in all of these cases the following will accomplish what you asked for:

    yourDateTime = yourDateTime.with(LocalTime.of(17, 30));

If yourDateTime was a LocalDateTime of 2018-02-27T00:00, it will now be 2018-02-27T17:30. Similarly for the other types, only they include offset and time zone too as appropriate.

If you only had a date, as in the first snippet above, you can also add time-of-day information to it:

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    LocalDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30));

For most purposes you should prefer to add the time-of-day in a specific time zone, though, for example

    ZonedDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30))
            .atZone(ZoneId.of("Asia/Kolkata"));

This yields 2018-02-27T17:30+05:30[Asia/Kolkata].

Date and Calendar vs java.time

The Date class that you use as well as Calendar and SimpleDateFormat used in the other answers are long outdated, and SimpleDateFormat in particular has proven troublesome. In all cases the modern Java date and time API is so much nicer to work with. Which is why I wanted to provide this answer to an old question that is still being visited.

Link: Oracle Tutorial Date Time, explaining how to use java.time.

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

Something like that happened to me when I made copies of structures to temporary tables, so I removed the not null.

DECLARE
   CURSOR cur_temp_not_null IS
        SELECT table_name, constraint_name  FROM all_constraints WHERE table_name LIKE 'TEMP_%' AND  owner='myUSUARIO';

   V_sql VARCHAR2(200); 

BEGIN
  FOR c_not_null IN cur_temp_not_null
   LOOP
     v_sql :='ALTER TABLE ' || c_not_null.table_name || ' DROP CONSTRAINT '|| c_not_null.constraint_name;
     EXECUTE IMMEDIATE  v_sql;     
  END LOOP;
END;

Failed to connect to camera service

when you use camera.open; and you finish using the camera write this commend camera.release(); this will stop the camera so you can use it again

CSS rule to apply only if element has BOTH classes

If you need a progmatic solution this should work in jQuery:

$(".abc.xyz").css("width", 200);

Mac OS X - EnvironmentError: mysql_config not found

I had been debugging this problem forever - 3 hours 17 mins. What particularly annoyed me was that I already had sql installed on my system through prior uni work but pip/pip3 wasn't recognising it. These threads above and many other I scoured the internet for were helpful in eluminating the problem but didn't actually solve things.

ANSWER

Pip is looking for mysql binaries in the Homebrew Directory which is located relative to Macintosh HD @

/usr/local/Cellar/

so I found that this requires you making a few changes

step 1: Download MySql if not already done so https://dev.mysql.com/downloads/

Step 2: Locate it relative to Macintosh HD and cd

/usr/local/mysql/bin

Step 3: Once there open terminal and use a text editor of choice - I'm a neovim guy myself so I typed (doesn't automatically come with Mac... another story for another day)

nvim mysql_config

Step 4: You will see at approx line 112

# Create options 
libs="-L$pkglibdir"
libs="$libs -l "

Change to

# Create options 
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

*you'll notice that this file has read-only access so if your using vim or neovim

:w !sudo tee %

Step 5: Head to the home directory and edit the .bash_profile file

cd ~

Then

nvim .bash_profile

and add

export PATH="/usr/local/mysql/bin:$PATH"

to the file then save

Step 6: relative to Macintosh HD locate paths and add to it

cd /private/etc/

then

nvim paths

and add

/usr/local/mysql/bin

*you'll again notice that this file has read-only access so if your using vim or neovim

:w !sudo tee % 

then

cd ~

then refresh the terminal with your changes by running

source .bash_profile

Finally

pip3 install mysqlclient

And Viola. Remember it's a vibe.

How to install pip with Python 3?

Here is my way to solve this problem at ubuntu 12.04:

sudo apt-get install build-essential libncursesw5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev tk-dev

Then install the python3 from source code:

wget https://www.python.org/ftp/python/3.4.0/Python-3.4.0.tar.xz
tar xvf Python-3.4.0.tar.xz
cd Python-3.4.0
./configure
make
make test
sudo make install

When you finished installing all of them, pip3 will get installed automatically.

PHP session lost after redirect

When i use relative path "dir/file.php" with in the header() function in works for me. I think that the session is not saved for some reason when you redirect using the full url...

//Does retain the session info for some reason
header("Location: dir");

//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")

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

you can use https://www.npmjs.com/package/react-native-parsed-text

_x000D_
_x000D_
import ParsedText from 'react-native-parsed-text';_x000D_
 _x000D_
class Example extends React.Component {_x000D_
  static displayName = 'Example';_x000D_
 _x000D_
  handleUrlPress(url) {_x000D_
    LinkingIOS.openURL(url);_x000D_
  }_x000D_
 _x000D_
  handlePhonePress(phone) {_x000D_
    AlertIOS.alert(`${phone} has been pressed!`);_x000D_
  }_x000D_
 _x000D_
  handleNamePress(name) {_x000D_
    AlertIOS.alert(`Hello ${name}`);_x000D_
  }_x000D_
 _x000D_
  handleEmailPress(email) {_x000D_
    AlertIOS.alert(`send email to ${email}`);_x000D_
  }_x000D_
 _x000D_
  renderText(matchingString, matches) {_x000D_
    // matches => ["[@michel:5455345]", "@michel", "5455345"]_x000D_
    let pattern = /\[(@[^:]+):([^\]]+)\]/i;_x000D_
    let match = matchingString.match(pattern);_x000D_
    return `^^${match[1]}^^`;_x000D_
  }_x000D_
 _x000D_
  render() {_x000D_
    return (_x000D_
      <View style={styles.container}>_x000D_
        <ParsedText_x000D_
          style={styles.text}_x000D_
          parse={_x000D_
            [_x000D_
              {type: 'url',                       style: styles.url, onPress: this.handleUrlPress},_x000D_
              {type: 'phone',                     style: styles.phone, onPress: this.handlePhonePress},_x000D_
              {type: 'email',                     style: styles.email, onPress: this.handleEmailPress},_x000D_
              {pattern: /Bob|David/,              style: styles.name, onPress: this.handleNamePress},_x000D_
              {pattern: /\[(@[^:]+):([^\]]+)\]/i, style: styles.username, onPress: this.handleNamePress, renderText: this.renderText},_x000D_
              {pattern: /42/,                     style: styles.magicNumber},_x000D_
              {pattern: /#(\w+)/,                 style: styles.hashTag},_x000D_
            ]_x000D_
          }_x000D_
          childrenProps={{allowFontScaling: false}}_x000D_
        >_x000D_
          Hello this is an example of the ParsedText, links like http://www.google.com or http://www.facebook.com are clickable and phone number 444-555-6666 can call too._x000D_
          But you can also do more with this package, for example Bob will change style and David too. [email protected]_x000D_
          And the magic number is 42!_x000D_
          #react #react-native_x000D_
        </ParsedText>_x000D_
      </View>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
 _x000D_
const styles = StyleSheet.create({_x000D_
  container: {_x000D_
    flex: 1,_x000D_
    justifyContent: 'center',_x000D_
    alignItems: 'center',_x000D_
    backgroundColor: '#F5FCFF',_x000D_
  },_x000D_
 _x000D_
  url: {_x000D_
    color: 'red',_x000D_
    textDecorationLine: 'underline',_x000D_
  },_x000D_
 _x000D_
  email: {_x000D_
    textDecorationLine: 'underline',_x000D_
  },_x000D_
 _x000D_
  text: {_x000D_
    color: 'black',_x000D_
    fontSize: 15,_x000D_
  },_x000D_
 _x000D_
  phone: {_x000D_
    color: 'blue',_x000D_
    textDecorationLine: 'underline',_x000D_
  },_x000D_
 _x000D_
  name: {_x000D_
    color: 'red',_x000D_
  },_x000D_
 _x000D_
  username: {_x000D_
    color: 'green',_x000D_
    fontWeight: 'bold'_x000D_
  },_x000D_
 _x000D_
  magicNumber: {_x000D_
    fontSize: 42,_x000D_
    color: 'pink',_x000D_
  },_x000D_
 _x000D_
  hashTag: {_x000D_
    fontStyle: 'italic',_x000D_
  },_x000D_
 _x000D_
});
_x000D_
_x000D_
_x000D_

do <something> N times (declarative syntax)

const loop (fn, times) => {
  if (!times) { return }
  fn()
  loop(fn, times - 1)
}

loop(something, 3)

Make columns of equal width in <table>

I think that this will do the trick:

table{
    table-layout: fixed;
    width: 300px;
}

System.BadImageFormatException: Could not load file or assembly

Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:

Go and set your choice as shown:

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

if you are getting id from url try

$id = (isset($_GET['id']) ? $_GET['id'] : '');

if getting from form you need to use POST method cause your form has method="post"

 $id = (isset($_POST['id']) ? $_POST['id'] : '');

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

Recursively update Windows 7 until it shows no more updates, using Windows Update check option in Windows 7.

Then download and install Visual C++ Redistributable vc_redist.x64.exe from the Windows website.

Then try to run Apache server.

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

What does CultureInfo.InvariantCulture mean?

When numbers, dates and times are formatted into strings or parsed from strings a culture is used to determine how it is done. E.g. in the dominant en-US culture you have these string representations:

  • 1,000,000.00 - one million with a two digit fraction
  • 1/29/2013 - date of this posting

In my culture (da-DK) the values have this string representation:

  • 1.000.000,00 - one million with a two digit fraction
  • 29-01-2013 - date of this posting

In the Windows operating system the user may even customize how numbers and date/times are formatted and may also choose another culture than the culture of his operating system. The formatting used is the choice of the user which is how it should be.

So when you format a value to be displayed to the user using for instance ToString or String.Format or parsed from a string using DateTime.Parse or Decimal.Parse the default is to use the CultureInfo.CurrentCulture. This allows the user to control the formatting.

However, a lot of string formatting and parsing is actually not strings exchanged between the application and the user but between the application and some data format (e.g. an XML or CSV file). In that case you don't want to use CultureInfo.CurrentCulture because if formatting and parsing is done with different cultures it can break. In that case you want to use CultureInfo.InvariantCulture (which is based on the en-US culture). This ensures that the values can roundtrip without problems.

The reason that ReSharper gives you the warning is that some application writers are unaware of this distinction which may lead to unintended results but they never discover this because their CultureInfo.CurrentCulture is en-US which has the same behavior as CultureInfo.InvariantCulture. However, as soon as the application is used in another culture where there is a chance of using one culture for formatting and another for parsing the application may break.

So to sum it up:

  • Use CultureInfo.CurrentCulture (the default) if you are formatting or parsing a user string.
  • Use CultureInfo.InvariantCulture if you are formatting or parsing a string that should be parseable by a piece of software.
  • Rarely use a specific national culture because the user is unable to control how formatting and parsing is done.

'too many values to unpack', iterating over a dict. key=>string, value=>list

you are missing fields.iteritems() in your code.

You could also do it other way, where you get values using keys in the dictionary.

for key in fields:
    value = fields[key]

jQuery get the name of a select option

 $(this).attr("name") 

means the name of the select tag not option name.

To get option name

 $("#band_type_choices option:selected").attr('name');

How to create a database from shell command?

Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

This somehow did the trick for me:

  • Clean project
  • Clean build folder
  • Restart Xcode

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The error tells you that there is an error but you don´t catch it. This is how you can catch it:

getAllPosts().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

You can also just put a console.log(reponse) at the beginning of your API callback function, there is definitely an error message from the Graph API in it.

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Or with async/await:

//some async function
try {
    let response = await getAllPosts();
} catch(e) {
    console.log(e);
}

git push rejected: error: failed to push some refs

I did the following steps to resolve the issue. On the branch which was giving me the error:

  1. git pull origin [branch-name]<current branch>
  2. After pulling, got some merge issues, solved them, pushed the changes to the same branch.
  3. Created the Pull request with the pushed branch... tada, My changes were reflecting, all of them.

HttpListener Access Denied

Thanks all, it was of great help. Just to add more [from MS page]:

Warning

Top-level wildcard bindings (http://*:8080/ and http://+:8080) should not be used. Top-level wildcard bindings can open up your app to security vulnerabilities. This applies to both strong and weak wildcards. Use explicit host names rather than wildcards. Subdomain wildcard binding (for example, *.mysub.com) doesn't have this security risk if you control the entire parent domain (as opposed to *.com, which is vulnerable). See rfc7230 section-5.4 for more information.

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

After looking more, the root element has to be associated with a schema-namespace as Blaise is noting. Yet, I didnt have a package-info java. So without using the @XMLSchema annotation, I was able to correct this issue by using

@XmlRootElement (name="RetrieveMultipleSetsResponse", namespace = XMLCodeTable.NS1)
@XmlType(name = "ns0", namespace = XMLCodeTable.NS1)
@XmlAccessorType(XmlAccessType.NONE)
public class RetrieveMultipleSetsResponse {//...}

Hope this helps!

No module named Image

You can this query:

pip install image 

I had pillow installed, and still, I got the error that you mentioned. But after I executed the above command, the error vanished. And My program worked perfectly.

Python Matplotlib figure title overlaps axes label when using twiny

I was having an issue with the x-label overlapping a subplot title; this worked for me:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 1)
ax[0].scatter(...)
ax[1].scatter(...)
plt.tight_layout()
.
.
.
plt.show()

before

enter image description here

after

enter image description here

reference:

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

How to change the button color when it is active using bootstrap?

HTML--

<div class="col-sm-12" id="my_styles">
   <button type="submit" class="btn btn-warning" id="1">Button1</button>
   <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css--

.active{
         background:red;
    }
 button.btn:active{
     background:red;
 }

jQuery--

jQuery("#my_styles .btn").click(function(){
    jQuery("#my_styles .btn").removeClass('active');
    jQuery(this).toggleClass('active'); 

});

view the live demo on jsfiddle

How to make a flat list out of list of lists?

flat_list = []
for i in list_of_list:
    flat_list+=i

This Code also works fine as it just extend the list all the way. Although it is much similar but only have one for loop. So It have less complexity than adding 2 for loops.

Update query using Subquery in Sql Server

Here in my sample I find out the solution of this, because I had the same problem with updates and subquerys:

UPDATE
    A
SET
    A.ValueToChange = B.NewValue
FROM
    (
        Select * From C
    ) B
Where 
    A.Id = B.Id

How to call one shell script from another shell script?

There are a couple of ways you can do this. Terminal to execute the script:

#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"

# Here you execute your script
"$SCRIPT_PATH"

# or
. "$SCRIPT_PATH"

# or
source "$SCRIPT_PATH"

# or
bash "$SCRIPT_PATH"

# or
eval '"$SCRIPT_PATH"'

# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT

# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT

# or
("$SCRIPT_PATH")

# or
(exec "$SCRIPT_PATH")

All this is correct for the path with spaces!!!

Array of char* should end at '\0' or "\0"?

The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.

Command to get latest Git commit hash from a branch

you can git fetch nameofremoterepo, then git log

and personally, I alias gitlog to git log --graph --oneline --pretty --decorate --all. try out and see if it fits you

How is the AND/OR operator represented as in Regular Expressions?

'^(part1|part2|part1,part2)$'

does it work?

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

Load RSA public key from file

This program is doing almost everything with Public and private keys. The der format can be obtained but saving raw data ( without encoding base64). I hope this helps programmers.

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.security.pkcs.PKCS8Key;
import sun.security.pkcs10.PKCS10;
import sun.security.x509.X500Name;

import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;



/**
 * @author Desphilboy
 * DorOd bar shomA barobach
 *
 */
public class csrgenerator {

    private static PublicKey publickey= null;
    private static PrivateKey privateKey=null;
    //private static PKCS8Key privateKey=null;
    private static KeyPairGenerator kpg= null;
    private static ByteArrayOutputStream bs =null;
    private static csrgenerator thisinstance;
    private KeyPair keypair;
    private static PKCS10 pkcs10;
    private String signaturealgorithm= "MD5WithRSA";

    public String getSignaturealgorithm() {
        return signaturealgorithm;
    }



    public void setSignaturealgorithm(String signaturealgorithm) {
        this.signaturealgorithm = signaturealgorithm;
    }



    private csrgenerator() {
        try {
           kpg = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.print("No such algorithm RSA in constructor csrgenerator\n");
        }
        kpg.initialize(2048);
        keypair = kpg.generateKeyPair();
        publickey = keypair.getPublic();
        privateKey = keypair.getPrivate();
    }



    /** Generates a new key pair 
    *
    * @param int bits 
    *   this is the number of bits in modulus must be 512, 1024, 2048  or so on 
    */
    public KeyPair generateRSAkys(int bits)
    {
          kpg.initialize(bits);
            keypair = kpg.generateKeyPair();
            publickey = keypair.getPublic();
            privateKey = keypair.getPrivate();
            KeyPair dup= keypair;
     return dup;
    }

     public static csrgenerator getInstance() {
            if (thisinstance == null)
                thisinstance = new csrgenerator();
            return thisinstance;
        }


     /**
      *  Returns a CSR as string  
      * @param cn  Common Name
      * @param OU  Organizational Unit 
      * @param Org  Organization
      * @param LocName Location name
      * @param Statename  State/Territory/Province/Region
      * @param Country    Country
      * @return     returns  csr as string.
      * @throws Exception
      */
     public String getCSR(String commonname, String organizationunit, String organization,String localname, String statename, String country ) throws Exception {
            byte[] csr = generatePKCS10(commonname, organizationunit, organization, localname, statename, country,signaturealgorithm);
            return new String(csr);
        }

     /** This function generates a new Certificate 
      * Signing Request. 
     *
     * @param CN
     *            Common Name, is X.509 speak for the name that distinguishes
     *            the Certificate best, and ties it to your Organization
     * @param OU
     *            Organizational unit
     * @param O
     *            Organization NAME
     * @param L
     *            Location
     * @param S
     *            State
     * @param C
     *            Country
     * @return    byte stream of generated request
     * @throws Exception
     */
    private static byte[] generatePKCS10(String CN, String OU, String O,String L, String S, String C,String sigAlg) throws Exception {
        // generate PKCS10 certificate request

        pkcs10 = new PKCS10(publickey);
       Signature   signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        // common, orgUnit, org, locality, state, country
        //X500Name(String commonName, String organizationUnit,String organizationName,Local,State, String country)
        X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
        pkcs10.encodeAndSign(x500Name,signature);
        bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        pkcs10.print(ps);
        byte[] c = bs.toByteArray();
        try {
            if (ps != null)
                ps.close();
            if (bs != null)
                bs.close();
        } catch (Throwable th) {
        }
        return c;
    }

    public  PublicKey getPublicKey() {
        return publickey;
    }




    /**
     * @return
     */
    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * saves private key to a file
     * @param filename
     */
    public  void SavePrivateKey(String filename)
    {
        PKCS8EncodedKeySpec pemcontents=null;
        pemcontents= new PKCS8EncodedKeySpec( privateKey.getEncoded());
        PKCS8Key pemprivatekey= new  PKCS8Key( );
        try {
            pemprivatekey.decode(pemcontents.getEncoded());
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file=new File(filename);
        try {

            file.createNewFile();
            FileOutputStream fos=new FileOutputStream(file);
            fos.write(pemprivatekey.getEncoded());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }



    /**
     * Saves Certificate Signing Request to a file;
     * @param filename  is a String containing full path to the file which will be created containing the CSR.
     */
    public void SaveCSR(String filename)
    {
        FileOutputStream fos=null;
        PrintStream ps=null;
        File file;
        try {

            file = new File(filename);
            file.createNewFile();
            fos = new FileOutputStream(file);
            ps= new PrintStream(fos);
        }catch (IOException e)
        {
            System.out.print("\n could not open the file "+ filename);
        }

        try {
            try {
                pkcs10.print(ps);
            } catch (SignatureException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ps.flush();
            ps.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.print("\n cannot write to the file "+ filename);
            e.printStackTrace();

        }

        }


    /**
     * Saves both public key and private  key to file names specified
     * @param fnpub  file name of public key
     * @param fnpri  file name of private key
     * @throws IOException
     */
    public static void SaveKeyPair(String fnpub,String fnpri) throws IOException { 

// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publickey.getEncoded());
FileOutputStream fos = new FileOutputStream(fnpub);
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();

// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
fos = new FileOutputStream(fnpri);
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
}


    /**
     * Reads a Private Key from a pem base64 encoded file.
     * @param filename name of the file to read.
     * @param algorithm Algorithm is usually "RSA"
     * @return returns the privatekey which is read from the file;
     * @throws Exception
     */
    public  PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", "");
          privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
          //System.out.println("Private key\n"+privKeyPEM);

          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(privKeyPEM);

          PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePrivate(spec);
          }



    /**
     * Saves the private key to a pem file.
     * @param filename  name of the file to write the key into 
     * @param key the Private key to save.
     * @return  String representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPrivateKey(String filename) throws Exception {
        PrivateKey key=this.privateKey;
          File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          PKCS8Key pkcs8= new PKCS8Key();
          pkcs8.decode(keyBytes);
          byte[] b=pkcs8.encode();

          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(b);

          encoded= "-----BEGIN PRIVATE KEY-----\r\n" + encoded + "-----END PRIVATE KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
        return pkcs8.toString();

          }


    /**
     * Saves a public key to a base64 encoded pem file
     * @param filename  name of the file 
     * @param key public key to be saved 
     * @return string representation of the pkcs8 object.
     * @throws Exception
     */
    public  String  SavePemPublicKey(String filename) throws Exception {
        PublicKey key=this.publickey;  
        File f = new File(filename);
          FileOutputStream fos = new FileOutputStream(f);
          DataOutputStream dos = new DataOutputStream(fos);


          byte[] keyBytes = key.getEncoded();
          BASE64Encoder b64=new BASE64Encoder();
          String  encoded = b64.encodeBuffer(keyBytes);

          encoded= "-----BEGIN PUBLIC KEY-----\r\n" + encoded + "-----END PUBLIC KEY-----";

         dos.writeBytes(encoded);
         dos.flush();
         dos.close();

          //System.out.println("Private key\n"+privKeyPEM);
      return  encoded.toString();

          }





       /**
     * reads a public key from a file
     * @param filename name of the file to read
     * @param algorithm is usually RSA
     * @return the read public key
     * @throws Exception
     */
    public  PublicKey getPemPublicKey(String filename, String algorithm) throws Exception {
          File f = new File(filename);
          FileInputStream fis = new FileInputStream(f);
          DataInputStream dis = new DataInputStream(fis);
          byte[] keyBytes = new byte[(int) f.length()];
          dis.readFully(keyBytes);
          dis.close();

          String temp = new String(keyBytes);
          String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
          publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");


          BASE64Decoder b64=new BASE64Decoder();
          byte[] decoded = b64.decodeBuffer(publicKeyPEM);

          X509EncodedKeySpec spec =
                new X509EncodedKeySpec(decoded);
          KeyFactory kf = KeyFactory.getInstance(algorithm);
          return kf.generatePublic(spec);
          }




    public static void main(String[] args) throws Exception {
        csrgenerator gcsr = csrgenerator.getInstance();
        gcsr.setSignaturealgorithm("SHA512WithRSA");
        System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());

        System.out.println("Private Key:\nAlgorithm: "+gcsr.getPrivateKey().getAlgorithm().toString());
        System.out.println("Format:"+gcsr.getPrivateKey().getFormat().toString());
        System.out.println("To String :"+gcsr.getPrivateKey().toString());
        System.out.println("GetEncoded :"+gcsr.getPrivateKey().getEncoded().toString());
        BASE64Encoder encoder= new BASE64Encoder();
        String s=encoder.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Base64:"+s+"\n");

        String csr = gcsr.getCSR( "[email protected]","baxshi az xodam", "Xodam","PointCook","VIC" ,"AU");
        System.out.println("CSR Request Generated!!");
        System.out.println(csr);
        gcsr.SaveCSR("c:\\testdir\\javacsr.csr");
        String p=gcsr.SavePemPrivateKey("c:\\testdir\\java_private.pem");
        System.out.print(p);
        p=gcsr.SavePemPublicKey("c:\\testdir\\java_public.pem");
        privateKey= gcsr.getPemPrivateKey("c:\\testdir\\java_private.pem", "RSA");
        BASE64Encoder encoder1= new BASE64Encoder();
        String s1=encoder1.encodeBuffer(gcsr.getPrivateKey().getEncoded());
        System.out.println("Private Key in Base64:"+s1+"\n");
        System.out.print(p);


    }

    }

How to convert std::string to LPCWSTR in C++ (Unicode)

The solution is actually a lot easier than any of the other suggestions:

std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();

Best of all, it's platform independent.

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

Concatenating variables and strings in React

exampleData=

        const json1 = [
            {id: 1, test: 1},
            {id: 2, test: 2},
            {id: 3, test: 3},
            {id: 4, test: 4},
            {id: 5, test: 5}
        ];

        const json2 = [
            {id: 3, test: 6},
            {id: 4, test: 7},
            {id: 5, test: 8},
            {id: 6, test: 9},
            {id: 7, test: 10}
        ];

example1=


        const finalData1 = json1.concat(json2).reduce(function (index, obj) {
            index[obj.id] = Object.assign({}, obj, index[obj.id]);
            return index;
        }, []).filter(function (res, obj) {
            return obj;
        });

example2=

        let hashData = new Map();

        json1.concat(json2).forEach(function (obj) {
            hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
        });

        const finalData2 = Array.from(hashData.values());

I recommend second example , it is faster.

How to use If Statement in Where Clause in SQL?

Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement

Evaluates a list of conditions and returns one of multiple possible result expressions.

The CASE expression has two formats:

The simple CASE expression compares an expression to a set of simple expressions to determine the result.

The searched CASE expression evaluates a set of Boolean expressions to determine the result.

Both formats support an optional ELSE argument.

How to make asynchronous HTTP requests in PHP

  1. Fake a request abortion using CURL setting a low CURLOPT_TIMEOUT_MS

  2. set ignore_user_abort(true) to keep processing after the connection closed.

With this method no need to implement connection handling via headers and buffer too dependent on OS, Browser and PHP version

Master process

function async_curl($background_process=''){

    //-------------get curl contents----------------

    $ch = curl_init($background_process);
    curl_setopt_array($ch, array(
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER =>true,
        CURLOPT_NOSIGNAL => 1, //to timeout immediately if the value is < 1000 ms
        CURLOPT_TIMEOUT_MS => 50, //The maximum number of mseconds to allow cURL functions to execute
        CURLOPT_VERBOSE => 1,
        CURLOPT_HEADER => 1
    ));
    $out = curl_exec($ch);

    //-------------parse curl contents----------------

    //$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    //$header = substr($out, 0, $header_size);
    //$body = substr($out, $header_size);

    curl_close($ch);

    return true;
}

async_curl('http://example.com/background_process_1.php');

Background process

ignore_user_abort(true);

//do something...

NB

If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:

[...]

The solution is to disable signals using CURLOPT_NOSIGNAL

Resources

Force “landscape” orientation mode

screen.orientation.lock('landscape');

Will force it to change to and stay in landscape mode. Tested on Nexus 5.

http://www.w3.org/TR/screen-orientation/#examples

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

Inversion of Control vs Dependency Injection

I found best example on Dzone.com which is really helpfull to understand the real different between IOC and DI

“IoC is when you have someone else create objects for you.” So instead of writing "new " keyword (For example, MyCode c=new MyCode())in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container. It means we handover the rrsponsibility (control )to the container to get instance of object is called Inversion of Control., means instead of you are creating object using new operator, let the container do that for you.

   DI(Dependency Injection):  Way of injecting properties to an object is 
   called 
  Dependency injection.
   We have three types of Dependency injection
    1)  Constructor Injection
    2)  Setter/Getter Injection
    3)  Interface Injection
   Spring will support only Constructor Injection and Setter/Getter Injection.

Read full article IOC and Read Full article DI

Cloning a private Github repo

If you are sure that you don't have 2FA enabled, you have permission to access the repo, and the repo exists, it's possible that your [email protected] is logged in with another account.

to check that you can do

ssh -T [email protected]

If it shows another account, to resolve this issue:

 ssh-add -D
 ssh-add ~/.ssh/your_rsa
 ssh -T [email protected]
 git clone [email protected]:<owner_name>/<repo_name>.git

Return 0 if field is null in MySQL

You can try something like this

IFNULL(NULLIF(X, '' ), 0)

Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.

Anyway, just to give another way to do that.

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

Write to text file without overwriting in Java

Here is a simple example of how it works, best practice to put a try\catch into it but for basic use this should do the trick. For this you have a string and file path and apply thus to the FileWriter and the BufferedWriter. This will write "Hello World"(Data variable) and then make a new line. each time this is run it will add the Data variable to the next line.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;


String Data = "Hello World";
File file = new File("C:/Users/stuff.txt");
FileWriter fw = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(Data);
bw.newLine();
bw.close();

How do I clear the content of a div using JavaScript?

Just Javascript (as requested)

Add this function somewhere on your page (preferably in the <head>)

function clearBox(elementID)
{
    document.getElementById(elementID).innerHTML = "";
}

Then add the button on click event:

<button onclick="clearBox('cart_item')" />

In JQuery (for reference)

If you prefer JQuery you could do:

$("#cart_item").html("");

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case I could not load one out of 5 projects in my solution.

It helped to close Visual Studio and I had to delete Microsoft.Net.Compilers.1.3.2 nuget folder under packages folder.

Afterwards, open your solution again and the project loaded as expected

Just to be sure, close all instances of VS before you delete the folder.

Sorting a List<int>

Keeping it simple is the key.

Try Below.

var values = new int[5,7,3];
values = values.OrderBy(p => p).ToList();

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

Assuming you're using docker-compose, where your docker-compose.yml file looks like:

version: '3.7'
services:
  mysql_db_container:
    image: mysql:latest
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_ROOT_PASSWORD: rootpassword
    ports:
      - 3307:3306
    volumes:
      - mysql_db_data_container:/var/lib/mysql


  web:
    image: ${DOCKER_IMAGE_NAME-eis}:latest
    build:
      context: .
    links:
      - mysql_db_container
    ports:
      - 4000:3000
    command: ["./scripts/wait-for-it.sh", "mysql_db_container:3306", "--", "./scripts/start_web_server.sh"]
    volumes:
      - .:/opt/eis:cached
    env_file:
      - .env

volumes:
  mysql_db_data_container:

Notice the ports definition for mysql_db_container

    ports:
      - 3307:3306

<= That indicates that mysql will be accessible via port 3307 to the localhost workstation and via port 3306 within the docker net

Run the following to see your container names:

$ dc config --services
mysql_db_container
web

In this case, we have two containers.

Errors

If you connect to mysql_db_container from your localhost workstation and try to access the mysql console there, you'll get that error:

docker-compose run mysql_db_container bash
root@8880ffe47962:/# mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
root@8880ffe47962:/# exit

Also, if you try to connect from your local workstation, you'll also get that error:

$ mysql -u root -p -P 3307
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Solutions

Connecting from local workstation

Just add the --protocol=tcp parameter (otherwise mysql assumes you want to connect via the mysql socket):

$ mysql --protocol=tcp -u root -p -P 3307
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.21 MySQL Community Server - GPL

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

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

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

mysql>

Connecting from web container

Reference the docker hostname -h mysql_db_container. Note that when you're running within the context of Docker that the TCP protocol is assumed.

$ dc run web bash
Starting eligibility-service_mysql_db_container_1_d625308b5a77 ... done
root@e7852ff02683:/opt/eis# mysql -h mysql_db_container -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 8.0.21 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MySQL [(none)]> 

Connecting from mysql container

Assuming your mysql container name is eis_mysql_db_container_1_d625308b5a77 (that you can see when running docker ps), the following should work:

$ docker exec -it eis_mysql_db_container_1_d625308b5a77 bash
root@3738cf6eb3e9:/# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.21 MySQL Community Server - GPL

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

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

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

mysql> 

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

How to make <div> fill <td> height

If you give your TD a height of 1px, then the child div would have a heighted parent to calculate it's % from. Because your contents would be larger then 1px, the td would automatically grow, as would the div. Kinda a garbage hack, but I bet it would work.

Pipe subprocess standard output to a variable

If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output() command. Here is an example:

output = subprocess.check_output('ls')

To also redirect stderr you can use the following:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)

Spring Boot War deployed to Tomcat

public class Application extends SpringBootServletInitializer {}

just extends the SpringBootServletInitializer. It will works in your AWS/tomcat

Bootstrap 3 and Youtube in Modal

I had this same issue - I had just added the font-awesome cdn links - commenting out the bootstrap one below solved my issue.. didnt really troubleshoot it as the font awesome still worked -

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">

RSA encryption and decryption in Python

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

And use

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

How to check python anaconda version installed on Windows 10 PC?

The folder containing your Anaconda installation contains a subfolder called conda-meta with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json.

My file is called anaconda-5.0.1-py27hdb50712_1.json, and at the bottom is more info about the version:

"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe", 
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" }, 
"name": "anaconda", 
"platform": "win", 
"subdir": "win-64", 
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2", 
"version": "5.0.1"

(Slightly edited for brevity.)

The output from conda -V is the conda version.

Excel formula to get ranking position

You can use the RANK function in Excel without necessarily sorting the data. Type =RANK(C2,$C$2:$C$7). Excel will find the relative position of the data in C2 and display the answer. Copy the formula through to C7 by dragging the small node at the right end of the cell cursor.

Is there an addHeaderView equivalent for RecyclerView?

you can create addHeaderView and use

adapter.addHeaderView(View).

This code build the addHeaderView for more then one header. the headers should have:

android:layout_height="wrap_content"

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_ITEM = -1;
    public class MyViewSHolder extends RecyclerView.ViewHolder {
        public MyViewSHolder (View view) {
            super(view);
        }
        // put you code. for example:
        View mView;
        ...
    }

    public class ViewHeader extends RecyclerView.ViewHolder {
        public ViewHeader(View view) {
            super(view);
        }
    }

    private List<View> mHeaderViews = new ArrayList<>();
    public void addHeaderView(View headerView) {
        mHeaderViews.add(headerView);
    }

    @Override
    public int getItemCount() {
       return ... + mHeaderViews.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderViews.size() > position) {
            return position;
        }

        return TYPE_ITEM;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType != TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new ViewHeader(mHeaderViews.get(viewType));
        }
        ...
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int basePosition1) {
        if (holder instanceof ViewHeader) {
            return;
        }
        int basePosition = basePosition1 -  mHeaderViews.size();
        ...
    }
}

Replace invalid values with None in Pandas DataFrame

With Pandas version =1.0.0, I would use DataFrame.replace or Series.replace:

df.replace(old_val, pd.NA, inplace=True)

This is better for two reasons:

  1. It uses pd.NA instead of None or np.nan.
  2. It replaces the value in-place which could be more memory efficient.

Select from multiple tables without a join?

select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;

Check If only numeric values were entered in input. (jQuery)

I used this to check if all the text boxes had numeric values:

if(!$.isNumeric($('input:text').val())) {
        alert("All the text boxes must have numeric values!");
        return false;
    }

or for one:

$.isNumeric($("txtBox").val());

Available with jQuery 1.7.

Where is the php.ini file on a Linux/CentOS PC?

#php -i | grep php.ini also will work too!

Python string.join(list) on object array rather than string array

You could use a list comprehension or a generator expression instead:

', '.join([str(x) for x in list])  # list comprehension
', '.join(str(x) for x in list)    # generator expression

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

Excel telling me my blank cells aren't blank

If you don't have formatting or formulas you want to keep, you can try saving your file as a tab delimited text file, closing it, and reopening it with excel. This worked for me.

python pandas convert index to datetime

I just give other option for this question - you need to use '.dt' in your code:

_x000D_
_x000D_
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
_x000D_
_x000D_

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

How to convert array to a string using methods other than JSON?

You are looking for serialize(). Here is an example:

$array = array('foo', 'bar');

//Array to String
$string = serialize($array);

//String to array
$array = unserialize($string);

How to change link color (Bootstrap)

ul.nav li a, ul.nav li a:visited {
    color: #anycolor !important;
}

ul.nav li a:hover, ul.nav li a:active {
    color: #anycolor !important;
}

ul.nav li.active a {
    color: #anycolor !important;
}

Change the styles as you wish.

Get the Highlighted/Selected text

Yes you can do it with simple JavaScript snippet:

document.addEventListener('mouseup', event => {  
    if(window.getSelection().toString().length){
       let exactText = window.getSelection().toString();        
    }
}

Using CSS td width absolute, position

Try to use

table {
  table-layout: auto;
}

If you use Bootstrap, class table has table-layout: fixed; by default.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

It was happening to me in ZF2. I was trying to load the Modal content but I forgot to disable the layout before.

So:

$viewModel = new ViewModel();
$viewModel->setTerminal(true);
return $viewModel;

CSS3 transition on click using pure CSS

If you want a css only solution you can use active

.crossRotate:active {
   transform: rotate(45deg);
   -webkit-transform: rotate(45deg);
   -ms-transform: rotate(45deg);
}

But the transformation will not persist when the activity moves. For that you need javascript (jquery click and css is the cleanest IMO).

$( ".crossRotate" ).click(function() {
    if (  $( this ).css( "transform" ) == 'none' ){
        $(this).css("transform","rotate(45deg)");
    } else {
        $(this).css("transform","" );
    }
});

Fiddle

How do I wrap text in a span?

Wrapping can be done in various ways. I'll mention 2 of them:

1.) text wrapping - using white-space property http://www.w3schools.com/cssref/pr_text_white-space.asp

2.) word wrapping - using word-wrap property http://webdesignerwall.com/tutorials/word-wrap-force-text-to-wrap

By the way, in order to work using these 2 approaches, I believe you need to set the "display" property to block of the corresponding span element.

However, as Kirill already mentioned, it's a good idea to think about it for a moment. You're talking about forcing the text into a paragraph. PARAGRAPH. That should ring some bells in your head, shouldn't it? ;)

Print a file, skipping the first X lines, in Bash

Just to propose a sed alternative. :) To skip first one million lines, try |sed '1,1000000d'.

Example:

$ perl -wle 'print for (1..1_000_005)'|sed '1,1000000d'
1000001
1000002
1000003
1000004
1000005

Difference between Running and Starting a Docker container

  • run runs an image
  • start starts a container.

The docker run doc does mention:

The docker run command first creates a writeable container layer over the specified image, and then starts it using the specified command.

That is, docker run is equivalent to the API /containers/create then /containers/(id)/start.

You do not run an existing container, you docker exec to it (since docker 1.3).
You can restart an exited container.

How to convert a file into a dictionary?

def get_pair(line):
    key, sep, value = line.strip().partition(" ")
    return int(key), value

with open("file.txt") as fd:    
    d = dict(get_pair(line) for line in fd)

Count number of 1's in binary representation

I have actually done this using a bit of sleight of hand: a single lookup table with 16 entries will suffice and all you have to do is break the binary rep into nibbles (4-bit tuples). The complexity is in fact O(1) and I wrote a C++ template which was specialized on the size of the integer you wanted (in # bits)… makes it a constant expression instead of indetermined.

fwiw you can use the fact that (i & -i) will return you the LS one-bit and simply loop, stripping off the lsbit each time, until the integer is zero — but that’s an old parity trick.

How to display raw JSON data on a HTML page

JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.

However, about formatting, that's another matter. I guess you should change the title of your question.

Take a look at this question. Also see this page.

What is the apply function in Scala?

Here is a small example for those who want to peruse quickly

 object ApplyExample01 extends App {


  class Greeter1(var message: String) {
    println("A greeter-1 is being instantiated with message " + message)


  }

  class Greeter2 {


    def apply(message: String) = {
      println("A greeter-2 is being instantiated with message " + message)
    }
  }

  val g1: Greeter1 = new Greeter1("hello")
  val g2: Greeter2 = new Greeter2()

  g2("world")


} 

output

A greeter-1 is being instantiated with message hello

A greeter-2 is being instantiated with message world

Principal Component Analysis (PCA) in Python

For the sake def plot_pca(data): will work, it is necessary to replace the lines

data_resc, data_orig = PCA(data)
ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)

with lines

newData, data_resc, data_orig = PCA(data)
ax1.plot(newData[:, 0], newData[:, 1], '.', mfc=clr1, mec=clr1)

'Missing contentDescription attribute on image' in XML

Add android:contentDescription="@string/description" (static or dynamic) to your ImageView. Please do not ignore nor filter the message, because it is helpfull for people using alternative input methods because of their disability (Like TalkBack, Tecla Access Shield etc etc).

SQL NVARCHAR and VARCHAR Limits

You mus use nvarchar text too. that's mean you have to simply had a "N" before your massive string and that's it! no limitation anymore

DELARE @SQL NVARCHAR(MAX);
SET @SQL = N'SomeMassiveString > 4000 chars...';
EXEC(@SQL);
GO

Stored procedure return into DataSet in C# .Net

Try this

    DataSet ds = new DataSet("TimeRanges");
    using(SqlConnection conn = new SqlConnection("ConnectionString"))
    {               
            SqlCommand sqlComm = new SqlCommand("Procedure1", conn);               
            sqlComm.Parameters.AddWithValue("@Start", StartTime);
            sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
            sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);

            sqlComm.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlComm;

            da.Fill(ds);
     }

Notepad++ - How can I replace blank lines

As of NP++ V6.2.3 (nor sure about older versions) simply:

  1. Go menu -> Edit -> Line operations
  2. Choose "Remove Empty Lines" or "Remove Empty Lines (Containing white spaces)" according to your needs.

Hope this helps to achieve goal in simple and yet fast way:)

What is the difference between null and undefined in JavaScript?

Undefined means a variable has been declared but has no value:

var var1;
alert(var1); //undefined
alert(typeof var1); //undefined

Null is an assignment:

var var2= null;
alert(var2); //null
alert(typeof var2); //object

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

If your project has Roslyn references and you are deploying it on an IIS server, you might get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn.

To resolve this issue, you will need to remove the Roslyn compiler from the project template. Removing Roslyn shouldn't affect your code's functionality. It worked fine for me and some other projects (C# 4.5.2) on which I worked.

Do the following steps:

  1. Remove from following Nuget Packages using command line shown below (or you can use GUI of Nuget Package manager by Right Clicking on Root Project Solution and removing them).

    PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
    PM> Uninstall-package Microsoft.Net.Compilers
    
  2. Remove the following code from your Web.Config file and restart IIS. (Use this method only if step 1 doesn't solve your problem.)

    <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
    

How to change active class while click to another link in bootstrap use jquery?

If you change the classes and load the content within the same function you should be fine.

$(document).ready(function(){
    $('.nav li').click(function(event){
        //remove all pre-existing active classes
        $('.active').removeClass('active');

        //add the active class to the link we clicked
        $(this).addClass('active');

        //Load the content
        //e.g.
        //load the page that the link was pointing to
        //$('#content').load($(this).find(a).attr('href'));      

        event.preventDefault();
    });
});

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

For each conflicted file you get, you can specify

git checkout --ours -- <paths>
# or
git checkout --theirs -- <paths>

From the git checkout docs

git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...

--ours
--theirs
When checking out paths from the index, check out stage #2 (ours) or #3 (theirs) for unmerged paths.

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

What size should TabBar images be?

According to the latest Apple Human Interface Guidelines:

In portrait orientation, tab bar icons appear above tab titles. In landscape orientation, the icons and titles appear side-by-side. Depending on the device and orientation, the system displays either a regular or compact tab bar. Your app should include custom tab bar icons for both sizes.

enter image description here

enter image description here

I suggest you to use the above link to understand the full concept. Because apple update it's document in regular interval

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

makedirs creates multiple levels of directories, if needed.

Maven Modules + Building a Single Specific Module

Maven absolutely was designed for this type of dependency.

mvn package won't install anything in your local repository it just packages the project and leaves it in the target folder.

Do mvn install in parent project (A), with this all the sub-modules will be installed in your computer's Maven repository, if there are no changes you just need to compile/package the sub-module (B) and Maven will take the already packaged and installed dependencies just right.

You just need to a mvn install in the parent project if you updated some portion of the code.

Displaying a webcam feed using OpenCV and Python

change import cv to import cv2.cv as cv See also the post here.

Updating GUI (WPF) using a different thread

there.

I am also developing a serial port testing tool using WPF, and I'd like to share some experience of mine.

I think you should refactor your source code according to MVVM design pattern.

At the beginning, I met the same problem as you met, and I solved it using this code:

new Thread(() => 
{
    while (...)
    {
        SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...));
    }
}).Start();

This works, but is too ugly. I have no idea how to refactor it, until I saw this: http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

This is a very kindly step-by-step MVVM tutorial for beginners. No shiny UI, no complex logic, only the basic of MVVM.

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

newlist = oldlist[::10]

This picks out every 10th element of the list.

$("#form1").validate is not a function

I had this issue, jquery URL was valid, everything looked good and validation still worked. After a hard refresh CTL+F5 the error went away in Chrome.

Save file/open file dialog box, using Swing & Netbeans GUI editor

Here is an example

private void doOpenFile() {
    int result = myFileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        Path path = myFileChooser.getSelectedFile().toPath();

        try {
            String contentString = "";

            for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
                contentString += s;
            }

            jText.setText(contentString);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private void doSaveFile() {
    int result = myFileChooser.showSaveDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        // We'll be making a mytmp.txt file, write in there, then move it to
        // the selected
        // file. This takes care of clearing that file, should there be
        // content in it.
        File targetFile = myFileChooser.getSelectedFile();

        try {
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }

            FileWriter fw = new FileWriter(targetFile);

            fw.write(jText.getText());
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ProcessStartInfo hanging on "WaitForExit"? Why?

Workaround I ended up using to avoid all the complexity:

var outputFile = Path.GetTempFileName();
info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args) + " > " + outputFile + " 2>&1");
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(File.ReadAllText(outputFile)); //need the StandardOutput contents

So I create a temp file, redirect both the output and error to it by using > outputfile > 2>&1 and then just read the file after the process has finished.

The other solutions are fine for scenarios where you want to do other stuff with the output, but for simple stuff this avoids a lot of complexity.

Java: Detect duplicates in ArrayList?

Improved code, using return value of Set#add instead of comparing the size of list and set.

public static <T> boolean hasDuplicate(Iterable<T> all) {
    Set<T> set = new HashSet<T>();
    // Set#add returns false if the set does not change, which
    // indicates that a duplicate element has been added.
    for (T each: all) if (!set.add(each)) return true;
    return false;
}

How do you create a Swift Date object?

Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate type, e.g:

class Date {

    class func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

Which you can use like:

var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)

file_put_contents(meta/services.json): failed to open stream: Permission denied

Setting permission to 777 is definitely terrible idea!

... but

If you are getting permission error connected with "storage" folder that's what worked for me:

1) Set "storage" and its subfolders permission to 777 with

sudo chmod -R 777 storage/

2) In browser go to laravel home page laravel/public/ (laravel will create necessary initial storage files)

3) Return safe 775 permission to storage and its subfolders

sudo chmod -R 775 storage/

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Regarding this part:

When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.

The easiest solution is to avoid the problem entirely by properly configuring Notepad++.

Try Settings -> Preferences -> New document -> Encoding -> choose UTF-8 without BOM, and check Apply to opened ANSI files.

notepad++ UTF-8 apply to opened ANSI files

That way all the opened ANSI files will be treated as UTF-8 without BOM.

For explanation what's going on, read the comments below this answer.

To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Best way to retrieve variable values from a text file?

hbn's answer won't work out of the box if the file to load is in a subdirectory or is named with dashes.

In such a case you may consider this alternative :

exec open(myconfig.py).read()

Or the simpler but deprecated in python3 :

execfile(myconfig.py)

I guess Stephan202's warning applies to both options, though, and maybe the loop on lines is safer.

Python display text with font & color?

There are 2 possibilities. In either case PyGame has to be initialized by pygame.init.

import pygame
pygame.init()

Use either the pygame.font module and create a pygame.font.SysFont or pygame.font.Font object. render() a pygame.Surface with the text and blit the Surface to the screen:

my_font = pygame.font.SysFont(None, 50)
text_surface = myfont.render("Hello world!", True, (255, 0, 0))
screen.blit(text_surface, (10, 10))

Or use the pygame.freetype module. Create a pygame.freetype.SysFont() or pygame.freetype.Font object. render() a pygame.Surface with the text or directly render_to() the text to the screen:

my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)
my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))

See also Text and font


Minimal pygame.font example: repl.it/@Rabbid76/PyGame-Text

import pygame

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)
text = font.render('Hello World', True, (255, 0, 0))

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    window.blit(text, text.get_rect(center = window.get_rect().center))
    pygame.display.flip()

pygame.quit()
exit()

Minimal pygame.freetype example: repl.it/@Rabbid76/PyGame-FreeTypeText

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()

ft_font = pygame.freetype.SysFont('Times New Roman', 80)

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
    pygame.draw.rect(background, color, rect)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(background, (0, 0))
    text_rect = ft_font.get_rect('Hello World')
    text_rect.center = window.get_rect().center
    ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0))
    pygame.display.flip()

pygame.quit()
exit()

Can a PDF file's print dialog be opened with Javascript?

I usually do something similar to the approach given by How to Use JavaScript to Print a PDF (eHow.com), using an iframe.

  1. a function to house the print trigger...

    function printTrigger(elementId) {
        var getMyFrame = document.getElementById(elementId);
        getMyFrame.focus();
        getMyFrame.contentWindow.print();
    }
    
  2. an button to give the user access...

    (an onClick on an a or button or input or whatever you wish)

    <input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
    
  3. an iframe pointing to your PDF...

    <iframe id="iFramePdf" src="myPdfUrl.pdf" style="display:none;"></iframe>
    

Bonus Idea #1 - Create the iframe and add it to your page within the printTrigger(); so that the PDF isn't loaded until the user clicks your "Print" button, then the javascript can attack! the iframe and trigger the print dialog.


Bonus Idea #2 - Extra credit if you disable your "Print" button and give the user a little loading spinner or something after they click it, so that they know something's in process instead of clicking it repeatedly!

How to specify the actual x axis values to plot as x axis ticks in R

In case of plotting time series, the command ts.plot requires a different argument than xaxt="n"

require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))

How to backup a local Git repository?

[Just leaving this here for my own reference.]

My bundle script called git-backup looks like this

#!/usr/bin/env ruby
if __FILE__ == $0
        bundle_name = ARGV[0] if (ARGV[0])
        bundle_name = `pwd`.split('/').last.chomp if bundle_name.nil? 
        bundle_name += ".git.bundle"
        puts "Backing up to bundle #{bundle_name}"
        `git bundle create /data/Dropbox/backup/git-repos/#{bundle_name} --all`
end

Sometimes I use git backup and sometimes I use git backup different-name which gives me most of the possibilities I need.

Shell script not running, command not found

There have been a few good comments about adding the shebang line to the beginning of the script. I'd like to add a recommendation to use the env command as well, for additional portability.

While #!/bin/bash may be the correct location on your system, that's not universal. Additionally, that may not be the user's preferred bash. #!/usr/bin/env bash will select the first bash found in the path.

SyntaxError: Unexpected token function - Async Await Nodejs

node v6.6.0

If you just use in development. You can do this:

npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev

the package.json would be like this:

"devDependencies": {
   "babel-cli": "^6.18.0",
   "babel-plugin-transform-async-to-generator": "^6.16.0",
   "babel-polyfill": "^6.20.0"
}

create .babelrc file and write this:

{
  "plugins": ["transform-async-to-generator"]
}

and then, run your async/await script like this:

./node_modules/.bin/babel-node script.js

How to make the python interpreter correctly handle non-ASCII characters in string operations?

The following code will replace all non ASCII characters with question marks.

"".join([x if ord(x) < 128 else '?' for x in s])

How to get the HTML's input element of "file" type to only accept pdf files?

Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.

Could not create work tree dir 'example.com'.: Permission denied

I think you don't have your permissions set up correctly for /var/www Change the ownership of the folder.

sudo chown -R **yourusername** /var/www

Converting a Pandas GroupBy output from Series to DataFrame

I have aggregated with Qty wise data and store to dataframe

almo_grp_data = pd.DataFrame({'Qty_cnt' :
almo_slt_models_data.groupby( ['orderDate','Item','State Abv']
          )['Qty'].sum()}).reset_index()

Given two directory trees, how can I find out which files differ by content?

You can also use Rsync and find. For find:

find $FOLDER -type f | cut -d/ -f2- | sort > /tmp/file_list_$FOLDER

But files with the same names and in the same subfolders, but with different content, will not be shown in the lists.

If you are a fan of GUI, you may check Meld that @Alexander mentioned. It works fine in both windows and linux.

How to install .MSI using PowerShell

In powershell 5.1 you can actually use install-package, but it can't take extra msi arguments.

install-package .\file.msi

Otherwise with start-process and waiting:

start -wait file.msi ALLUSERS=1,INSTALLDIR=C:\FILE

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

What is the best way to prevent session hijacking?

Protect by:

$ip=$_SERVER['REMOTE_ADDER'];
$_SESSEION['ip']=$ip;

Set Locale programmatically

For people still looking for this answer, since configuration.locale was deprecated from API 24, you can now use:

configuration.setLocale(locale);

Take in consideration that the minSkdVersion for this method is API 17.

Full example code:

@SuppressWarnings("deprecation")
private void setLocale(Locale locale){
    SharedPrefUtils.saveLocale(locale); // optional - Helper method to save the selected language to SharedPreferences in case you might need to attach to activity context (you will need to code this)
    Resources resources = getResources();
    Configuration configuration = resources.getConfiguration();
    DisplayMetrics displayMetrics = resources.getDisplayMetrics();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
        configuration.setLocale(locale);
    } else{
        configuration.locale=locale;
    }
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N){
        getApplicationContext().createConfigurationContext(configuration);
    } else {
        resources.updateConfiguration(configuration,displayMetrics);
    }
}

Don't forget that, if you change the locale with a running Activity, you will need to restart it for the changes to take effect.

EDIT 11th MAY 2018

As from @CookieMonster's post, you might have problems keeping the locale change in higher API versions. If so, add the following code to your Base Activity so that you update the context locale on every Activity creation:

@Override
protected void attachBaseContext(Context base) {
     super.attachBaseContext(updateBaseContextLocale(base));
}

private Context updateBaseContextLocale(Context context) {
    String language = SharedPrefUtils.getSavedLanguage(); // Helper method to get saved language from SharedPreferences
    Locale locale = new Locale(language);
    Locale.setDefault(locale);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
        return updateResourcesLocale(context, locale);
    }

    return updateResourcesLocaleLegacy(context, locale);
}

@TargetApi(Build.VERSION_CODES.N_MR1)
private Context updateResourcesLocale(Context context, Locale locale) {
    Configuration configuration = new Configuration(context.getResources().getConfiguration())
    configuration.setLocale(locale);
    return context.createConfigurationContext(configuration);
}

@SuppressWarnings("deprecation")
private Context updateResourcesLocaleLegacy(Context context, Locale locale) {
    Resources resources = context.getResources();
    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    return context;
}

If you use this, don't forget to save the language to SharedPreferences when you set the locale with setLocate(locale)

EDIT 7th APRIL 2020

You might be experiencing issues in Android 6 and 7, and this happens due to an issue in the androidx libraries while handling the night mode. For this you will also need to override applyOverrideConfiguration in your base activity and update the configuration's locale in case a fresh new locale one is created.

Sample code:

@Override
public void applyOverrideConfiguration(Configuration overrideConfiguration) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) {
        // update overrideConfiguration with your locale  
        setLocale(overrideConfiguration) // you will need to implement this
    }
    super.applyOverrideConfiguration(overrideConfiguration);
} 

What is the best free SQL GUI for Linux for various DBMS systems

I'm sticking with DbVisualizer Free until something better comes along.

EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this

Capture Signature using HTML5 and iPad

The options already listed are very good, however here a few more on this topic that I've researched and came across.

1) http://perfectionkills.com/exploring-canvas-drawing-techniques/
2) http://mcc.id.au/2010/signature.html
3) https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/

And as always you may want to save the canvas to image:
http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/

good luck and happy signing

java.lang.NoClassDefFoundError: Could not initialize class XXX

NoClassDefFoundError doesn't give much of a clue as to what went wrong inside the static block. It is good practice to always have a block like this inside of static { ... } initialization code:

static {
  try {

    ... your init code here

  } catch (Throwable t) {
    LOG.error("Failure during static initialization", t);
    throw t;
  }
}

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

Why should text files end with a newline?

Some tools expect this. For example, wc expects this:

$ echo -n "Line not ending in a new line" | wc -l
0
$ echo "Line ending with a new line" | wc -l
1

How do I copy directories recursively with gulp?

Turns out that to copy a complete directory structure gulp needs to be provided with a base for your gulp.src() method.

So gulp.src( [ files ], { "base" : "." }) can be used in the structure above to copy all the directories recursively.

If, like me, you may forget this then try:

gulp.copy=function(src,dest){
    return gulp.src(src, {base:"."})
        .pipe(gulp.dest(dest));
};

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

Convert string to nullable type (int, double, etc...)

Here's something based on accepted answer. I removed the try/catch to make sure all the exceptions are not swallowed and not dealt with. Also made sure that the return variable (in accepted answer) is never initialized twice for nothing.

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    if (!string.IsNullOrWhiteSpace(s))
    {
        TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));

        return (T)conv.ConvertFrom(s);
    }

    return default(Nullable<T>);
}

Daemon Threads Explanation

Other posters gave some examples for situations in which you'd use daemon threads. My recommendation, however, is never to use them.

It's not because they're not useful, but because there are some bad side effects you can experience if you use them. Daemon threads can still execute after the Python runtime starts tearing down things in the main thread, causing some pretty bizarre exceptions.

More info here:

https://joeshaw.org/python-daemon-threads-considered-harmful/

https://mail.python.org/pipermail/python-list/2005-February/343697.html

Strictly speaking you never need them, it just makes implementation easier in some cases.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

First off, if you're using savefig, be aware that it will override the figure's background color when saving unless you specify otherwise (e.g. fig.savefig('blah.png', transparent=True)).

However, to remove the axes' and figure's background on-screen, you'll need to set both ax.patch and fig.patch to be invisible.

E.g.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for item in [fig, ax]:
    item.patch.set_visible(False)

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

(Of course, you can't tell the difference on SO's white background, but everything is transparent...)

If you don't want to show anything other than the line, turn the axis off as well using ax.axis('off'):

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

fig.patch.set_visible(False)
ax.axis('off')

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

In that case, though, you may want to make the axes take up the full figure. If you manually specify the location of the axes, you can tell it to take up the full figure (alternately, you can use subplots_adjust, but this is simpler for the case of a single axes).

import matplotlib.pyplot as plt

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.plot(range(10))

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

Undefined reference to sqrt (or other mathematical functions)

Just adding the #include <math.h> in c source file and -lm in Makefile at the end will work for me.

    gcc -pthread -o p3 p3.c -lm

SQLAlchemy default DateTime

DateTime doesn't have a default key as an input. The default key should be an input to the Column function. Try this:

import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Test(Base):
    __tablename__ = 'test'

    id = Column(Integer, primary_key=True)
    created_date = Column(DateTime, default=datetime.datetime.utcnow)

Why does HTML think “chucknorris” is a color?

I'm sorry to disagree, but according to the rules for parsing a legacy color value posted by @Yuhong Bao, chucknorris DOES NOT equate to #CC0000, but rather to #C00000, a very similar but slightly different hue of red. I used the Firefox ColorZilla add-on to verify this.

The rules state:

  • make the string a length that is a multiple of 3 by adding 0s: chucknorris0
  • separate the string into 3 equal length strings: chuc knor ris0
  • truncate each string to 2 characters: ch kn ri
  • keep the hex values, and add 0's where necessary: C0 00 00

I was able to use these rules to correctly interpret the following strings:

  • LuckyCharms
  • Luck
  • LuckBeALady
  • LuckBeALadyTonight
  • GangnamStyle

UPDATE: The original answerers who said the color was #CC0000 have since edited their answers to include the correction.

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Also, you can use -o or --offline in the mvn command line which will put maven in "offline mode" so it won't check for updates. You'll get some warning about not being able to get dependencies not already in your local repo, but no big deal.

Input Type image submit form value?

Add this

    name="myvalue"

To your tag.

Call to getLayoutInflater() in places not in activity

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

ActionBarActivity cannot resolve a symbol

Follow the steps mentioned for using support ActionBar in Android Studio(0.4.2) :

Download the Android Support Repository from Android SDK Manager, SDK Manager icon will be available on Android Studio tool bar (or Tools -> Android -> SDK Manager).

enter image description here

After download you will find your Support repository here

$SDK_DIR\extras\android\m2repository\com\android\support\appcompat-v7

Open your main module's build.gradle file and add following dependency for using action bar in lower API level

dependencies {
    compile 'com.android.support:appcompat-v7:+'
}

Sync your project with gradle using the tiny Gradle icon available in toolbar (or Tools -> Android -> Sync Project With Gradle Files).

There is some issue going on with Android Studio 0.4.2 so check this as well if you face any issue while importing classes in code.

Import Google Play Services library in Android Studio

If Required follow the steps as well :

  • Exit Android Studio
  • Delete all the .iml files and files inside .idea folder from your project
  • Relaunch Android Studio and wait till the project synced completely with gradle. If it shows an error in Event Log with import option click on Import Project.

This is bug in Android Studio 0.4.2 and fixed for Android Studio 0.4.3 release.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

How to work-it in Tomcat 7

I wanted to support a self signed certificate in a Tomcat App but the following snippet failed to work

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HTTPSPlayground {
    public static void main(String[] args) throws Exception {

        URL url = new URL("https:// ... .com");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        httpURLConnection.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());

        String serializedMessage = "{}";
        wr.writeBytes(serializedMessage);
        wr.flush();
        wr.close();

        int responseCode = httpURLConnection.getResponseCode();
        System.out.println(responseCode);
    }
}

this is what solved my issue:

1) Download the .crt file

echo -n | openssl s_client -connect <your domain>:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/<your domain>.crt
  • replace <your domain> with your domain (e.g. jossef.com)

2) Apply the .crt file in Java's cacerts certificate store

keytool -import -v -trustcacerts -alias <your domain> -file ~/<your domain>.crt -keystore <JAVA HOME>/jre/lib/security/cacerts -keypass changeit -storepass changeit
  • replace <your domain> with your domain (e.g. jossef.com)
  • replace <JAVA HOME> with your java home directory

3) Hack it

Even though iv'e installed my certificate in Java's default certificate stores, Tomcat ignores that (seems like it's not configured to use Java's default certificate stores).

To hack this, add the following somewhere in your code:

String certificatesTrustStorePath = "<JAVA HOME>/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.trustStore", certificatesTrustStorePath);

// ...

Add Custom Headers using HttpWebRequest

IMHO it is considered as malformed header data.

You actually want to send those name value pairs as the request content (this is the way POST works) and not as headers.

The second way is true.

Forbidden You don't have permission to access /wp-login.php on this server

I got recently this error and i used the solution which is proposed by @SirPaul. But the error was existing on the other configuration pages of the WordPress like update-core.php .

The solution that i have found, which resolved all the permission problems, was to deactivate iThemes Security plugin and update it and reactivate it.

Search and replace a particular string in a file using Perl

Quick and dirty:

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/<PREF>/ABCD/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.

How to get last N records with activerecord?

Add an :order parameter to the query

Why emulator is very slow in Android Studio?

Use x86 images and download "Intel Hardware Accelerated Execution Manager" from the sdk manager.

See here how to enable it: http://developer.android.com/tools/devices/emulator.html#accel-vm

Your emulator will be super fast!

npm ERR! network getaddrinfo ENOTFOUND

does your proxy require you to authenticate? because if it does, you might want you configure your proxy like this.

placeholder names. username is a placeholder for your actual username. password is a placeholder for your actual password. proxy.company.com is a placeholder for your actualy proxy *port" is your actualy port the proxy goes through. its usualy 8080

npm config set proxy "http://username:[email protected]:port"
npm config set https-proxy "http://username:[email protected]:port"

Select distinct values from a table field

In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by() on distinct("field_name") queries. This is, however, a Postgres only feature!

If you are using Postgres and if you define a field name that the query should be distinct for, then order_by() needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).

Note

When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.

For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.

If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:

# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')  

OpenSSL: unable to verify the first certificate for Experian URL

Adding additional information to emboss's answer.

To put it simply, there is an incorrect cert in your certificate chain.

For example, your certificate authority will have most likely given you 3 files.

  • your_domain_name.crt
  • DigiCertCA.crt # (Or whatever the name of your certificate authority is)
  • TrustedRoot.crt

You most likely combined all of these files into one bundle.

-----BEGIN CERTIFICATE----- 
(Your Primary SSL certificate: your_domain_name.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Intermediate certificate: DigiCertCA.crt) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Root certificate: TrustedRoot.crt) 
-----END CERTIFICATE-----

If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.

Redownload all certs from your certificate authority and make a fresh bundle.

Event handler not working on dynamic content

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

See http://api.jquery.com/on/#direct-and-delegated-events

Change your code to

$(document.body).on('click', '.update' ,function(){

The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.

As this answers receives a lot of attention, here are two supplementary advises :

1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.

That is, if you're adding an element of class b to an existing element of id a, then don't use

$(document.body).on('click', '#a .b', function(){

but use

$('#a').on('click', '.b', function(){

2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.

How can I get the count of line in a file in an efficient way?

Old post, but I have a solution that could be usefull for next people. Why not just use file length to know what is the progression? Of course, lines has to be almost the same size, but it works very well for big files:

public static void main(String[] args) throws IOException {
    File file = new File("yourfilehere");
    double fileSize = file.length();
    System.out.println("=======> File size = " + fileSize);
    InputStream inputStream = new FileInputStream(file);
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "iso-8859-1");
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    int totalRead = 0;
    try {
        while (bufferedReader.ready()) {
            String line = bufferedReader.readLine();
            // LINE PROCESSING HERE
            totalRead += line.length() + 1; // we add +1 byte for the newline char.
            System.out.println("Progress ===> " + ((totalRead / fileSize) * 100) + " %");
        }
    } finally {
        bufferedReader.close();
    }
}

It allows to see the progression without doing any full read on the file. I know it depends on lot of elements, but I hope it will be usefull :).

[Edition] Here is a version with estimated time. I put some SYSO to show progress and estimation. I see that you have a good time estimation errors after you have treated enough line (I try with 10M lines, and after 1% of the treatment, the time estimation was exact at 95%). I know, some values has to be set in variable. This code is quickly written but has be usefull for me. Hope it will be for you too :).

long startProcessLine = System.currentTimeMillis();
    int totalRead = 0;
    long progressTime = 0;
    double percent = 0;
    int i = 0;
    int j = 0;
    int fullEstimation = 0;
    try {
        while (bufferedReader.ready()) {
            String line = bufferedReader.readLine();
            totalRead += line.length() + 1;
            progressTime = System.currentTimeMillis() - startProcessLine;
            percent = (double) totalRead / fileSize * 100;
            if ((percent > 1) && i % 10000 == 0) {
                int estimation = (int) ((progressTime / percent) * (100 - percent));
                fullEstimation += progressTime + estimation;
                j++;
                System.out.print("Progress ===> " + percent + " %");
                System.out.print(" - current progress : " + (progressTime) + " milliseconds");
                System.out.print(" - Will be finished in ===> " + estimation + " milliseconds");
                System.out.println(" - estimated full time => " + (progressTime + estimation));
            }
            i++;
        }
    } finally {
        bufferedReader.close();
    }
    System.out.println("Ended in " + (progressTime) + " seconds");
    System.out.println("Estimative average ===> " + (fullEstimation / j));
    System.out.println("Difference: " + ((((double) 100 / (double) progressTime)) * (progressTime - (fullEstimation / j))) + "%");

Feel free to improve this code if you think it's a good solution.

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

SQL Server converting varbinary to string

Here is a simple example I wrote to convert and convert back using the 2 convert methods, I also checked it with a fixed string

declare @VB1 VARBINARY(500),@VB2 VARBINARY(500),@VB3 VARBINARY(500)

declare @S1 VARCHAR(500)

SET @VB1=HASHBYTES('SHA1','Test')

SET @S1=CONVERT(varchar(500),@VB1,2)

SET @VB2=CONVERT(varbinary(500),@S1,2)

SET @VB3=CONVERT(varbinary(500),'640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA',2)

SELECT @VB1,@S1,@VB2,@VB3

IF @VB1=@VB2 PRINT 'They Match(2)'

IF @VB1=@VB3 PRINT 'They Match(3)'

PRINT str(Len(@VB1))

PRINT str(Len(@S1))

PRINT str(Len(@VB2))

SET @VB1=HASHBYTES('SHA1','Test')

SET @S1=CONVERT(varchar(500),@VB1,1)

SET @VB2=CONVERT(varbinary(500),@S1,1)

SELECT @VB1,@S1,@VB2

IF @VB1=@VB2 PRINT 'They Match(1)'

PRINT str(Len(@VB1))

PRINT str(Len(@S1))

PRINT str(Len(@VB2))

and the output

||| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA

(1 row(s) affected)

They Match(2)

They Match(3)

    20
    40
    20

|| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA

(1 row(s) affected)

They Match(1)

    20
    42
    20

Visual Studio Code cannot detect installed git

Three years later, I ran into the same issue. Setting the path in user settings & PATH environment variable didn't help. I updated VSCode and that solved it.

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

"No such file or directory" is coming from Linux, and I've seen the following causes:

First cause is not actually having the file inside your container. Some people try to run a command from the host without adding it to their image. Some people shadow their command by mounting a volume on top of the command they wanted to run. If you run the same container, but with a shell instead of your normal entrypoint/cmd value, and run an ls /path/to/cmd you'll see if this exists.

The next cause is running the wrong command. This often appears with json/exec formatting of the command to run that doesn't parse correctly. If you see a command trying to run ["app", or something similar, the json string wasn't parsed by Docker and Linux is trying to use a shell to parse the command as a string. This can also happen if you misorder the args, e.g. trying to run -it is a sign you tried to place flags after the image name when they must be placed before the image name.

With shell scripts, this error appears if the first line with the #! points to a command that doesn't exist inside the container. For some, this is trying to run bash in an image that only has /bin/sh. And in your case, this can be from Windows linefeeds in the script. Switching to Linux/Unix linefeeds in your editor will correct that.

With binaries, this error appears if a linked library is missing. I've seen this often when Go commands that are compiled with libc, but run on alpine with musl or scratch without any libraries at all. You need to either include all the missing libraries or statically compile your command. To see these library links, use ldd /your/app on your binary.

How to create a simple map using JavaScript/JQuery

Just use plain objects:

var map = { key1: "value1", key2: "value2" }
function get(k){
  return map[k];
}

How do I set adaptive multiline UILabel text?

I know it's a bit old but since I recently looked into it :

let l = UILabel()
l.numberOfLines = 0
l.lineBreakMode = .ByWordWrapping
l.text = "BLAH BLAH BLAH BLAH BLAH"
l.frame.size.width = 300
l.sizeToFit()

First set the numberOfLines property to 0 so that the device understands you don't care how many lines it needs. Then specify your favorite BreakMode Then the width needs to be set before sizeToFit() method. Then the label knows it must fit in the specified width

How to get JSON Key and Value?

It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):

$.each(result[0], function(key, value){
    console.log(key, value);
});

If you might have more than one element and you'd like to iterate over them all, you could nest $.each():

$.each(result, function(key, value){
    $.each(value, function(key, value){
        console.log(key, value);
    });
});

GitLab git user password

I had the same problem, I spent a lot of time searching!

I had the idea to use Eclipse to import the project from GitLab.

Once the project is imported correctly, I made the comparison between the configuration of :

  • the project's Git ripository that I imported into Eclispe, ("in Eclipse", Git Repository, in myprojectRepo / Working Directory / .git / config)
  • the one that is made in .git / config, there i wanted to push my project with git: git push ... and asked me for a password.

Surprise: The remote does not have the same in both cases. I handed the same as that in eclipse and everything works.

Spring RequestMapping for controllers that produce and consume JSON

You shouldn't need to configure the consumes or produces attribute at all. Spring will automatically serve JSON based on the following factors.

  • The accepts header of the request is application/json
  • @ResponseBody annotated method
  • Jackson library on classpath

You should also follow Wim's suggestion and define your controller with the @RestController annotation. This will save you from annotating each request method with @ResponseBody

Another benefit of this approach would be if a client wants XML instead of JSON, they would get it. They would just need to specify xml in the accepts header.

ASP.NET Identity reset password

string message = null;
//reset the password
var result = await IdentityManager.Passwords.ResetPasswordAsync(model.Token, model.Password);
if (result.Success)
{
    message = "The password has been reset.";
    return RedirectToAction("PasswordResetCompleted", new { message = message });
}
else
{
    AddErrors(result);
}

This snippet of code is taken out of the AspNetIdentitySample project available on github

Curl error: Operation timed out

Some time this error in Joomla appear because some thing incorrect with SESSION or coockie. That may because incorrect HTTPd server setting or because some before CURL or Server http requests

so PHP code like:

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
  curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

will need replace to PHP code

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
  //if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

May be some body reply how this options connected with "Curl error: Operation timed out after .."

Launch Pycharm from command line (terminal)

You're right that the JetBrains help page isn't very clear. On OS X, you'll want to use the launcher at:

/Applications/PyCharm.app/Contents/MacOS/pycharm

Or, for community edition:

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm

Unfortunately, adding a symlink to this binary wouldn't work for me (the launcher would crash). Setting an alias worked, though. Add this in your .bash_profile (or whatever shell you use):

alias pycharm="/Applications/PyCharm CE.app/Contents/MacOS/pycharm"

Then, you can run commands with simply pycharm.

With this you can do things like open a project:

pycharm ~/repos/my-project

Or open a specific line of a file in a project:

pycharm ~/repos/my-project --line 42 ~/repos/my-project/script.py

Or view the diff of two files (they don't need to be part of a project):

pycharm ~/some_file.txt ~/Downloads/some_other_file.txt

Note that I needed to pass absolute paths to those files or PyCharm couldn't find them..

What is the difference between `new Object()` and object literal notation?

Also, according to some of the O'Really javascript books....(quoted)

Another reason for using literals as opposed to the Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.

Chrome sendrequest error: TypeError: Converting circular structure to JSON

One approach is to strip object and functions from main object. And stringify the simpler form

function simpleStringify (object){
    var simpleObject = {};
    for (var prop in object ){
        if (!object.hasOwnProperty(prop)){
            continue;
        }
        if (typeof(object[prop]) == 'object'){
            continue;
        }
        if (typeof(object[prop]) == 'function'){
            continue;
        }
        simpleObject[prop] = object[prop];
    }
    return JSON.stringify(simpleObject); // returns cleaned up JSON
};

Access PHP variable in JavaScript

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

Strip spaces/tabs/newlines - python

Since there is not anything else that was more intricate, I wanted to share this as it helped me out.

This is what I originally used:

import requests
import re

url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
print("{}".format(r.content))

Undesired Result:

b'<!DOCTYPE html>\r\n\r\n\r\n    <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive">\r\n\r\n    <head>\r\n\r\n        <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>\r\n        <link

This is what I changed it to:

import requests
import re

url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
regex = r'\s+'
print("CNT: {}".format(re.sub(regex, " ", r.content.decode('utf-8'))))

Desired Result:

<!DOCTYPE html> <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive"> <head> <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>

The precise regex that @MattH had mentioned, was what worked for me in fitting it into my code. Thanks!

Note: This is python3

Delete all but the most recent X files in bash

found interesting cmd in Sed-Onliners - Delete last 3 lines - fnd it perfect for another way to skin the cat (okay not) but idea:

 #!/bin/bash
 # sed cmd chng #2 to value file wish to retain

 cd /opt/depot 

 ls -1 MyMintFiles*.zip > BigList
 sed -n -e :a -e '1,2!{P;N;D;};N;ba' BigList > DeList

 for i in `cat DeList` 
 do 
 echo "Deleted $i" 
 rm -f $i  
 #echo "File(s) gonzo " 
 #read junk 
 done 
 exit 0

Postgresql - unable to drop database because of some auto connections to DB

REVOKE CONNECT will not prevent the connections from the db owner or superuser. So if you don't want anyone to connect the db, follow command may be useful.

alter database pilot allow_connections = off;

Then use:

SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'pilot';

How do I pass a variable to the layout using Laravel' Blade templating?

$data['title'] = $this->layout->title = 'The Home Page';
$this->layout->content = View::make('home', $data);

I've done this so far because I needed in both the view and master file. It seems if you don't use $this->layout->title it won't be available in the master layout. Improvements welcome!

copy all files and folders from one drive to another drive using DOS (command prompt)

xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y

Use the above command. It will definitely work.

In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:

  • /h copies hidden and system files also
  • /i if destination does not exist and copying more than one file, assume that destination must be a directory
  • /c continue copying even if error occurs
  • /k copies attributes
  • /e copies directories and subdirectories, including empty ones
  • /r overwrites read-only files
  • /y suppress prompting to confirm whether you want to overwrite a file

How to get the first line of a file in a bash script?

The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:

# best:
head -n1 $bigfile >/dev/null

# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null

# VERY slow:
sed -n '1p' $bigfile >/dev/null

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

The hexadecimal value you are looking for is %2B

To get it automatically in PHP run your string through urlencode($stringVal). And then run it rhough urldecode($stringVal) to get it back.

If you want the JavaScript to handle it, use escape( str )

Edit

After @bobince's comment I did more reading and he is correct. Use encodeURIComponent(str) and decodeURIComponent(str). Escape will not convert the characters, only escape them with \'s

How can I clone a private GitLab repository?

Before doing

git clone https://example.com/root/test.git

make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .

Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.

How do I hide the PHP explode delimiter from submitted form results?

Instead of adding the line breaks with nl2br() and then removing the line breaks with explode(), try using the line break character '\r' or '\n' or '\r\n'.

<?php     $options= file_get_contents("employees.txt");     $options=explode("\n",$options);        // try \r as well.      foreach ($options as $singleOption){         echo "<option value='".$singleOption."'>".$singleOption."</option>";     }   ?> 

This could also fix the issue if the problem was due to Google Spreadsheets reading the line breaks.

how to get the selected index of a drop down

the actual index is available as a property of the select element.

var sel = document.getElementById('CCards');
alert(sel.selectedIndex);

you can use the index to get to the selection option, where you can pull the text and value.

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);

In Java, what is the best way to determine the size of an object?

There isn't a method call, if that's what you're asking for. With a little research, I suppose you could write your own. A particular instance has a fixed sized derived from the number of references and primitive values plus instance bookkeeping data. You would simply walk the object graph. The less varied the row types, the easier.

If that's too slow or just more trouble than it's worth, there's always good old-fashioned row counting rule-of-thumbs.

Set proxy through windows command line including login parameters

cmd

Tunnel all your internet traffic through a socks proxy:

netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"

View the current proxy settings:

netsh winhttp show proxy

Clear all proxy settings:

netsh winhttp reset proxy

Set default syntax to different filetype in Sublime Text 2

In ST2 there's a package you can install called Default FileType which does just that.

More info here.

Redeploy alternatives to JRebel

I have been working on an open source project that allows you to hot replace classes over and above what hot swap allows: https://github.com/fakereplace/fakereplace

It may or may not work for you, but any feedback is appreciated

Date format in dd/MM/yyyy hh:mm:ss

This can be done as follows :

select CONVERT(VARCHAR(10), GETDATE(), 103) + ' '  + convert(VARCHAR(8), GETDATE(), 14)

Hope it helps

How to check file MIME type with javascript before upload?

If you just want to check if the file uploaded is an image you can just try to load it into <img> tag an check for any error callback.

Example:

var input = document.getElementsByTagName('input')[0];
var reader = new FileReader();

reader.onload = function (e) {
    imageExists(e.target.result, function(exists){
        if (exists) {

            // Do something with the image file.. 

        } else {

            // different file format

        }
    });
};

reader.readAsDataURL(input.files[0]);


function imageExists(url, callback) {
    var img = new Image();
    img.onload = function() { callback(true); };
    img.onerror = function() { callback(false); };
    img.src = url;
}

Unable to set data attribute using jQuery Data() API

It is mentioned in the .data() documentation

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

This was also covered on Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

The demo on my original answer below doesn't seem to work any more.

Updated answer

Again, from the .data() documentation

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

So for <div data-role="page"></div> the following is true $('div').data('role') === 'page'

I'm fairly sure that $('div').data('data-role') worked in the past but that doesn't seem to be the case any more. I've created a better showcase which logs to HTML rather than having to open up the Console and added an additional example of the multi-hyphen to camelCase data- attributes conversion.

Updated demo (2015-07-25)

Also see jQuery Data vs Attr?

HTML

<div id="changeMe" data-key="luke" data-another-key="vader"></div>
<a href="#" id="changeData"></a>
<table id="log">
    <tr><th>Setter</th><th>Getter</th><th>Result of calling getter</th><th>Notes</th></tr>
</table>

JavaScript (jQuery 1.6.2+)

var $changeMe = $('#changeMe');
var $log = $('#log');

var logger;
(logger = function(setter, getter, note) {
    note = note || '';
    eval('$changeMe' + setter);
    var result = eval('$changeMe' + getter);
    $log.append('<tr><td><code>' + setter + '</code></td><td><code>' + getter + '</code></td><td>' + result + '</td><td>' + note + '</td></tr>');
})('', ".data('key')", "Initial value");

$('#changeData').click(function() {
    // set data-key to new value
    logger(".data('key', 'leia')", ".data('key')", "expect leia on jQuery node object but DOM stays as luke");
    // try and set data-key via .attr and get via some methods
    logger(".attr('data-key', 'yoda')", ".data('key')", "expect leia (still) on jQuery object but DOM now yoda");
    logger("", ".attr('key')", "expect undefined (no attr <code>key</code>)");
    logger("", ".attr('data-key')", "expect yoda in DOM and on jQuery object");

    // bonus points
    logger('', ".data('data-key')", "expect undefined (cannot get via this method)");
    logger(".data('anotherKey')", ".data('anotherKey')", "jQuery 1.6+ get multi hyphen <code>data-another-key</code>");
    logger(".data('another-key')", ".data('another-key')", "jQuery < 1.6 get multi hyphen <code>data-another-key</code> (also supported in jQuery 1.6+)");

    return false;
});

$('#changeData').click();

Older demo


Original answer

For this HTML:

<div id="foo" data-helptext="bar"></div>
<a href="#" id="changeData">change data value</a>

and this JavaScript (with jQuery 1.6.2)

console.log($('#foo').data('helptext'));

$('#changeData').click(function() {
    $('#foo').data('helptext', 'Testing 123');
//  $('#foo').attr('data-helptext', 'Testing 123');
    console.log($('#foo').data('data-helptext'));
    return false;
});

See demo

Using the Chrome DevTools Console to inspect the DOM, the $('#foo').data('helptext', 'Testing 123'); does not update the value as seen in the Console but $('#foo').attr('data-helptext', 'Testing 123'); does.

How to set alignment center in TextBox in ASP.NET?

You can use:

<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>

Or this:

textbox.Style["text-align"] = "center"; //right, left

Check whether a table contains rows or not sql server 2005

FOR the best performance, use specific column name instead of * - for example:

SELECT TOP 1 <columnName> 
FROM <tableName> 

This is optimal because, instead of returning the whole list of columns, it is returning just one. That can save some time.

Also, returning just first row if there are any values, makes it even faster. Actually you got just one value as the result - if there are any rows, or no value if there is no rows.

If you use the table in distributed manner, which is most probably the case, than transporting just one value from the server to the client is much faster.

You also should choose wisely among all the columns to get data from a column which can take as less resource as possible.

An array of List in c#

use

List<int>[] a = new List<int>[100];

How to get the public IP address of a user in C#

For Web Applications ( ASP.NET MVC and WebForm )

/// <summary>
/// Get current user ip address.
/// </summary>
/// <returns>The IP Address</returns>
public static string GetUserIPAddress()
{
    var context = System.Web.HttpContext.Current;
    string ip = String.Empty;

    if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
        ip = context.Request.UserHostAddress;

    if (ip == "::1")
        ip = "127.0.0.1";

    return ip;
}

For Windows Applications ( Windows Form, Console, Windows Service , ... )

    static void Main(string[] args)
    {
        HTTPGet req = new HTTPGet();
        req.Request("http://checkip.dyndns.org");
        string[] a = req.ResponseBody.Split(':');
        string a2 = a[1].Substring(1);
        string[] a3=a2.Split('<');
        string a4 = a3[0];
        Console.WriteLine(a4);
        Console.ReadLine();
    }

Configuring ObjectMapper in Spring

Above Spring 4, there is no need to configure MappingJacksonHttpMessageConverter if you only intend to configure ObjectMapper.

(configure MappingJacksonHttpMessageConverter will cause you to lose other MessageConverter)

You just need to do:

public class MyObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 4219938065516862637L;

    public MyObjectMapper() {
        super();
        enable(SerializationFeature.INDENT_OUTPUT);
    }       
}

And in your Spring configuration, create this bean:

@Bean 
public MyObjectMapper myObjectMapper() {        
    return new MyObjectMapper();
}

Why is an OPTIONS request sent and can I disable it?

For a developer who understands the reason it exists but needs to access an API that doesn't handle OPTIONS calls without auth, I need a temporary answer so I can develop locally until the API owner adds proper SPA CORS support or I get a proxy API up and running.

I found you can disable CORS in Safari and Chrome on a Mac.

Disable same origin policy in Chrome

Chrome: Quit Chrome, open an terminal and paste this command: open /Applications/Google\ Chrome.app --args --disable-web-security --user-data-dir

Safari: Disabling same-origin policy in Safari

If you want to disable the same-origin policy on Safari (I have 9.1.1), then you only need to enable the developer menu, and select "Disable Cross-Origin Restrictions" from the develop menu.

MySQL equivalent of DECODE function in Oracle

If additional table doesn't fit, you can write your own function for translation.

The plus of sql function over case is, that you can use it in various places, and keep translation logic in one place.

How do I change the JAVA_HOME for ant?

JAVA_HOME needs to point to a JDK home if you're trying to compile code. Check to see if '/usr/tomcat/jre/bin/javac' exists. I doubt it does.

If you don't have a JDK, then you can work around it by getting the ECJ (eclipse compiler) library, dropping it into '~/.ant/lib' and adding a system property to the command-line to use that compiler - check the Ant manual for details.

http://ant.apache.org/