Programs & Examples On #Nmea

National Marine Electronics Association (NMEA)

How do I make WRAP_CONTENT work on a RecyclerView

UPDATE 02.07.2020
This method may prevent recycling and should not be used on large data sets.

UPDATE 05.07.2019

If you are using RecyclerView inside a ScrollView, just change ScrollView to androidx.core.widget.NestedScrollView. Inside this view there is no need to pack RecyclerView inside a RelativeLayout.

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- other views -->

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <!-- other views -->

    </LinearLayout>

</androidx.core.widget.NestedScrollView>

Finally found the solution for this problem.

All you need to do is wrap the RecyclerView in a RelativeLayout. Maybe there are other Views which may also work.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

App crashing when trying to use RecyclerView on android 5.0

using fragment

writing code in onCreateView()

RecyclerView recyVideo = view.findViewById(R.id.recyVideoFag);

using activity

writing code in onCreate() RecyclerView recyVideo = findViewById(R.id.recyVideoFag);

android.content.res.Resources$NotFoundException: String resource ID #0x0

If we get the value as int and we set it to String, the error occurs. PFB my solution,

Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));

onMeasure custom view explanation

If you don't need to change something onMeasure - there's absolutely no need for you to override it.

Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).

You can check the onMeasure method here :

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
    case MeasureSpec.UNSPECIFIED:
        result = size;
        break;
    case MeasureSpec.AT_MOST:
    case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result;
}

Overriding SDK code to be replaced with the exact same code makes no sense.

This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.

Get screen width and height in Android

Display display = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int mWidthScreen = display.getWidth();
int mHeightScreen = display.getHeight();

ValueError: setting an array element with a sequence

From the code you showed us, the only thing we can tell is that you are trying to create an array from a list that isn't shaped like a multi-dimensional array. For example

numpy.array([[1,2], [2, 3, 4]])

or

numpy.array([[1,2], [2, [3, 4]]])

will yield this error message, because the shape of the input list isn't a (generalised) "box" that can be turned into a multidimensional array. So probably UnFilteredDuringExSummaryOfMeansArray contains sequences of different lengths.

Edit: Another possible cause for this error message is trying to use a string as an element in an array of type float:

numpy.array([1.2, "abc"], dtype=float)

That is what you are trying according to your edit. If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which enables the array to hold arbitrary Python objects:

numpy.array([1.2, "abc"], dtype=object)

Without knowing what your code shall accomplish, I can't judge if this is what you want.

Android center view in FrameLayout doesn't work

I'd suggest a RelativeLayout instead of a FrameLayout.

Assuming that you want to have the TextView always below the ImageView I'd use following layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:src="@drawable/icon"
        android:visibility="visible"/>
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_below="@id/imageview"
        android:gravity="center"
        android:text="@string/hello"/>
</RelativeLayout>

Note that if you set the visibility of an element to gone then the space that element would consume is gone whereas when you use invisible instead the space it'd consume will be preserved.

If you want to have the TextView on top of the ImageView then simply leave out the android:layout_alignParentTop or set it to false and on the TextView leave out the android:layout_below="@id/imageview" attribute. Like this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="false"
        android:layout_centerInParent="true"
        android:src="@drawable/icon"
        android:visibility="visible"/>
    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="@string/hello"/>
</RelativeLayout>

I hope this is what you were looking for.

Custom ImageView with drop shadow

I manage to apply gradient border using this code..

public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (leftRightThk * 2);
    int newH = h - (bottomThk + padTop);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Left
    int leftMargin = (leftRightThk + 7)/2;
    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
    paint.setShader(lshader);
    c.drawRect(0, padTop, leftMargin, newH, paint); 

    // Right
    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, padTop, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
    c.drawBitmap(sbmp, leftRightThk, 0, null);

    return bmp;
}

hope this helps !

How to size an Android view based on its parent's dimensions

Try this

int parentWidth = ((parentViewType)childView.getParent()).getWidth();
int parentHeight = ((parentViewType)childView.getParent()).getHeight();

then you can use LinearLayout.LayoutParams for setting the chileView's parameters

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(childWidth,childLength);
childView.setLayoutParams(params);

How to convert latitude or longitude to meters?

To convert latitude and longitude in x and y representation you need to decide what type of map projection to use. As for me, Elliptical Mercator seems very well. Here you can find an implementation (in Java too).

Invalid self signed SSL cert - "Subject Alternative Name Missing"

Here is a very simple way to create an IP certificate that Chrome will trust.

The ssl.conf file...

[ req ]
default_bits       = 4096
distinguished_name = req_distinguished_name
req_extensions     = req_ext
prompt             = no

[ req_distinguished_name ]
commonName                  = 192.168.1.10

[ req_ext ]
subjectAltName = IP:192.168.1.10

Where, of course 192.168.1.10 is the local network IP we want Chrome to trust.

Create the certificate:

openssl genrsa -out key1.pem
openssl req -new -key key1.pem -out csr1.pem -config ssl.conf
openssl x509 -req -days 9999 -in csr1.pem -signkey key1.pem -out cert1.pem -extensions req_ext -extfile ssl.conf
rm csr1.pem

On Windows import the certificate into the Trusted Root Certificate Store on all client machines. On Android Phone or Tablet download the certificate to install it. Now Chrome will trust the certificate on windows and Android.

On windows dev box the best place to get openssl.exe is from "c:\Program Files\Git\usr\bin\openssl.exe"

How to enable curl in Wamp server

I got the same issue and this solved it for me. Perhaps this might be a fix for your problem too.

Here is the fix. Follow this link http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/

Go to "Fixed curl extensions" and download the extension that matches your PHP version.

Extract and copy "php_curl.dll" to the extension directory of your wamp installation. (i.e. C:\wamp\bin\php\php5.3.13\ext)

Restart Apache

Done!

Refer to: http://blog.nterms.com/2012/07/php-curl-issues-with-wamp-server-on.html

Cheers!

How to retrieve the hash for the current commit in Git?

On git bash, simply run $ git log -1

you will see, these lines following your command.

commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)

d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.

SQL Server: Is it possible to insert into two tables at the same time?

//if you want to insert the same as first table

$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";

$result = @mysql_query($qry);

$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";

$result = @mysql_query($qry2);

//or if you want to insert certain parts of table one

 $qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";


  $result = @mysql_query($qry);

 $qry2 = "INSERT INTO table2 (two) VALUES('$two')";

 $result = @mysql_query($qry2);

//i know it looks too good to be right, but it works and you can keep adding query's just change the

    "$qry"-number and number in @mysql_query($qry"")

I have 17 tables this has worked in.

How to thoroughly purge and reinstall postgresql on ubuntu?

Following ae the steps i followed to uninstall and reinstall. Which worked for me.

First remove the installed postgres :-

sudo apt-get purge postgr*

sudo apt-get autoremove

Then install 'synaptic':

sudo apt-get install synaptic

sudo apt-get update

Then install postgres

sudo apt-get install postgresql postgresql-contrib

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

Error - Unable to access the IIS metabase

Open visual studio command prompt and type below command and run

aspnet_regiis -ga machinename\ASPNET

After running the above command Reset the IIS and test the application that resolve your issue.

If above command doesn’t resolve your problem then try to run below command in visual studio command prompt:-

aspnet_regiis -i

Alternatively we can run above command from our windows command prompt also

Go to the Start menu and open Run and enter and click OK

%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe –I

After that Reset the IIS and test the application that resolves your issue

Get size of folder or file

public long folderSize (String directory)
    {
        File curDir = new File(directory);
        long length = 0;
        for(File f : curDir.listFiles())
        {
            if(f.isDirectory())
            {               
                 for ( File child : f.listFiles()) 
                 {
                     length = length + child.length();
                 }

                System.out.println("Directory: " + f.getName() + " " + length + "kb");
            }
            else
            {
                length = f.length();
                System.out.println("File: " + f.getName() + " " + length + "kb");
            }
            length = 0;
        }
        return length;
    }

How to center a button within a div?

Using flexbox

.Center {
  display: flex;
  align-items: center;
  justify-content: center;
}

And then adding the class to your button.

<button class="Center">Demo</button> 

How to change background color in the Notepad++ text editor?

You may need admin access to do it on your system.

  1. Create a folder 'themes' in the Notepad++ installation folder i.e. C:\Program Files (x86)\Notepad++
  2. Search or visit pages like http://timtrott.co.uk/notepad-colour-schemes/ to download the favourite theme. It will be an SML file.
    • Note: I prefer Neon any day.
  3. Download the themes from the site and drag them to the themes folder.
    • Note: I was unable to copy-paste or create new files in 'themes' folder so I used drag and that worked.
  4. Follow the steps provided by @triforceofcourage to select the new theme in Notepad++ preferences.

How to run function of parent window when child window closes?

This is an old post, but I thought I would add another method to do this:

var win = window.open("http://www.google.com");

var winClosed = setInterval(function () {

    if (win.closed) {
        clearInterval(winClosed);
        foo(); //Call your function here
    }

}, 250);

You don't have to modify the contents or use any event handlers from the child window.

How to calculate the width of a text string of a specific font and font-size?

This simple extension in Swift works well.

extension String {
    func size(OfFont font: UIFont) -> CGSize {
        return (self as NSString).size(attributes: [NSFontAttributeName: font])
    }
}

Usage:

let string = "hello world!"
let font = UIFont.systemFont(ofSize: 12)
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32}

Commit history on remote repository

Here's a bash function that makes it easy to view the logs on a remote. It takes two optional arguments. The first one is the branch, it defaults to master. The second one is the remote, it defaults to staging.

git_log_remote() {
  branch=${1:-master}
  remote=${2:-staging}
  
  git fetch $remote
  git checkout $remote/$branch
  git log
  git checkout -
}

examples:

 $ git_log_remote
 $ git_log_remote development origin

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

Go to Phone Settings --> Developer Options --> Simulate Secondary Displays and turn it to None. If you don't see Developer Options in the settings menu (it should be at the bottom, go Settings ==> About phone and tap on the Build number a lot of times)

Adjust UILabel height depending on the text

To do this in Swift3 following is the code:

 let labelSizeWithFixedWith = CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)
            let exactLabelsize = self.label.sizeThatFits(labelSizeWithFixedWith)
            self.label.frame = CGRect(origin: CGPoint(x: 20, y: 20), size: exactLabelsize)

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

I think this could be useful for you.

_x000D_
_x000D_
const myObject = {_x000D_
   "a":"a",_x000D_
   "b":{_x000D_
      "c":"c",_x000D_
      "d":{_x000D_
         "e":"e",_x000D_
         "f":{_x000D_
            "g":"g",_x000D_
            "h":{_x000D_
               "i":"i"_x000D_
            }_x000D_
         }_x000D_
      }_x000D_
   }_x000D_
};_x000D_
_x000D_
console.log(JSON.stringify(myObject, null, '\t'));
_x000D_
_x000D_
_x000D_

As mentioned in this answer:

JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces).

Use Fieldset Legend with bootstrap

I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.

_x000D_
_x000D_
.text-on-pannel {_x000D_
  background: #fff none repeat scroll 0 0;_x000D_
  height: auto;_x000D_
  margin-left: 20px;_x000D_
  padding: 3px 5px;_x000D_
  position: absolute;_x000D_
  margin-top: -47px;_x000D_
  border: 1px solid #337ab7;_x000D_
  border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
  /* for text on pannel */_x000D_
  margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
  padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
  <div class="panel panel-primary">_x000D_
    <div class="panel-body">_x000D_
      <h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
      <p> Your Code </p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div>
_x000D_
_x000D_
_x000D_

This will give below look. enter image description here

Note: We need to change the styles in order to use different header size.

How do I copy a folder from remote to local using scp?

In case you run into "Too many authentication failures", specify the exact SSH key you have added to your severs ssh server:

scp -r -i /path/to/local/key [email protected]:/path/to/folder /your/local/target/dir

I'm getting favicon.ico error

The answers above didn't work for me. I found a very good article for Favicon, explaining:

  • what is a Favicon;
  • why does Favicon.ico show up as a 404 in the log files;
  • why should You use a Favicon;
  • how to make a Favicon using FavIcon from Pics or other Favicon creator;
  • how to get Your Favicon to show.

So I created Favicon using FavIcon from Pics. Put it in folder (named favicon) and add this code in <head> tag:

<link rel="shortcut icon" href="favicon/favicon.ico">
<link rel="icon" type="image/gif" href="favicon/animated_favicon1.gif">

Now there is no error and I see my Favicon:

enter image description here

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

Why do I need to configure the SQL dialect of a data source?

Databases implement subtle differences in the SQL they use. Things such as data types for example vary across databases (e.g. in Oracle You might put an integer value in a number field and in SQL Server use an int field). Or database specific functionality - selecting the top n rows is different depending on the database. The dialect abstracts this so you don't have to worry about it.

Initialize 2D array

Easy to read/type.

  table = new char[][] {
      "0123456789".toCharArray()
    , "abcdefghij".toCharArray()
  };

Measure the time it takes to execute a t-sql query

If you want a more accurate measurement than the answer above:

set statistics time on 

-- Query 1 goes here

-- Query 2 goes here

set statistics time off

The results will be in the Messages window.

Update (2015-07-29):

By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats that may also be of value:

-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.

-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';

SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0)) 
       AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
      (OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
      (DB_NAME(database_id)=@DbName OR @DbName IS NULL)

How to create Toast in Flutter?

just use SnackBar(content: Text("hello"),) inside any event like onTap and onPress

you can read more about Snackbar here https://flutter.dev/docs/cookbook/design/snackbars

What type of hash does WordPress use?

$hash_type$salt$password

If the hash does not use a salt, then there is no $ sign for that. The actual hash in your case is after the 2nd $

The reason for this is, so you can have many types of hashes with different salts and feeds that string into a function that knows how to match it with some other value.

Suppress console output in PowerShell

Try redirecting the output to Out-Null. Like so,

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

Another way-too-complicated workaround, with the benefit of not having to re-install the application as the previous workaround required. This requires that you have access to the msi (or a setup.exe with the msi embedded).

If you have Visual Studio 2012 (or possibly other editions) and install the free "InstallShield LE", then you can create a new setup project using InstallShield.

One of the configuration options in the "Organize your Setup" step is called "Upgrade Paths". Open the properties for Upgrade Paths, and in the left pane right click "Upgrade Paths" and select "New Upgrade Path" ... now browse to the msi (or setup.exe containing the msi) and click "open". The upgrade code will be populated for you in the settings page in the right pane which you should now see.

Best way to extract a subvector from a vector?

Maybe the array_view/span in the GSL library is a good option.

Here is also a single file implementation: array_view.

Maven – Always download sources and javadocs

Not sure, but you should be able to do something by setting a default active profile in your settings.xml

See

See http://maven.apache.org/guides/introduction/introduction-to-profiles.html

How to change Format of a Cell to Text using VBA

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

If you just want to delete the address assigned to the user and not to affect on User entity class you should try something like that:

@Entity
public class User {
   @OneToMany(mappedBy = "addressOwner", cascade = CascadeType.ALL)
   protected Set<Address> userAddresses = new HashSet<>();
}

@Entity 
public class Addresses {
   @ManyToOne(cascade = CascadeType.REFRESH) @JoinColumn(name = "user_id")
   protected User addressOwner;
}

This way you dont need to worry about using fetch in annotations. But remember when deleting the User you will also delete connected address to user object.

How does one get started with procedural generation?

You should probably start with a little theory and simple examples such as the midpoint displacement algorithm. You should also learn a little about Perlin Noise if you are interested in generating graphics. I used this to get me started with my final year project on procedural generation.

Fractals are closely related to procedural generation.

Terragen and SpeedTree will show you some amazing possibilities of procedural generation.

Procedural generation is a technique that can be used in any language (it is definitely not restricted to procedural languages such as C, as it can be used in OO languages such as Java, and Logic languages such as Prolog). A good understanding of recursion in any language will strengthen your grasp of Procedural Generation.

As for 'serious' or non-game code, procedural generation techniques have been used to:

  • simulate the growth of cities in order to plan for traffic management
  • to simulate the growth of blood vessels
  • SpeedTree is used in movies and architectural presentations

How are ssl certificates verified?

Here is a very simplified explanation:

  1. Your web browser downloads the web server's certificate, which contains the public key of the web server. This certificate is signed with the private key of a trusted certificate authority.

  2. Your web browser comes installed with the public keys of all of the major certificate authorities. It uses this public key to verify that the web server's certificate was indeed signed by the trusted certificate authority.

  3. The certificate contains the domain name and/or ip address of the web server. Your web browser confirms with the certificate authority that the address listed in the certificate is the one to which it has an open connection.

  4. Your web browser generates a shared symmetric key which will be used to encrypt the HTTP traffic on this connection; this is much more efficient than using public/private key encryption for everything. Your browser encrypts the symmetric key with the public key of the web server then sends it back, thus ensuring that only the web server can decrypt it, since only the web server has its private key.

Note that the certificate authority (CA) is essential to preventing man-in-the-middle attacks. However, even an unsigned certificate will prevent someone from passively listening in on your encrypted traffic, since they have no way to gain access to your shared symmetric key.

How are zlib, gzip and zip related? What do they have in common and how are they different?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

Running Facebook application on localhost

None of the answers above worked for me. I am running on FB API 2.5. Mine was a combination of issues that lead to success once resolved

  1. Create a test app to ensure that it is maintained and managed as such and can be disabled when going live
  2. Read the error message properly :) - I had to enable "Web OAuth Login" WITH "Client OAuth Login"
  3. Use https://www.whatismyip.com/ to find out what my current IP is
  4. Create an A record on my Domain i.e. http://localhost.mydomain.com that points to my current IP

It's probably not ideal as Dynamic IP's change and one could probably use DynDNS or something similar to make the IP more "static" but it worked for me

Extracting the top 5 maximum values in excel

Given a data setup like this:

Top 5 by criteria

The formula in cell D2 and copied down is:

=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))

This formula will work even if there are tied OPS scores among players.

How to get page content using cURL?

Get content with Curl php

request server support Curl function, enable in httpd.conf in folder Apache


function UrlOpener($url)
     global $output;
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     $output = curl_exec($ch); 
     curl_close($ch);    
     echo $output;

If get content by google cache use Curl you can use this url: http://webcache.googleusercontent.com/search?q=cache:Put your url Sample: http://urlopener.mixaz.net/

Python using enumerate inside list comprehension

Or, if you don't insist on using a list comprehension:

>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

How to send redirect to JSP page in Servlet

    String u = request.getParameter("username");
    String p = request.getParameter("password");

    try {
        st = con.createStatement();
        String sql;
        sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
                + p + "'";
        ResultSet rs = st.executeQuery(sql);
        if (rs.next()) {
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/home.jsp");
            requestDispatcher.forward(request, response);
        } else {

            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/invalidLogin.jsp");
            requestDispatcher.forward(request, response);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        try {
            rs.close();
            ps.close();
            con.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

Refresh/reload the content in Div using jquery/ajax

I know the topic is old, but you can declare the Ajax as a variable, then use a function to call the variable on the desired content. Keep in mind you are calling what you have in the Ajax if you want a different elements from the Ajax you need to specify it.

Example:

Var infogen = $.ajax({'your query')};

$("#refresh").click(function(){
  infogen;
  console.log("to verify");
});    

Hope helps

if not try:

$("#refresh").click(function(){
      loca.tion.reload();
      console.log("to verify");
    });    

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

python: restarting a loop

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.

perhaps a:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop  

How do I get a file's last modified time in Perl?

You need the stat call, and the file name:

my $last_mod_time = (stat ($file))[9];

Perl also has a different version:

my $last_mod_time = -M $file;

but that value is relative to when the program started. This is useful for things like sorting, but you probably want the first version.

How to create a JSON object

$post_data = [
  "item" => [
    'item_type_id' => $item_type,
    'string_key' => $string_key,
    'string_value' => $string_value,
    'string_extra' => $string_extra,
    'is_public' => $public,
    'is_public_for_contacts' => $public_contacts
  ]
];

$post_data = json_encode(post_data);
$post_data = json_decode(post_data);
return $post_data;

Xcode 'CodeSign error: code signing is required'

It happens when Xcode doesn't recognize your certificate.

It's just a pain in the ass to solve it, there are a lot of possibilities to help you.

But the first thing you should try is removing in the "Window" tab => Organizer, the provisioning that is in your device. Then re-add them (download them again on the apple website). And try to compile again.

By the way, did you check in the Project Info Window the "code signing identity" ?

Good Luck.

How can I escape a double quote inside double quotes?

Check out printf...

#!/bin/bash
mystr="say \"hi\""

Without using printf

echo -e $mystr

Output: say "hi"

Using printf

echo -e $(printf '%q' $mystr)

Output: say \"hi\"

Scatter plots in Pandas/Pyplot: How to plot by category

With plt.scatter, I can only think of one: to use a proxy artist:

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)

ccm=x.get_cmap()
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)]
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1)

And the result is:

enter image description here

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

Try Jochen Kalmbach's Memory Leak Detector on Code Project. The URL to the latest version was somewhere in the comments when I last checked.

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

For Ubuntu-like distro with your own git compiled: you might be missing libcurl4-openssl-dev. apt install libcurl4-openssl-dev then reconfigure, then make install

MongoDB vs Firebase

I will answer this question in terms of AngularFire, Firebase's library for Angular.

  1. Tl;dr: superpowers. :-)

  2. AngularFire's three-way data binding. Angular binds the view and the $scope, i.e., what your users do in the view automagically updates in the local variables, and when your JavaScript updates a local variable the view automagically updates. With Firebase the cloud database also updates automagically. You don't need to write $http.get or $http.put requests, the data just updates.

  3. Five-way data binding, and seven-way, nine-way, etc. I made a tic-tac-toe game using AngularFire. Two players can play together, with the two views updating the two $scopes and the cloud database. You could make a game with three or more players, all sharing one Firebase database.

  4. AngularFire's OAuth2 library makes authorization easy with Facebook, GitHub, Google, Twitter, tokens, and passwords.

  5. Double security. You can set up your Angular routes to require authorization, and set up rules in Firebase about who can read and write data.

  6. There's no back end. You don't need to make a server with Node and Express. Running your own server can be a lot of work, require knowing about security, require that someone do something if the server goes down, etc.

  7. Fast. If your server is in San Francisco and the client is in San Jose, fine. But for a client in Bangalore connecting to your server will be slower. Firebase is deployed around the world for fast connections everywhere.

add controls vertically instead of horizontally using flow layout

As I stated in comment i would use a box layout for this.

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout());

JButton button = new JButton("Button1");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

button = new JButton("Button2");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

button = new JButton("Button3");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(button);

add(panel);

Difference between PCDATA and CDATA in DTD

  • PCDATA is text that will be parsed by a parser. Tags inside the text will be treated as markup and entities will be expanded.
  • CDATA is text that will not be parsed by a parser. Tags inside the text will not be treated as markup and entities will not be expanded.

By default, everything is PCDATA. In the following example, ignoring the root, <bar> will be parsed, and it'll have no content, but one child.

<?xml version="1.0"?>
<foo>
<bar><test>content!</test></bar>
</foo>

When we want to specify that an element will only contain text, and no child elements, we use the keyword PCDATA, because this keyword specifies that the element must contain parsable character data – that is , any text except the characters less-than (<) , greater-than (>) , ampersand (&), quote(') and double quote (").

In the next example, <bar> contains CDATA. Its content will not be parsed and is thus <test>content!</test>.

<?xml version="1.0"?>
<foo>
<bar><![CDATA[<test>content!</test>]]></bar>
</foo>

There are several content models in SGML. The #PCDATA content model says that an element may contain plain text. The "parsed" part of it means that markup (including PIs, comments and SGML directives) in it is parsed instead of displayed as raw text. It also means that entity references are replaced.

Another type of content model allowing plain text contents is CDATA. In XML, the element content model may not implicitly be set to CDATA, but in SGML, it means that markup and entity references are ignored in the contents of the element. In attributes of CDATA type however, entity references are replaced.

In XML, #PCDATA is the only plain text content model. You use it if you at all want to allow text contents in the element. The CDATA content model may be used explicitly through the CDATA block markup in #PCDATA, but element contents may not be defined as CDATA per default.

In a DTD, the type of an attribute that contains text must be CDATA. The CDATA keyword in an attribute declaration has a different meaning than the CDATA section in an XML document. In a CDATA section all characters are legal (including <,>,&,' and " characters), except the ]]> end tag.

#PCDATA is not appropriate for the type of an attribute. It is used for the type of "leaf" text.

#PCDATA is prepended by a hash in the content model to distinguish this keyword from an element named PCDATA (which would be perfectly legal).

SELECT FOR UPDATE with SQL Server

Have you tried READPAST?

I've used UPDLOCK and READPAST together when treating a table like a queue.

Java Read Large Text File With 70million line of text

1) I am sure there is no difference speedwise, both use FileInputStream internally and buffering

2) You can take measurements and see for yourself

3) Though there's no performance benefits I like the 1.7 approach

try (BufferedReader br = Files.newBufferedReader(Paths.get("test.txt"), StandardCharsets.UTF_8)) {
    for (String line = null; (line = br.readLine()) != null;) {
        //
    }
}

4) Scanner based version

    try (Scanner sc = new Scanner(new File("test.txt"), "UTF-8")) {
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
        }
        // note that Scanner suppresses exceptions
        if (sc.ioException() != null) {
            throw sc.ioException();
        }
    }

5) This may be faster than the rest

try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
    ByteBuffer bb = ByteBuffer.allocateDirect(1000);
    for(;;) {
        StringBuilder line = new StringBuilder();
        int n = ch.read(bb);
        // add chars to line
        // ...
    }
}

it requires a bit of coding but it can be really faster because of ByteBuffer.allocateDirect. It allows OS to read bytes from file to ByteBuffer directly, without copying

6) Parallel processing would definitely increase speed. Make a big byte buffer, run several tasks that read bytes from file into that buffer in parallel, when ready find first end of line, make a String, find next...

Maven Error: Could not find or load main class

For me the problem was nothing to do with Maven but to do with how I was running the .jar. I wrote some code and packaged it as a .jar with Maven. I ran it with

java target/gs-maven-0.1.0.jar

and got the error in the OP. Actually you need the -jar option:

java -jar target/gs-maven-0.1.0.jar

How to increase IDE memory limit in IntelliJ IDEA on Mac?

As for the intellij2018 version I am using the following configuration for better performance

-server
-Xms1024m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-Dfile.encoding=UTF-8
-XX:+UseConcMarkSweepGC
-XX:+AggressiveOpts
-XX:+CMSClassUnloadingEnabled
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:CMSIncrementalDutyCycleMin=0
-XX:-TraceClassUnloading
-XX:+TieredCompilation
-XX:SoftRefLRUPolicyMSPerMB=100
-ea
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Djdk.http.auth.tunneling.disabledSchemes=""
-XX:+HeapDumpOnOutOfMemoryError
-XX:-OmitStackTraceInFastThrow
-Xverify:none

-XX:ErrorFile=$USER_HOME/java_error_in_idea_%p.log
-XX:HeapDumpPath=$USER_HOME/java_error_in_idea.hprof

Setting width and height

Use this, it works fine.

<canvas id="totalschart" style="height:400px;width: content-box;"></canvas>

and under options,

responsive:true,

CSS float right not working correctly

LIke this

final answer

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

demo1

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: gray;
    float: left;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

html

<h2>
Contact Details</h2>
<button type="button" class="edit_button" >My Button</button>

demo

html

<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray; float:left;">
Contact Details



</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>

How to stop java process gracefully?

Similar Question Here

Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.

The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.

Questions every good PHP Developer should be able to answer

Explain difference of

extract()

explode()

implode()

How to add border around linear layout except at the bottom?

Create an XML file named border.xml in the drawable folder and put the following code in it.

 <?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item> 
    <shape android:shape="rectangle">
      <solid android:color="#FF0000" /> 
    </shape>
  </item>   
    <item android:left="5dp" android:right="5dp"  android:top="5dp" >  
     <shape android:shape="rectangle"> 
      <solid android:color="#000000" />
    </shape>
   </item>    
 </layer-list> 

Then add a background to your linear layout like this:

         android:background="@drawable/border"

EDIT :

This XML was tested with a galaxy s running GingerBread 2.3.3 and ran perfectly as shown in image below:

enter image description here

ALSO

tested with galaxy s 3 running JellyBean 4.1.2 and ran perfectly as shown in image below :

enter image description here

Finally its works perfectly with all APIs

EDIT 2 :

It can also be done using a stroke to keep the background as transparent while still keeping a border except at the bottom with the following code.

<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:left="0dp" android:right="0dp"  android:top="0dp"  
        android:bottom="-10dp"> 
    <shape android:shape="rectangle">
     <stroke android:width="10dp" android:color="#B22222" />
    </shape>
   </item>  
 </layer-list> 

hope this help .

How to check whether a given string is valid JSON in Java

Here you can find a tool that can validate a JSON file, or you could just deserialize your JSON file with any JSON library and if the operation is successful then it should be valid (google-json for example that will throw an exception if the input it is parsing is not valid JSON).

how to open a jar file in Eclipse

Since the jar file 'executes' then it contains compiled java files known as .class files. You cannot import it to eclipse and modify the code. You should ask the supplier of the "demo" for the "source code". (or check the page you got the demo from for the source code)

Unless, you want to decompile the .class files and import to Eclipse. That may not be the case for starters.

XML string to XML document

Using Linq to xml

Add a reference to System.Xml.Linq

and use

XDocument.Parse(string xmlString)

Edit: Sample follows, xml data (TestConfig.xml)..

<?xml version="1.0"?>
<Tests>
  <Test TestId="0001" TestType="CMD">
    <Name>Convert number to string</Name>
    <CommandLine>Examp1.EXE</CommandLine>
    <Input>1</Input>
    <Output>One</Output>
  </Test>
  <Test TestId="0002" TestType="CMD">
    <Name>Find succeeding characters</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>abc</Input>
    <Output>def</Output>
  </Test>
  <Test TestId="0003" TestType="GUI">
    <Name>Convert multiple numbers to strings</Name>
    <CommandLine>Examp2.EXE /Verbose</CommandLine>
    <Input>123</Input>
    <Output>One Two Three</Output>
  </Test>
  <Test TestId="0004" TestType="GUI">
    <Name>Find correlated key</Name>
    <CommandLine>Examp3.EXE</CommandLine>
    <Input>a1</Input>
    <Output>b1</Output>
  </Test>
  <Test TestId="0005" TestType="GUI">
    <Name>Count characters</Name>
    <CommandLine>FinalExamp.EXE</CommandLine>
    <Input>This is a test</Input>
    <Output>14</Output>
  </Test>
  <Test TestId="0006" TestType="GUI">
    <Name>Another Test</Name>
    <CommandLine>Examp2.EXE</CommandLine>
    <Input>Test Input</Input>
    <Output>10</Output>
  </Test>
</Tests>

C# usage...

XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
    from el in root.Elements("Test")
    where (string)el.Element("CommandLine") == "Examp2.EXE"
    select el;
foreach (XElement el in tests)
    Console.WriteLine((string)el.Attribute("TestId"));

This code produces the following output: 0002 0006

How to force view controller orientation in iOS 8?

If you are using navigationViewController you should create your own superclass for this and override:

- (BOOL)shouldAutorotate {
  id currentViewController = self.topViewController;

  if ([currentViewController isKindOfClass:[SecondViewController class]])
    return NO;

  return YES;
}

this will disable rotation in SecondViewController but if you push your SecondViewController when your device is on portrait orientation then your SecondViewController will appear in portrait mode.

Assume that you are using storyboard. You have to create manual segue (How to) and in your "onClick" method:

- (IBAction)onPlayButtonClicked:(UIBarButtonItem *)sender {
  NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
  [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
  [self performSegueWithIdentifier:@"PushPlayerViewController" sender:self];
}

This will force landscape orientation before your superclass disable autorotate feature.

How to refresh the data in a jqGrid?

$('#grid').trigger( 'reloadGrid' );

How to specify jdk path in eclipse.ini on windows 8 when path contains space

Try to escape the space with back slash.. Like

C:\program\folder\ \name\java\jdk\bin

Testing Spring's @RequestBody using Spring MockMVC

I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...) but it would not work in my case.

I actually had a String in a JSON format, but I feel like it is literally transforming the toString() method of every field into JSON. In my case, a date LocalDate field would end up as:

"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}

which is not the best date format to send in a request ...

In the end, the simplest solution in my case is to use the Spring ObjectMapper. Its behaviour is better since it uses Jackson to build your JSON with complex types.

@Autowired
private ObjectMapper objectMapper;

and I simply used it in mytest:

mockMvc.perform(post("/api/")
                .content(objectMapper.writeValueAsString(...))
                .contentType(MediaType.APPLICATION_JSON)
);

How to fix the session_register() deprecated issue?

We just have to use @ in front of the deprecated function. No need to change anything as mentioned in above posts. For example: if(!@session_is_registered("username")){ }. Just put @ and problem is solved.

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

I am on XAMPP on Mac OS X, and Brian Lowe's solution above worked with a slight modification.

The mysql.sock file is actually in "/Applications/xampp/xamppfiles/var/mysql/" folder. So had to link it up both in /tmp and /var/mysql. I haven't checked which one is used by PHP command line, but this did the fix, so I am happy :-)

sudo su
ln -s /Applications/xampp/xamppfiles/var/mysql/mysql.sock /tmp/mysql.sock
mkdir /var/mysql
ln -s /Applications/xampp/xamppfiles/var/mysql/mysql.sock /var/mysql/mysql.sock

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

What is the best way to delete a value from an array in Perl?

Is this something you are going to be doing a lot? If so, you may want to consider a different data structure. Grep is going to search the entire array every time and for a large array could be quite costly. If speed is an issue then you may want to consider using a Hash instead.

In your example, the key would be the number and the value would be the count of elements of that number.

Insert json file into mongodb

It happened to me couple of weeks back. The version of mongoimport was too old. Once i Updated to latest version it ran successfully and imported all documents.

Reference: http://docs.mongodb.org/master/tutorial/install-mongodb-on-ubuntu/?_ga=1.11365492.1588529687.1434379875

Validate that a string is a positive integer

Simple

function isInteger(num) {
  return (num ^ 0) === num;
}

console.log(isInteger(1));

You can also extend Number and assign the function to it via prototype.

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

The user/host combination may have been created without password.

I was assuming that when adding a new host for an existing user (using a GUI app), the existing password would also be used for the new user/host combination.

I could log in with

mysql -u username -p PASSWORD

locally, but not from IPADDRESS with

mysql -u --host=HOST -p PASSWORD

(I could actually log in from IPADDRESS without using a password)

mysql -u --host=HOST

Setting the password allowed access:

set password for '<USER>'@'<IPADDRESS>' = '<PASSWORD>';

Multiple types were found that match the controller named 'Home'

i just deleted folder 'Bin' from server and copy my bin to server, and my problem solved.

Can a for loop increment/decrement by more than one?

A for loop:

for(INIT; TEST; ADVANCE) {
    BODY
}

Means the following:

INIT;
while (true) {
    if (!TEST)
        break;
    BODY;
    ADVANCE;
}

You can write almost any expression for INIT, TEST, ADVANCE, and BODY.

Do note that the ++ operators and variants are operators with side-effects (one should try to avoid them if you are not using them like i+=1 and the like):

  • ++i means i+=1; return i
  • i++ means oldI=i; i+=1; return oldI

Example:

> i=0
> [i++, i, ++i, i, i--, i, --i, i]
[0, 1, 2, 2, 2, 1, 0, 0]

Using CMake to generate Visual Studio C++ project files

CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.

Adding and removing source files is just a matter of modifying the CMakeLists.txt which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).

The following link explains CMake and Visual Studio specific behavior very well.

CMake and Visual Studio

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

The javax.mail-api artifact is only good for compiling against.

You actually need to run code, so you need a complete implementation of JavaMail API. Use this:

<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

NOTE: The version number will probably differ. Check the latest version here.

jQuery - add additional parameters on submit (NOT ajax)

You can even use this one. worked well for me

$("#registerform").attr("action", "register.php?btnsubmit=Save") 
$('#registerform').submit();

this will submit btnsubmit =Save as GET value to register.php form.

Convert integer to hexadecimal and back again

I created my own solution for converting int to Hex string and back before I found this answer. Not surprisingly, it's considerably faster than the .net solution since there's less code overhead.

        /// <summary>
        /// Convert an integer to a string of hexidecimal numbers.
        /// </summary>
        /// <param name="n">The int to convert to Hex representation</param>
        /// <param name="len">number of digits in the hex string. Pads with leading zeros.</param>
        /// <returns></returns>
        private static String IntToHexString(int n, int len)
        {
            char[] ch = new char[len--];
            for (int i = len; i >= 0; i--)
            {
                ch[len - i] = ByteToHexChar((byte)((uint)(n >> 4 * i) & 15));
            }
            return new String(ch);
        }

        /// <summary>
        /// Convert a byte to a hexidecimal char
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private static char ByteToHexChar(byte b)
        {
            if (b < 0 || b > 15)
                throw new Exception("IntToHexChar: input out of range for Hex value");
            return b < 10 ? (char)(b + 48) : (char)(b + 55);
        }

        /// <summary>
        /// Convert a hexidecimal string to an base 10 integer
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static int HexStringToInt(String str)
        {
            int value = 0;
            for (int i = 0; i < str.Length; i++)
            {
                value += HexCharToInt(str[i]) << ((str.Length - 1 - i) * 4);
            }
            return value;
        }

        /// <summary>
        /// Convert a hex char to it an integer.
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private static int HexCharToInt(char ch)
        {
            if (ch < 48 || (ch > 57 && ch < 65) || ch > 70)
                throw new Exception("HexCharToInt: input out of range for Hex value");
            return (ch < 58) ? ch - 48 : ch - 55;
        }

Timing code:

static void Main(string[] args)
        {
            int num = 3500;
            long start = System.Diagnostics.Stopwatch.GetTimestamp();
            for (int i = 0; i < 2000000; i++)
                if (num != HexStringToInt(IntToHexString(num, 3)))
                    Console.WriteLine(num + " = " + HexStringToInt(IntToHexString(num, 3)));
            long end = System.Diagnostics.Stopwatch.GetTimestamp();
            Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);

            for (int i = 0; i < 2000000; i++)
                if (num != Convert.ToInt32(num.ToString("X3"), 16))
                    Console.WriteLine(i);
            end = System.Diagnostics.Stopwatch.GetTimestamp();
            Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);
            Console.ReadLine(); 
        }

Results:

Digits : MyCode : .Net
1 : 0.21 : 0.45
2 : 0.31 : 0.56
4 : 0.51 : 0.78
6 : 0.70 : 1.02
8 : 0.90 : 1.25

Is it possible in Java to catch two exceptions in the same catch block?

Java <= 6.x just allows you to catch one exception for each catch block:

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Documentation:

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.

For Java 7 you can have multiple Exception caught on one catch block:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Documentation:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

How to generate a range of numbers between two numbers?

Here's what I came up with:

create or alter function dbo.fn_range(@start int, @end int)  returns table
return
with u2(n) as (
    select n 
    from (VALUES (0),(1),(2),(3)) v(n)
), 
u8(n) as (
    select
        x0.n | x1.n * 4 | x2.n * 16 | x3.n * 64 as n
    from u2 x0, u2 x1, u2 x2, u2 x3
)
select 
    @start + s.n as n
from (
    select
        x0.n | isnull(x1.n, 0) * 256 | isnull(x2.n, 0) * 65536 as n
    from u8 x0 
    left join u8 x1 on @end-@start > 256
    left join u8 x2 on @end-@start > 65536
) s
where s.n < @end - @start

Generates up to 2^24 values. Join conditions keep it fast for small values.

How to add a touch event to a UIView?

Heres a Swift version:

// MARK: Gesture Extensions
extension UIView {

    func addTapGesture(#tapNumber: Int, target: AnyObject, action: Selector) {
        let tap = UITapGestureRecognizer (target: target, action: action)
        tap.numberOfTapsRequired = tapNumber
        addGestureRecognizer(tap)
        userInteractionEnabled = true
    }

    func addTapGesture(#tapNumber: Int, action: ((UITapGestureRecognizer)->())?) {
        let tap = BlockTap (tapCount: tapNumber, fingerCount: 1, action: action)
        addGestureRecognizer(tap)
        userInteractionEnabled = true
    }
}

How to open mail app from Swift

You can use simple mailto: links in iOS to open the mail app.

let email = "[email protected]"
if let url = URL(string: "mailto:\(email)") {
  if #available(iOS 10.0, *) {
    UIApplication.shared.open(url)
  } else {
    UIApplication.shared.openURL(url)
  }    
}

Extract code country from phone number [libphonenumber]

If the string containing the phone number will always start this way (+33 or another country code) you should use regex to parse and get the country code and then use the library to get the country associated to the number.

Best way to get value from Collection by index

You can get the value from collection using for-each loop or using iterator interface. For a Collection c for (<ElementType> elem: c) System.out.println(elem); or Using Iterator Interface

 Iterator it = c.iterator(); 
        while (it.hasNext()) 
        System.out.println(it.next()); 

PackagesNotFoundError: The following packages are not available from current channels:

Conda itself provides a quite detailed guidance about installing non-conda packages. Details can be found here: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-pkgs.html

The basic idea is to use conda-forge. If it doesn't work, activate the environment and use pip.

Adding timestamp to a filename with mv in BASH

The few lines you posted from your script look okay to me. It's probably something a bit deeper.

You need to find which line is giving you this error. Add set -xv to the top of your script. This will print out the line number and the command that's being executed to STDERR. This will help you identify where in your script you're getting this particular error.

BTW, do you have a shebang at the top of your script? When I see something like this, I normally expect its an issue with the Shebang. For example, if you had #! /bin/bash on top, but your bash interpreter is located in /usr/bin/bash, you'll see this error.

EDIT

New question: How can I save the file correctly in the first place, to avoid having to perform this fix every time I resend the file?

Two ways:

  1. Select the Edit->EOL Conversion->Unix Format menu item when you edit a file. Once it has the correct line endings, Notepad++ will keep them.
  2. To make sure all new files have the correct line endings, go to the Settings->Preferences menu item, and pull up the Preferences dialog box. Select the New Document/Default Directory tab. Under New Document and Format, select the Unix radio button. Click the Close button.

How do I use IValidatableObject?

Just to add a couple of points:

Because the Validate() method signature returns IEnumerable<>, that yield return can be used to lazily generate the results - this is beneficial if some of the validation checks are IO or CPU intensive.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if (this.Enable)
    {
        // ...
        if (this.Prop1 > this.Prop2)
        {
            yield return new ValidationResult("Prop1 must be larger than Prop2");
        }

Also, if you are using MVC ModelState, you can convert the validation result failures to ModelState entries as follows (this might be useful if you are doing the validation in a custom model binder):

var resultsGroupedByMembers = validationResults
    .SelectMany(vr => vr.MemberNames
                        .Select(mn => new { MemberName = mn ?? "", 
                                            Error = vr.ErrorMessage }))
    .GroupBy(x => x.MemberName);

foreach (var member in resultsGroupedByMembers)
{
    ModelState.AddModelError(
        member.Key,
        string.Join(". ", member.Select(m => m.Error)));
}

Converting array to list in Java

Even shorter:

List<Integer> list = Arrays.asList(1, 2, 3, 4);

PivotTable's Report Filter using "greater than"

I can't say how much this might help you, but just found a solution to something similar problem which I faced. In the Pivot-

  1. Right click and choose Pivot table options
  2. Choose the display option
  3. uncheck the first 'Show expand/Collapse buttons'
  4. check the 'Classic PivotTable Layout(enables dragging of fields in the grid)
  5. click ok.

This would refine the data. Then, I had just copy and pasted this data in a new tab wherein I had applied the filters to my Total column with values greater than certain percentage.

This did work in my case and hope it helps you too.

Python 3 Float Decimal Points/Precision

In a word, you can't.

3.65 cannot be represented exactly as a float. The number that you're getting is the nearest number to 3.65 that has an exact float representation.

The difference between (older?) Python 2 and 3 is purely due to the default formatting.

I am seeing the following both in Python 2.7.3 and 3.3.0:

In [1]: 3.65
Out[1]: 3.65

In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'

For an exact decimal datatype, see decimal.Decimal.

How to create a link to another PHP page

You can also used like this

<a href="<?php echo 'index.php'; ?>">Index Page</a>
<a href="<?php echo 'page2.php'; ?>">Page 2</a>

jQuery UI DatePicker to show month year only

Made a couple of refinements to BrianS's nearly perfect response above:

  1. I've regexed the value set on show because I think it does actually make it slightly more readable in this case (although note I'm using a slightly different format)

  2. My client wanted no calendar so I've added an on show / hide class addition to do that without affecting any other datepickers. The removal of the class is on a timer to avoid the table flashing back up as the datepicker fades out, which seems to be very noticeable in IE.

EDIT: One problem left to solve with this is that there is no way to empty the datepicker - clear the field and click away and it repopulates with the selected date.

EDIT2: I have not managed to solve this nicely (i.e. without adding a separate Clear button next to the input), so ended up just using this: https://github.com/thebrowser/jquery.ui.monthpicker - if anyone can get the standard UI one to do it that would be amazing.

    $('.typeof__monthpicker').datepicker({
        dateFormat: 'mm/yy',
        showButtonPanel:true,
        beforeShow: 
            function(input, dpicker)
            {                           
                if(/^(\d\d)\/(\d\d\d\d)$/.exec($(this).val()))
                {
                    var d = new Date(RegExp.$2, parseInt(RegExp.$1, 10) - 1, 1);

                    $(this).datepicker('option', 'defaultDate', d);
                    $(this).datepicker('setDate', d);
                }

                $('#ui-datepicker-div').addClass('month_only');
            },
        onClose: 
            function(dt, dpicker)
            {
                setTimeout(function() { $('#ui-datepicker-div').removeClass('month_only') }, 250);

                var m = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var y = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

                $(this).datepicker('setDate', new Date(y, m, 1));
            }
    });

You also need this style rule:

#ui-datepicker-div.month_only .ui-datepicker-calendar {
display:none
}

How do I extract a substring from a string until the second space is encountered?

Get the position of the first space:

int space1 = theString.IndexOf(' ');

The the position of the next space after that:

int space2 = theString.IndexOf(' ', space1 + 1);

Get the part of the string up to the second space:

string firstPart = theString.Substring(0, space2);

The above code put togehter into a one-liner:

string firstPart = theString.Substring(0, theString.IndexOf(' ', theString.IndexOf(' ') + 1));

How to make MySQL handle UTF-8 properly

These tips on MySQL and UTF-8 may be helpful. Unfortunately, they don't constitute a full solution, just common gotchas.

Reverse the ordering of words in a string

Reverse the entire string, then reverse the letters of each individual word.

After the first pass the string will be

s1 = "Z Y X si eman yM"

and after the second pass it will be

s1 = "Z Y X is name My"

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

If you would like to ignore case you could use the following:

String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
    //-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
    // strings are equal.
}

Why doesn't git recognize that my file has been changed, therefore git add not working

TL;DR; Are you even on the correct repository?

My story is bit funny but I thought it can happen with someone who might be having a similar scenario so sharing it here.

Actually on my machine, I had two separate git repositories repo1 and repo2 configured in the same root directory named source. These two repositories are essentially the repositories of two products I work off and on in my company. Now the thing is that as a standard guideline, the directory structure of source code of all the products is exactly the same in my company.

So without realizing I modified an exactly same named file in repo2 which I was supposed to change in repo1. So, I just kept running command git status on repo1 and it kept giving the same message

On branch master

nothing to commit, working directory clean

for half an hour. Then colleague of mine observed it as independent pair of eyes and brought this thing to my notice that I was in wrong but very similar looking repository. The moment I switched to repo1 Git started noticing the changed files.

Not so common case. But you never know!

Declaring a custom android UI element using XML

Great reference. Thanks! An addition to it:

If you happen to have a library project included which has declared custom attributes for a custom view, you have to declare your project namespace, not the library one's. Eg:

Given that the library has the package "com.example.library.customview" and the working project has the package "com.example.customview", then:

Will not work (shows the error " error: No resource identifier found for attribute 'newAttr' in package 'com.example.library.customview'" ):

<com.library.CustomView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.library.customview"
        android:id="@+id/myView"
        app:newAttr="value" />

Will work:

<com.library.CustomView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.customview"
        android:id="@+id/myView"
        app:newAttr="value" />

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

Pyspark does include a dropDuplicates() method, which was introduced in 1.4. https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.dropDuplicates

>>> from pyspark.sql import Row
>>> df = sc.parallelize([ \
...     Row(name='Alice', age=5, height=80), \
...     Row(name='Alice', age=5, height=80), \
...     Row(name='Alice', age=10, height=80)]).toDF()
>>> df.dropDuplicates().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
|  5|    80|Alice|
| 10|    80|Alice|
+---+------+-----+

>>> df.dropDuplicates(['name', 'height']).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
|  5|    80|Alice|
+---+------+-----+

Delete directory with files in it?

what's the easiest way to delete a directory with all it's files in it?

system("rm -rf ".escapeshellarg($dir));

How to list files in an android directory?

If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:

Android Q (10) ask permission to get access all storage. Scoped storage

I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.

How to get the absolute path to the public_html folder?

You just need to create an offset bypass to how far you want the backwards reading to go. So, we use getcwd() to get the path and explode (split into array) to fetch the data between $root and the ending of the path.

function getRoot($root = "public_html") {
    return explode($root, getcwd())[0].$root."/";
}

how to refresh my datagridview after I add new data

In the code of the button that saves the changes to the database eg the update button, add the following lines of code:

MyDataGridView.DataSource = MyTableBindingSource

MyDataGridView.Update()

MyDataGridView.RefreshEdit()

Python can't find module in the same folder

Your code is fine, I suspect your problem is how you are launching it.

You need to launch python from your '2014_07_13_test' directory.

Open up a command prompt and 'cd' into your '2014_07_13_test' directory.

For instance:

$ cd /path/to/2014_07_13_test
$ python test.py

If you cannot 'cd' into the directory like this you can add it to sys.path

In test.py:

import sys, os
sys.path.append('/path/to/2014_07_13_test')

Or set/edit the PYTHONPATH

And all should be well...

...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'

There is a better shebang you should use.

Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.

How to make a Java Generic method static?

You need to move type parameter to the method level to indicate that you have a generic method rather than generic class:

public class ArrayUtils {
    public static <T> E[] appendToArray(E[] array, E item) {
        E[] result = (E[])new Object[array.length+1];
        result[array.length] = item;
        return result;
    }
}

How to check if a textbox is empty using javascript

You can also check it using jQuery.. It's quite easy:

<html>
    <head>
        <title>jQuery: Check if Textbox is empty</title>
        <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
    </head>
    <body>
        <form name="form1" method="post" action="">
            <label for="city">City:</label>
            <input type="text" name="city" id="city">
        </form>
        <button id="check">Check</button>
        <script type="text/javascript">
             $('#check').click(function () {
                 if ($('#city').val() == '') {
                     alert('Empty!!!');
                 } else {
                     alert('Contains: ' + $('#city').val());
                 }
             });                
        </script>
    </body>
</html>

Validate SSL certificates with Python

You can use Twisted to verify certificates. The main API is CertificateOptions, which can be provided as the contextFactory argument to various functions such as listenSSL and startTLS.

Unfortunately, neither Python nor Twisted comes with a the pile of CA certificates required to actually do HTTPS validation, nor the HTTPS validation logic. Due to a limitation in PyOpenSSL, you can't do it completely correctly just yet, but thanks to the fact that almost all certificates include a subject commonName, you can get close enough.

Here is a naive sample implementation of a verifying Twisted HTTPS client which ignores wildcards and subjectAltName extensions, and uses the certificate-authority certificates present in the 'ca-certificates' package in most Ubuntu distributions. Try it with your favorite valid and invalid certificate sites :).

import os
import glob
from OpenSSL.SSL import Context, TLSv1_METHOD, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, OP_NO_SSLv2
from OpenSSL.crypto import load_certificate, FILETYPE_PEM
from twisted.python.urlpath import URLPath
from twisted.internet.ssl import ContextFactory
from twisted.internet import reactor
from twisted.web.client import getPage
certificateAuthorityMap = {}
for certFileName in glob.glob("/etc/ssl/certs/*.pem"):
    # There might be some dead symlinks in there, so let's make sure it's real.
    if os.path.exists(certFileName):
        data = open(certFileName).read()
        x509 = load_certificate(FILETYPE_PEM, data)
        digest = x509.digest('sha1')
        # Now, de-duplicate in case the same cert has multiple names.
        certificateAuthorityMap[digest] = x509
class HTTPSVerifyingContextFactory(ContextFactory):
    def __init__(self, hostname):
        self.hostname = hostname
    isClient = True
    def getContext(self):
        ctx = Context(TLSv1_METHOD)
        store = ctx.get_cert_store()
        for value in certificateAuthorityMap.values():
            store.add_cert(value)
        ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname)
        ctx.set_options(OP_NO_SSLv2)
        return ctx
    def verifyHostname(self, connection, x509, errno, depth, preverifyOK):
        if preverifyOK:
            if self.hostname != x509.get_subject().commonName:
                return False
        return preverifyOK
def secureGet(url):
    return getPage(url, HTTPSVerifyingContextFactory(URLPath.fromString(url).netloc))
def done(result):
    print 'Done!', len(result)
secureGet("https://google.com/").addCallback(done)
reactor.run()

Calculating the position of points in a circle

Working Solution in Java:

import java.awt.event.*;
import java.awt.Robot;

public class CircleMouse {

/* circle stuff */
final static int RADIUS = 100;
final static int XSTART = 500;
final static int YSTART = 500;
final static int DELAYMS = 1;
final static int ROUNDS = 5;

public static void main(String args[]) {

    long startT = System.currentTimeMillis();
    Robot bot = null;

    try {
        bot = new Robot();
    } catch (Exception failed) {
        System.err.println("Failed instantiating Robot: " + failed);
    }
    int mask = InputEvent.BUTTON1_DOWN_MASK;

    int howMany = 360 * ROUNDS;
    while (howMany > 0) {
        int x = getX(howMany);
        int y = getY(howMany);
        bot.mouseMove(x, y);
        bot.delay(DELAYMS);
        System.out.println("x:" + x + " y:" + y);
        howMany--;
    }

    long endT = System.currentTimeMillis();
    System.out.println("Duration: " + (endT - startT));

}

/**
 * 
 * @param angle
 *            in degree
 * @return
 */
private static int getX(int angle) {
    double radians = Math.toRadians(angle);
    Double x = RADIUS * Math.cos(radians) + XSTART;
    int result = x.intValue();

    return result;
}

/**
 * 
 * @param angle
 *            in degree
 * @return
 */
private static int getY(int angle) {
    double radians = Math.toRadians(angle);
    Double y = RADIUS * Math.sin(radians) + YSTART;
    int result = y.intValue();

    return result;
}
}

How do I check that a number is float or integer?

try this one
function amountcheck()
    {
        var dpamt=$('#dpamt').val()/5000;
        var ints=dpamt.toString();
        var isint=ints.split('.');
        if(isint[1]>0)
        {
            alert('float value');
            return false;
        }
        else
        {   
            alert('int value');
        }
    }

How to check for null in a single statement in scala?

Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach is the preferred way of doing it, I like to use an AnyRef pimp that allows me to write:

getObject ifNotNull ( QueueManager.add(_) )

I find it reads better.

And, in a more general way, I sometimes write

val returnVal = getObject ifNotNull { obj =>
  returnSomethingFrom(obj)
} otherwise {
  returnSomethingElse
}

... replacing ifNotNull with ifSome if I'm dealing with an Option. I find it clearer than first wrapping in an option and then pattern-matching it.

(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0/Otherwise1 classes.)

Variable that has the path to the current ansible-playbook that is executing?

I was using a playbook like this to test my roles locally:

---
- hosts: localhost
  roles:
     - role: .

but this stopped working with Ansible v2.2.

I debugged the aforementioned solution of

---
- hosts: all
  tasks:
    - name: Find out playbooks path
      shell: pwd
      register: playbook_path_output
    - debug: var=playbook_path_output.stdout

and it produced my home directory and not the "current working directory"

I settled with

---
- hosts: all
  roles:
    - role: '{{playbook_dir}}'

per the solution above.

Have a reloadData for a UITableView animate when changing

Animating without reloadData() in Swift can be done like this (as of version 2.2):

tableview.beginUpdates()
var indexPathsToDeleteForAnimation: [NSIndexPath] = []
var numOfCellsToRemove = ArrayOfItemsToRemove ?? 0

// Do your work here
while numOfCellsToRemove > 0 {
    // ...or here, if you need to add/remove the same amount of objects to/from somewhere
    indexPathsToDeleteForAnimation.append(NSIndexPath(forRow: selectedCellIndex+numOfCellsToRemove, inSection: 0))
    numOfCellsToRemove -= 1
}
tableview.deleteRowsAtIndexPaths(indexPathsToDeleteForAnimation, withRowAnimation: UITableViewRowAnimation.Right)
tableview.endUpdates()

in case you need to call reloadData() after the animation ends, you can embrace the changes in CATransaction like this:

CATransaction.begin()
CATransaction.setCompletionBlock({() in self.tableview.reloadData() })
tableview.beginUpdates()
var indexPathsToDeleteForAnimation: [NSIndexPath] = []
var numOfCellsToRemove = ArrayOfItemsToRemove.count ?? 0

// Do your work here
while numOfCellsToRemove > 0 {
     // ...or here, if you need to add/remove the same amount of objects to/from somewhere
     indexPathsToDeleteForAnimation.append(NSIndexPath(forRow: selectedCellIndex+numOfCellsToRemove, inSection: 0))
     numOfCellsToRemove -= 1
}
tableview.deleteRowsAtIndexPaths(indexPathsToDeleteForAnimation, withRowAnimation: UITableViewRowAnimation.Right)
tableview.endUpdates()
CATransaction.commit()

The logic is shown for the case when you delete rows, but the same idea works also for adding rows. You can also change animation to UITableViewRowAnimation.Left to make it neat, or choose from the list of other available animations.

how to add a day to a date using jquery datepicker

The datepicker('setDate') sets the date in the datepicket not in the input.

You should add the date and set it in the input.

var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);

How to change the CHARACTER SET (and COLLATION) throughout a database?

change database collation:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change table collation:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change column collation:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

What do the parts of utf8mb4_0900_ai_ci mean?

3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 --   _unicode_
v5.20 --  _unicode_520_
v9.0 --   _0900_ (new)
_bin      -- just compare the bits; don't consider case folding, accents, etc
_ci       -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci    -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin         -- simple, fast
_general_ci  -- fails to compare multiple letters; eg ss=ß, somewhat fast
...          -- slower
_0900_       -- (8.0) much faster because of a rewrite

More info:

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

You can always use the DATALENGTH Function to determine if you have extra white space characters in text fields. This won't make the text visible but will show you where there are extra white space characters.

    SELECT DATALENGTH('MyTextData ') AS BinaryLength, LEN('MyTextData ') AS TextLength

This will produce 11 for BinaryLength and 10 for TextLength.

In a table your SQL would like this:

    SELECT * 
    FROM tblA
    WHERE DATALENGTH(MyTextField) > LEN(MyTextField)

This function is usable in all versions of SQL Server beginning with 2005.

What is best way to start and stop hadoop ecosystem, with command line?

start-all.sh & stop-all.sh : Used to start and stop hadoop daemons all at once. Issuing it on the master machine will start/stop the daemons on all the nodes of a cluster. Deprecated as you have already noticed.

start-dfs.sh, stop-dfs.sh and start-yarn.sh, stop-yarn.sh : Same as above but start/stop HDFS and YARN daemons separately on all the nodes from the master machine. It is advisable to use these commands now over start-all.sh & stop-all.sh

hadoop-daemon.sh namenode/datanode and yarn-deamon.sh resourcemanager : To start individual daemons on an individual machine manually. You need to go to a particular node and issue these commands.

Use case : Suppose you have added a new DN to your cluster and you need to start the DN daemon only on this machine,

bin/hadoop-daemon.sh start datanode

Note : You should have ssh enabled if you want to start all the daemons on all the nodes from one machine.

Hope this answers your query.

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

I set the token delimiter to be a newline pattern, read the next token, and then put the delimiter back to whatever it was.

public static String readLine(Scanner scanner) {
        Pattern oldDelimiter = scanner.delimiter();
        scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
        String r = scanner.next();
        scanner.useDelimiter(oldDelimiter);
        return r;
}

JS jQuery - check if value is in array

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

Can't install gems on OS X "El Capitan"

Disclaimer: @theTinMan and other Ruby developers often point out not to use sudo when installing gems and point to things like RVM. That's absolutely true when doing Ruby development. Go ahead and use that.

However, many of us just want some binary that happens to be distributed as a gem (e.g. fakes3, cocoapods, xcpretty …). I definitely don't want to bother with managing a separate ruby. Here are your quicker options:

Option 1: Keep using sudo

Using sudo is probably fine if you want these tools to be installed globally.

The problem is that these binaries are installed into /usr/bin, which is off-limits since El Capitan. However, you can install them into /usr/local/bin instead. That's where Homebrew install its stuff, so it probably exists already.

sudo gem install fakes3 -n/usr/local/bin

Gems will be installed into /usr/local/bin and every user on your system can use them if it's in their PATH.

Option 2: Install in your home directory (without sudo)

The following will install gems in ~/.gem and put binaries in ~/bin (which you should then add to your PATH).

gem install fakes3 --user-install -n~/bin

Make it the default

Either way, you can add these parameters to your ~/.gemrc so you don't have to remember them:

gem: -n/usr/local/bin

i.e. echo "gem: -n/usr/local/bin" >> ~/.gemrc

or

gem: --user-install -n~/bin

i.e. echo "gem: --user-install -n~/bin" >> ~/.gemrc

(Tip: You can also throw in --no-document to skip generating Ruby developer documentation.)

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

In my case work fine after it:

rm -f .git/FETCH_HEAD

git branch -u

Bootstrap - 5 column layout

<div class="row">
    <div class="col">One</div>
    <div class="col">Two</div>
    <div class="col">Three</div>
    <div class="col">Four</div>
    <div class="col">Five</div>
</div>

you can customize however you need by writing media query. So that we can maintain responsive design

@media(max-width: 425px) {
    .col {
      flex-basis: auto;
      -webkit-box-flex: 1;
      flex-grow: 1;
      max-width: 100%;
    }
}
@media(min-width: 426px) and  (max-width: 961px){
  .col {
    flex-basis: auto;
    -webkit-box-flex: 1;
    flex-grow: 1;
    max-width: 50%;
  }
}

Send JSON via POST in C# and Receive the JSON returned?

You can build your HttpContent using the combination of JObject to avoid and JProperty and then call ToString() on it when building the StringContent:

        /*{
          "agent": {                             
            "name": "Agent Name",                
            "version": 1                                                          
          },
          "username": "Username",                                   
          "password": "User Password",
          "token": "xxxxxx"
        }*/

        JObject payLoad = new JObject(
            new JProperty("agent", 
                new JObject(
                    new JProperty("name", "Agent Name"),
                    new JProperty("version", 1)
                    ),
                new JProperty("username", "Username"),
                new JProperty("password", "User Password"),
                new JProperty("token", "xxxxxx")    
                )
            );

        using (HttpClient client = new HttpClient())
        {
            var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");

            using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JObject.Parse(responseBody);
            }
        }

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Pandas convert dataframe to array of tuples

Here's a vectorized approach (assuming the dataframe, data_set to be defined as df instead) that returns a list of tuples as shown:

>>> df.set_index(['data_date'])[['data_1', 'data_2']].to_records().tolist()

produces:

[(datetime.datetime(2012, 2, 17, 0, 0), 24.75, 25.03),
 (datetime.datetime(2012, 2, 16, 0, 0), 25.0, 25.07),
 (datetime.datetime(2012, 2, 15, 0, 0), 24.99, 25.15),
 (datetime.datetime(2012, 2, 14, 0, 0), 24.68, 25.05),
 (datetime.datetime(2012, 2, 13, 0, 0), 24.62, 24.77),
 (datetime.datetime(2012, 2, 10, 0, 0), 24.38, 24.61)]

The idea of setting datetime column as the index axis is to aid in the conversion of the Timestamp value to it's corresponding datetime.datetime format equivalent by making use of the convert_datetime64 argument in DF.to_records which does so for a DateTimeIndex dataframe.

This returns a recarray which could be then made to return a list using .tolist


More generalized solution depending on the use case would be:

df.to_records().tolist()                              # Supply index=False to exclude index

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

There's no need for all the code mentioned by galambalazs. The cross-browser way to do it in pure JavaScript is simply to test document.readyState:

if (document.readyState === "complete") { init(); }

This is also how jQuery does it.

Depending on where the JavaScript is loaded, this can be done inside an interval:

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);

In fact, document.readyState can have three states:

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded. -- document.readyState at Mozilla Developer Network

So if you only need the DOM to be ready, check for document.readyState === "interactive". If you need the whole page to be ready, including images, check for document.readyState === "complete".

How to set UTF-8 encoding for a PHP file

You have to specify what encoding the data is. Either in meta or in headers

header('Content-Type: text/plain; charset=utf-8');

How to get memory available or used in C#

You can use:

Process proc = Process.GetCurrentProcess();

To get the current process and use:

proc.PrivateMemorySize64;

To get the private memory usage. For more information look at this link.

:before and background-image... should it work?

Background images on :before and :after elements should work. If you post an example I could probably tell you why it does not work in your case.

Here is an example: http://jsfiddle.net/namas/3/

You can specify the dimensions of the element in % by using background-size: 100% 100% (width / height), for example.

Output single character in C

char variable = 'x';  // the variable is a char whose value is lowercase x

printf("<%c>", variable); // print it with angle brackets around the character

How to reliably open a file in the same directory as a Python script

Ok here is what I do

sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe

For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.

    C:\Documents and Settings\Admin>python test.py
    sys.argv[0]: test.py
    C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py"
    sys.argv[0]: C:\Documents and Settings\Admin\test.py

Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname

    import sys, os
    print os.path.dirname(os.path.abspath(sys.argv[0]))

That will output this:

   C:\Documents and Settings\Admin\

it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"

The problem with using __file__ Consider these two files test.py

import sys
import os

def paths():
        print "__file__: %s" % __file__
        print "sys.argv: %s" % sys.argv[0]

        a_f = os.path.abspath(__file__)
        a_s = os.path.abspath(sys.argv[0])

        print "abs __file__: %s" % a_f
        print "abs sys.argv: %s" % a_s

if __name__ == "__main__":
    paths()

import_test.py

import test
import sys

test.paths()

print "--------"
print __file__
print sys.argv[0]

Output of "python test.py"

C:\Documents and Settings\Admin>python test.py
__file__: test.py
sys.argv: test.py
abs __file__: C:\Documents and Settings\Admin\test.py
abs sys.argv: C:\Documents and Settings\Admin\test.py

Output of "python test_import.py"

C:\Documents and Settings\Admin>python test_import.py
__file__: C:\Documents and Settings\Admin\test.pyc
sys.argv: test_import.py
abs __file__: C:\Documents and Settings\Admin\test.pyc
abs sys.argv: C:\Documents and Settings\Admin\test_import.py
--------
test_import.py
test_import.py

So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

How to update the value of a key in a dictionary in Python?

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

We got this error when the connection string to our database was incorrect. The key to figuring this out was running the dotnet blah.dll which provided a stacktrace showing us that the sql server instance specified could not be found. Hope this helps someone.

How to change default language for SQL Server?

@John Woo's accepted answer has some caveats which you should be aware of:

  1. Default language setting of a session is controlled from default language setting of the user login instead which you have used to create the session. SQL Server instance level setting doesn't affect the default language of the session.
  2. Changing default language setting at SQL Server instance level doesn't affects the default language setting of the existing SQL Server logins. It is meant to be inherited only by the new user logins that you create after changing the instance level setting.

So, there is an intermediate level between your SQL Server instance and the session which you can use to control the default language setting for session - login level.

SQL Server Instance level setting -> User login level setting -> Query Session level setting

This can help you in case you want to set default language of all new sessions belonging to some specific user only.

Simply change the default language setting of the target user login as per this link and you are all set. You can also do it from SQL Server Management Studio (SSMS) UI. Below you can see the default language setting in properties window of sa user in SQL Server:

enter image description here

Note: Also, it is important to know that changing the setting doesn't affect the default language of already active sessions from that user login. It will affect only the new sessions created after changing the setting.

Move div to new line

What about something like this.

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
        <div class="movie_item_content_year">year</div>
        <div class="movie_item_content_title">title</div>
        <div class="movie_item_content_plot">plot</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

You don't have to float both movie_item_poster AND movie_item_content. Just float one of them...

#movie_item {
    position: relative;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
}

.movie_item_content {
    position: relative;
}

.movie_item_content_title {
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

Here it is as a JSFiddle.

c#: getter/setter

It's an automatically backed property, basically equivalent to:

private string type;
public string Type
{
   get{ return type; }
   set{ type = value; }
}

How to parse/format dates with LocalDateTime? (Java 8)

GET CURRENT UTC TIME IN REQUIRED FORMAT

// Current UTC time
        OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);

        // GET LocalDateTime 
        LocalDateTime localDateTime = utc.toLocalDateTime();
        System.out.println("*************" + localDateTime);

        // formated UTC time
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF.format(localDateTime));

        //GET UTC time for current date
        Date now= new Date();
        LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

Where is database .bak file saved from SQL Server Management Studio?

As said by Faiyaz, to get default backup location for the instance, you cannot get it into msdb, but you have to look into Registry. You can get it in T-SQL in using xp_instance_regread stored procedure like this:

EXEC  master.dbo.xp_instance_regread 
      N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQLServer',N'BackupDirectory'

The double backslash (\\) is because the spaces into that key name part (Microsoft SQL Server). The "MSSQL12.MSSQLSERVER" part is for default instance name for SQL 2014. You have to adapt to put your own instance name (look into Registry).

force line break in html table cell

You could put the text into a div (or other container) with a width of 50%.

http://jsfiddle.net/6gjsd/

How can I get the browser's scrollbar sizes?

From David Walsh's blog:

_x000D_
_x000D_
// Create the measurement node_x000D_
var scrollDiv = document.createElement("div");_x000D_
scrollDiv.className = "scrollbar-measure";_x000D_
document.body.appendChild(scrollDiv);_x000D_
_x000D_
// Get the scrollbar width_x000D_
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;_x000D_
console.info(scrollbarWidth); // Mac:  15_x000D_
_x000D_
// Delete the DIV _x000D_
document.body.removeChild(scrollDiv);
_x000D_
.scrollbar-measure {_x000D_
 width: 100px;_x000D_
 height: 100px;_x000D_
 overflow: scroll;_x000D_
 position: absolute;_x000D_
 top: -9999px;_x000D_
}
_x000D_
_x000D_
_x000D_

Gives me 17 on my website, 14 here on Stackoverflow.

How to ping a server only once from within a batch file?

Enter in a command prompt window ping /? and read the short help output after pressing RETURN. Or take a look on

  • Ping - Windows XP documentation
  • Ping - Microsoft TechNet article

Explanation for option -t given by Microsoft:

Pings the specified host until stopped. To see statistics and continue type Control-Break. To stop type Control-C.

You may want to use:

@%SystemRoot%\system32\ping.exe -n 1 www.google.de

Or to check first if a server is available:

@echo off
set MyServer=Server.MyDomain.de
%SystemRoot%\system32\ping.exe -n 1 %MyServer% >nul
if errorlevel 1 goto NoServer

echo %MyServer% is availabe.
rem Insert commands here, for example 1 or more net use to connect network drives.
goto :EOF

:NoServer
echo %MyServer% is not availabe yet.
pause
goto :EOF

How can I stream webcam video with C#?

You could just use VideoLAN. VideoLAN will work as a server (or you can wrap your own C# application around it for more control). There are also .NET wrappers for the viewer that you can use and thus embed in your C# client.

TokenMismatchException in VerifyCsrfToken.php Line 67

I had the same issue but I solved it by correcting my form open as shown below :

{!!Form::open(['url'=>route('auth.login-post'),'class'=>'form-horizontal'])!!}

If this doesn't solve your problem, can you please show how you opened the form ?

Best way to access a control on another form in Windows Forms?

I personally would recommend NOT doing it... If it's responding to some sort of action and it needs to change its appearance, I would prefer raising an event and letting it sort itself out...

This kind of coupling between forms always makes me nervous. I always try to keep the UI as light and independent as possible..

I hope this helps. Perhaps you could expand on the scenario if not?

What is the definition of "interface" in object oriented programming

An interface defines what a class that inherits from it must implement. In this way, multiple classes can inherit from an interface, and because of that inherticance, you can

  • be sure that all members of the interface are implemented in the derived class (even if its just to throw an exception)
  • Abstract away the class itself from the caller (cast an instance of a class to the interface, and interact with it without needing to know what the actual derived class IS)

for more info, see this http://msdn.microsoft.com/en-us/library/ms173156.aspx

Difference between RUN and CMD in a Dockerfile

RUN - Install Python , your container now has python burnt into its image
CMD - python hello.py , run your favourite script

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

I found 2 things worth mentioning while uploading files using webdav and http web request. First, for the provider I was using, I had to append the filename at the end of the provider url. Ihad to append the port number in the url. And I also set the Request method to PUT instead of POST.

example:

string webdavUrl = "https://localhost:443/downloads/test.pdf";
request.Method = "PUT";

Screen width in React Native

First get Dimensions from react-native

import { Dimensions } from 'react-native';

then

const windowWidth = Dimensions.get('window').width;

const windowHeight = Dimensions.get('window').height;

in windowWidth you will find the width of the screen while in windowHeight you will find the height of the screen.

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

with MariaDb, above solutions doesn't works.

Use (exemple below with ubuntu 16.04 and mariadb-server Distrib 10.0.28):

    sudo mysql_secure_installation
    …
    Change the root password? [Y/n] 
    New password: 

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

for this small example:

import socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print (data);

mysock.close()

adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem

How to round a number to significant figures in Python

The posted answer was the best available when given, but it has a number of limitations and does not produce technically correct significant figures.

numpy.format_float_positional supports the desired behaviour directly. The following fragment returns the float x formatted to 4 significant figures, with scientific notation suppressed.

import numpy as np
x=12345.6
np.format_float_positional(x, precision=4, unique=False, fractional=False, trim='k')
> 12340.

m2eclipse error

This error bothered me for two days. I tried all kinds of solutions, nothing worked. Finally I give up and tried a radical approach. and it worked! Here are the steps:

  1. Save a copy of the pom.xml,
  2. deleted all text in pom.xml
  3. Let eclipse do a clean rebuild, of course everything will be broken.
  4. pasted back everything in the original pom.xml
  5. let Eclipse build again

I guess it was "indeterministic" as the following article said.

http://wiki.eclipse.org/M2E_plugin_execution_not_covered

How to detect the device orientation using CSS media queries?

@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}

@media all and (orientation:landscape) {
  /* Style adjustments for landscape mode goes here */
}

but it still looks like you have to experiment

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

Make page to tell browser not to cache/preserve input values

Another approach would be to reset the form using JavaScript right after the form in the HTML:

<form id="myForm">
  <input type="text" value="" name="myTextInput" />
</form>

<script type="text/javascript">
  document.getElementById("myForm").reset();
</script>

What is the difference between \r and \n?

In addition to @Jon Skeet's answer:

Traditionally Windows has used \r\n, Unix \n and Mac \r, however newer Macs use \n as they're unix based.

Should I call Close() or Dispose() for stream objects?

For what it's worth, the source code for Stream.Close explains why there are two methods:

// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable.  However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern.  We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup now.

In short, Close is only there because it predates Dispose, and it can't be deleted for compatibility reasons.

Bootstrap modal in React.js

I've only used bootstrap cdn (css + js) to achieve "reactstrap" like solution. I've used props.children to pass dynamic data from parent to child components. You can find more about this here. In this way you have three separate components modal header, modal body and modal footer and they are totally independent from each other.


//Modal component
import React, { Component } from 'react';

export const ModalHeader = props => {
  return <div className="modal-header">{props.children}</div>;
};

export const ModalBody = props => {
  return <div className="modal-body">{props.children}</div>;
};

export const ModalFooter = props => {
  return <div className="modal-footer">{props.children}</div>;
};

class Modal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalShow: '',
      display: 'none'
    };
    this.openModal = this.openModal.bind(this);
    this.closeModal = this.closeModal.bind(this);
  }

  openModal() {
    this.setState({
      modalShow: 'show',
      display: 'block'
    });
  }

  closeModal() {
    this.setState({
      modalShow: '',
      display: 'none'
    });
  }

  componentDidMount() {
    this.props.isOpen ? this.openModal() : this.closeModal();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.isOpen !== this.props.isOpen) {
      this.props.isOpen ? this.openModal() : this.closeModal();
    }
  }

  render() {
    return (
      <div
        className={'modal fade ' + this.state.modalShow}
        tabIndex="-1"
        role="dialog"
        aria-hidden="true"
        style={{ display: this.state.display }}
      >
        <div className="modal-dialog" role="document">
          <div className="modal-content">{this.props.children}</div>
        </div>
      </div>
    );
  }
}

export default Modal;

//App component
import React, { Component } from 'react';
import Modal, { ModalHeader, ModalBody, ModalFooter } from './components/Modal';

import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modal: false
    };
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({ modal: !this.state.modal });
  }

  render() {
    return (
      <div className="App">
        <h1>Bootstrap Components</h1>

        <button
          type="button"
          className="btn btn-secondary"
          onClick={this.toggle}
        >
          Modal
        </button>

        <Modal isOpen={this.state.modal}>
          <ModalHeader>
            <h3>This is modal header</h3>
            <button
              type="button"
              className="close"
              aria-label="Close"
              onClick={this.toggle}
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </ModalHeader>
          <ModalBody>
            <p>This is modal body</p>
          </ModalBody>
          <ModalFooter>
            <button
              type="button"
              className="btn btn-secondary"
              onClick={this.toggle}
            >
              Close
            </button>
            <button
              type="button"
              className="btn btn-primary"
              onClick={this.toggle}
            >
              Save changes
            </button>
          </ModalFooter>
        </Modal>
      </div>
    );
  }
}

export default App;

How do I check if an integer is even or odd?

Here is an answer in Java:

public static boolean isEven (Integer Number) {
    Pattern number = Pattern.compile("^.*?(?:[02]|8|(?:6|4))$");
    String num = Number.toString(Number);
    Boolean numbr = new Boolean(number.matcher(num).matches());
    return numbr.booleanValue();
}

Get GPS location via a service in Android

public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private static final String LOGSERVICE = "#######";

    @Override
    public void onCreate() {
        super.onCreate();
        buildGoogleApiClient();
        Log.i(LOGSERVICE, "onCreate");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(LOGSERVICE, "onStartCommand");

        if (!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
        return START_STICKY;
    }


    @Override
    public void onConnected(Bundle bundle) {
        Log.i(LOGSERVICE, "onConnected" + bundle);

        Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (l != null) {
            Log.i(LOGSERVICE, "lat " + l.getLatitude());
            Log.i(LOGSERVICE, "lng " + l.getLongitude());

        }

        startLocationUpdate();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(LOGSERVICE, "onConnectionSuspended " + i);

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.i(LOGSERVICE, "lat " + location.getLatitude());
        Log.i(LOGSERVICE, "lng " + location.getLongitude());
        LatLng mLocation = (new LatLng(location.getLatitude(), location.getLongitude()));
        EventBus.getDefault().post(mLocation);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOGSERVICE, "onDestroy - Estou sendo destruido ");

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(LOGSERVICE, "onConnectionFailed ");

    }

    private void initLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000);
        mLocationRequest.setFastestInterval(2000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    }

    private void startLocationUpdate() {
        initLocationRequest();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    private void stopLocationUpdate() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
    }

}

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

PyPy has had Python 3 support for a while, but according to this HackerNoon post by Anthony Shaw from April 2nd, 2018, PyPy3 is still several times slower than PyPy (Python 2).

For many scientific calculations, particularly matrix calculations, numpy is a better choice (see FAQ: Should I install numpy or numpypy?).

Pypy does not support gmpy2. You can instead make use of gmpy_cffi though I haven't tested its speed and the project had one release in 2014.

For Project Euler problems, I make frequent use of PyPy, and for simple numerical calculations often from __future__ import division is sufficient for my purposes, but Python 3 support is still being worked on as of 2018, with your best bet being on 64-bit Linux. Windows PyPy3.5 v6.0, the latest as of December 2018, is in beta.

How to put an image next to each other

Change div to span. And space the icons using &nbsp; HTML

 <div class="nav3" style="height:705px;">
 <span class="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a>
 </span>&nbsp;&nbsp;&nbsp;
 <span class="icons"><a href="https://twitter.com"><img src="images/twitter.png"></a>
 </span>
 </div>

CSS

.nav3 {
background-color: #E9E8C7;
height: auto;
width: 150px;
float: left;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333333;
padding-top: 20px;
padding-right: 20px;
}

.icons{
display:inline-block;
width: 64px; 
height: 64px; 
}

 a.icons:hover {
 background: #C93;
 }

span does not break line, div does.

Use sudo with password as parameter

You can set the s bit for your script so that it does not need sudo and runs as root (and you do not need to write your root password in the script):

sudo chmod +s myscript

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

I had the same exception and I was excluding javassist because of its issue with powermock. Then I was adding it again as below but it was not working:

<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
   <exclusions>
      <exclusion>
         <groupId>org.javassist</groupId>
         <artifactId>javassist</artifactId>
      </exclusion>
   </exclusions>
</dependency>

<dependency>
   <groupId>org.javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.20.0-GA</version>
   <scope>test</scope>
</dependency>

Finally I found out that I have to remove <scope>test</scope> from javassist dependency. Hope it helps someone.

Determine which element the mouse pointer is on top of in JavaScript

DEMO

There's a really cool function called document.elementFromPoint which does what it sounds like.

What we need is to find the x and y coords of the mouse and then call it using those values:

var x = event.clientX, y = event.clientY,
    elementMouseIsOver = document.elementFromPoint(x, y);

document.elementFromPoint

jQuery event object

What values for checked and selected are false?

The empty string is false as a rule.

Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.

What is the "assert" function?

In addition, you can use it to check if the dynamic allocation was successful.

Code example:

int ** p;
p = new int * [5];      // Dynamic array (size 5) of pointers to int
for (int i = 0; i < 5; ++i) {
    p[i] = new int[3]; // Each i(ptr) is now pointing to a dynamic
                       // array (size 3) of actual int values
}

assert (p);            // Check the dynamic allocation.

Similar to:

if (p == NULL) {
    cout << "dynamic allocation failed" << endl;
    exit(1);
}

How many files can I put in a directory?

The question comes down to what you're going to do with the files.

Under Windows, any directory with more than 2k files tends to open slowly for me in Explorer. If they're all image files, more than 1k tend to open very slowly in thumbnail view.

At one time, the system-imposed limit was 32,767. It's higher now, but even that is way too many files to handle at one time under most circumstances.

Remove Duplicates from range of cells in excel vba

If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:

 Sub norepeat()

    Range("C8:C16").RemoveDuplicates (1)

End Sub

Regards

Best way to encode text data for XML in Java?

Note: Your question is about escaping, not encoding. Escaping is using <, etc. to allow the parser to distinguish between "this is an XML command" and "this is some text". Encoding is the stuff you specify in the XML header (UTF-8, ISO-8859-1, etc).

First of all, like everyone else said, use an XML library. XML looks simple but the encoding+escaping stuff is dark voodoo (which you'll notice as soon as you encounter umlauts and Japanese and other weird stuff like "full width digits" (&#FF11; is 1)). Keeping XML human readable is a Sisyphus' task.

I suggest never to try to be clever about text encoding and escaping in XML. But don't let that stop you from trying; just remember when it bites you (and it will).

That said, if you use only UTF-8, to make things more readable you can consider this strategy:

  • If the text does contain '<', '>' or '&', wrap it in <![CDATA[ ... ]]>
  • If the text doesn't contain these three characters, don't warp it.

I'm using this in an SQL editor and it allows the developers to cut&paste SQL from a third party SQL tool into the XML without worrying about escaping. This works because the SQL can't contain umlauts in our case, so I'm safe.

Is there a way of setting culture for a whole application? All current threads and new threads?

This gets asked a lot. Basically, no there isn't, not for .NET 4.0. You have to do it manually at the start of each new thread (or ThreadPool function). You could perhaps store the culture name (or just the culture object) in a static field to save having to hit the DB, but that's about it.

How to convert const char* to char* in C?

You can cast it by doing (char *)Identifier_Of_Const_char

But as there is probabbly a reason that the api doesn't accept const cahr *, you should do this only, if you are sure, the function doesn't try to assign any value in range of your const char* which you casted to a non const one.

Getting user input

In python 3.x, use input() instead of raw_input()

Can you style html form buttons with css?

write the below style into same html file head section or write into a .css file

<style type="text/css">
.submit input
    {
    color: #000;
    background: #ffa20f;
    border: 2px outset #d7b9c9
    }
</style>

<input type="submit" class="submit"/>

.submit - in css . means class , so i created submit class with set of attributes
and applied that class to the submit tag, using class attribute

How can I change the Bootstrap default font family using font from Google?

First of all, you can't import fonts to CSS that way.

You can add this code in HTML head:

<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>

or to import it in CSS file like this:

@import url("http://fonts.googleapis.com/css?family=Oswald:400,300,700");

Then, in your css, you can edit the body's font-family:

body {
  font-family: 'Oswald', sans-serif !important;
}

How to capture the android device screen content?

Use the following code:

Bitmap bitmap;
View v1 = MyView.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

Here MyView is the View through which we need include in the screen. You can also get DrawingCache from of any View this way (without getRootView()).


There is also another way..
If we having ScrollView as root view then its better to use following code,

LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
FrameLayout root = (FrameLayout) inflater.inflate(R.layout.activity_main, null); // activity_main is UI(xml) file we used in our Activity class. FrameLayout is root view of my UI(xml) file.
root.setDrawingCacheEnabled(true);
Bitmap bitmap = getBitmapFromView(this.getWindow().findViewById(R.id.frameLayout)); // here give id of our root layout (here its my FrameLayout's id)
root.setDrawingCacheEnabled(false);

Here is the getBitmapFromView() method

public static Bitmap getBitmapFromView(View view) {
        //Define a bitmap with the same size as the view
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        //Bind a canvas to it
        Canvas canvas = new Canvas(returnedBitmap);
        //Get the view's background
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null) 
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
        else 
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE);
        // draw the view on the canvas
        view.draw(canvas);
        //return the bitmap
        return returnedBitmap;
    }

It will display entire screen including content hidden in your ScrollView


UPDATED AS ON 20-04-2016

There is another better way to take screenshot.
Here I have taken screenshot of WebView.

WebView w = new WebView(this);
    w.setWebViewClient(new WebViewClient()
    {
        public void onPageFinished(final WebView webView, String url) {

            new Handler().postDelayed(new Runnable(){
                @Override
                public void run() {
                    webView.measure(View.MeasureSpec.makeMeasureSpec(
                                    View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                    webView.layout(0, 0, webView.getMeasuredWidth(),
                            webView.getMeasuredHeight());
                    webView.setDrawingCacheEnabled(true);
                    webView.buildDrawingCache();
                    Bitmap bitmap = Bitmap.createBitmap(webView.getMeasuredWidth(),
                            webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

                    Canvas canvas = new Canvas(bitmap);
                    Paint paint = new Paint();
                    int height = bitmap.getHeight();
                    canvas.drawBitmap(bitmap, 0, height, paint);
                    webView.draw(canvas);

                    if (bitmap != null) {
                        try {
                            String filePath = Environment.getExternalStorageDirectory()
                                    .toString();
                            OutputStream out = null;
                            File file = new File(filePath, "/webviewScreenShot.png");
                            out = new FileOutputStream(file);

                            bitmap.compress(Bitmap.CompressFormat.PNG, 50, out);
                            out.flush();
                            out.close();
                            bitmap.recycle();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, 1000);
        }
    });

Hope this helps..!

How to check a boolean condition in EL?

You can have a look at the EL (expression language) description here.

Both your code are correct, but I prefer the second one, as comparing a boolean to true or false is redundant.

For better readibility, you can also use the not operator:

<c:if test="${not theBooleanVariable}">It's false!</c:if>

How can I determine the URL that a local Git repository was originally cloned from?

To get the IP address/hostname of origin

For ssh:// repositories:

git ls-remote --get-url origin | cut -f 2 -d @ | cut -f 1 -d "/"

For git:// repositories:

git ls-remote --get-url origin | cut -f 2 -d @ | cut -f 1 -d ":"

assignment operator overloading in c++

The second is pretty standard. You often prefer to return a reference from an assignment operator so that statements like a = b = c; resolve as expected. I can't think of any cases where I would want to return a copy from assignment.

One thing to note is that if you aren't needing a deep copy it's sometimes considered best to use the implicit copy constructor and assignment operator generated by the compiler than roll your own. Really up to you though ...

Edit:

Here's some basic calls:

SimpleCircle x; // default constructor
SimpleCircle y(x); // copy constructor
x = y; // assignment operator

Now say we had the first version of your assignment operator:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this; // calls copy constructor SimpleCircle(*this)
     itsRadius = rhs.getRadius(); // copy member
     return *this; // calls copy constructor
}

It calls the copy constructor and passes a reference to this in order to construct the copy to be returned. Now in the second example we avoid the copy by just returning a reference to this

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this; // return reference to this (no copy)
    itsRadius = rhs.getRadius(); // copy member
    return *this; // return reference to this (no copy)
}

C++ code file extension? .cc vs .cpp

As others wrote before me, at the end its what being used by your project/team/company.

Personally, I am not using cc extension, I am trying to lower the number of extensions and not increase them, unless there's a clear value (in my opinion).

For what its worth, this is what I'm using:

c - Pure C code only, no classes or structs with methods.

cpp - C++ code

hpp - Headers only code. Implementations are in the headers (like template classes)

h - header files for both C/C++. I agree another distinction can be made, but as I wrote, I am trying to lower the number of extensions for simplicity. At least from the C++ projects I've worked in, h files for pure-C are more rare, therefore I did not want to add another extension.

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

Using filesystem in node.js with async / await

Starting with node 8.0.0, you can use this:

const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);

async function myF() {
  let names;
  try {
    names = await readdir('path/to/dir');
  } catch (err) {
    console.log(err);
  }
  if (names === undefined) {
    console.log('undefined');
  } else {
    console.log('First Name', names[0]);
  }
}

myF();

See https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original

Merge two (or more) lists into one, in C# .NET

you can combine them using LINQ:

  list = list1.Concat(list2).Concat(list3).ToList();

the more traditional approach of using List.AddRange() might be more efficient though.

MySQL Where DateTime is greater than today

SELECT * 
FROM customer 
WHERE joiningdate >= NOW();

How do I write a custom init for a UIView subclass in Swift?

Here is how I do a Subview on iOS in Swift -

class CustomSubview : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        let windowHeight : CGFloat = 150;
        let windowWidth  : CGFloat = 360;

        self.backgroundColor = UIColor.whiteColor();
        self.frame = CGRectMake(0, 0, windowWidth, windowHeight);
        self.center = CGPoint(x: UIScreen.mainScreen().bounds.width/2, y: 375);

        //for debug validation
        self.backgroundColor = UIColor.grayColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Skip first entry in for loop in python?

Here is a more general generator function that skips any number of items from the beginning and end of an iterable:

def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()

Example usage:

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]

Iterating over every two elements in a list

A simple solution.

l = [1, 2, 3, 4, 5, 6]

for i in range(0, len(l), 2):
    print str(l[i]), '+', str(l[i + 1]), '=', str(l[i] + l[i + 1])

Can you force Visual Studio to always run as an Administrator in Windows 8?

  1. On Windows 8 Start Menu select All Apps
  2. Right click on Visual Studio 2010 Icon
  3. Select Open File Location
  4. Right click on Visual Studio 2010 shortcut icon
  5. Click Advanced button
  6. Check the Run as Administrator checkbox
  7. Click OK

Android : How to set onClick event for Button in List item of ListView

FOR KOTLIN USERS

inside your getView(...) method if you try to start an activity through button onClickListener:

   myButton.setOnClickListener{
        val intent = Intent(this@CurrentActivity, SecondActivity::class.java)
        startActivity(intent)
   }

Pass the correct pointer for "this"

TypeError: p.easing[this.easing] is not a function

You need to include jQueryUI for the extended easing options.

I think there may be an option to only include the easing in the download, or at least just the base library plus easing.

How to fill background image of an UIView

For Swift 2.1 use this...

    UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "Cyan.jpg")?.drawInRect(self.view.bounds)

    let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    self.view.backgroundColor = UIColor(patternImage: image)

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.