Programs & Examples On #Run war

Launching Spring application Address already in use

I resolved this problem, by stop the application (red square in Eclipse) before run again. If you don't stop it , the application stay in run mode , so port still used .

How can I get the nth character of a string?

Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:

char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];

...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:

str = str + 1; // makes it point to 'E' now
char myChar =  *str;

I hope this helps.

How to stop line breaking in vim

I like that the long lines are displayed over more than one terminal line

This sort of visual/virtual line wrapping is enabled with the wrap window option:

set wrap

I don’t like that vim inserts newlines into my actual text.

To turn off physical line wrapping, clear both the textwidth and wrapmargin buffer options:

set textwidth=0 wrapmargin=0

Multiple Where clauses in Lambda expressions

The lambda you pass to Where can include any normal C# code, for example the && operator:

.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)

How to filter input type="file" dialog by specific file type?

<asp:FileUpload ID="FileUploadExcel" ClientIDMode="Static" runat="server" />
<asp:Button ID="btnUpload" ClientIDMode="Static" runat="server" Text="Upload Excel File" />

.

$('#btnUpload').click(function () {
    var uploadpath = $('#FileUploadExcel').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);

    if ($('#FileUploadExcel').val().length == 0) {
        // write error message
        return false;
    }

    if (fileExtension == "xls" || fileExtension == "xlsx") {
        //write code for success
    }
    else {
        //error code - select only excel files
        return false;
    }

});

setup.py examples?

I recommend the setup.py of the Python Packaging User Guide's example project.

The Python Packaging User Guide "aims to be the authoritative resource on how to package, publish and install Python distributions using current tools".

SQL to Query text in access with an apostrophe in it

...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:

e.g.:

DIM YourName string

YourName = "Daniel O'Neal"

  If InStr(YourName, "'") Then
      SELECT * FROM tblStudents WHERE [name]  Like """ Your Name """ ;
   else
      SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;       
  endif

Why doesn't Python have multiline comments?

For anyone else looking for multi-line comments in Python - using the triple quote format can have some problematic consequences, as I've just learned the hard way. Consider this:

this_dict = {
    'name': 'Bob',

"""
This is a multiline comment in the middle of a dictionary
"""

    'species': 'Cat'
}

The multi-line comment will be tucked into the next string, messing up the 'species' key. Better to just use # for comments.

How to get the size of a range in Excel

The Range object has both width and height properties, which are measured in points.

cancelling a handler.postdelayed process

Here is a class providing a cancel method for a delayed action

public class DelayedAction {

private Handler _handler;
private Runnable _runnable;

/**
 * Constructor
 * @param runnable The runnable
 * @param delay The delay (in milli sec) to wait before running the runnable
 */
public DelayedAction(Runnable runnable, long delay) {
    _handler = new Handler(Looper.getMainLooper());
    _runnable = runnable;
    _handler.postDelayed(_runnable, delay);
}

/**
 * Cancel a runnable
 */
public void cancel() {
    if ( _handler == null || _runnable == null ) {
        return;
    }
    _handler.removeCallbacks(_runnable);
}}

Checking if a folder exists using a .bat file

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

Disable the postback on an <ASP:LinkButton>

You might also want to have the client-side function return false.

<asp:LinkButton runat="server" id="button" Text="Click Me" OnClick="myfunction();return false;" AutoPostBack="false" />

You might also consider:

<span runat="server" id="clickableSpan" onclick="myfunction();" class="clickable">Click Me</span>

I use the clickable class to set things like pointer, color, etc. so that its appearance is similar to an anchor tag, but I don't have to worry about it getting posted back or having to do the href="javascript:void(0);" trick.

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

How do I include a Perl module that's in a different directory?

From perlfaq8:


How do I add the directory my program lives in to the module/library search path?

(contributed by brian d foy)

If you know the directory already, you can add it to @INC as you would for any other directory. You might use lib if you know the directory at compile time:

use lib $directory;

The trick in this task is to find the directory. Before your script does anything else (such as a chdir), you can get the current working directory with the Cwd module, which comes with Perl:

BEGIN {
    use Cwd;
    our $directory = cwd;
    }

use lib $directory;

You can do a similar thing with the value of $0, which holds the script name. That might hold a relative path, but rel2abs can turn it into an absolute path. Once you have the

BEGIN {
    use File::Spec::Functions qw(rel2abs);
    use File::Basename qw(dirname);

    my $path   = rel2abs( $0 );
    our $directory = dirname( $path );
    }

use lib $directory;

The FindBin module, which comes with Perl, might work. It finds the directory of the currently running script and puts it in $Bin, which you can then use to construct the right library path:

use FindBin qw($Bin);

Visualizing branch topology in Git

Gitx is also a fantastic visualization tool if you happen to be on OS X.

MATLAB error: Undefined function or method X for input arguments of type 'double'

You get this error when the function isn't on the MATLAB path or in pwd.

First, make sure that you are able to find the function using:

>> which divrat
c:\work\divrat\divrat.m

If it returns:

>> which divrat
'divrat' not found.

It is not on the MATLAB path or in PWD.

Second, make sure that the directory that contains divrat is on the MATLAB path using the PATH command. It may be that a directory that you thought was on the path isn't actually on the path.

Finally, make sure you aren't using a "private" directory. If divrat is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:

>> foo

ans =

     1

>> divrat(1,1)
??? Undefined function or method 'divrat' for input arguments of type 'double'.

>> which -all divrat
c:\work\divrat\private\divrat.m  % Private to divrat

How can I convert a Timestamp into either Date or DateTime object?

You can also get DateTime object from timestamp, including your current daylight saving time:

public DateTime getDateTimeFromTimestamp(Long value) {
    TimeZone timeZone = TimeZone.getDefault();
    long offset = timeZone.getOffset(value);
    if (offset < 0) {
        value -= offset;
    } else {
        value += offset;
    }
    return new DateTime(value);
}    

How can one develop iPhone apps in Java?

There is anew tool called Codename one: One SDK based on JAVA to code in WP8, Android, iOS with all extensive features

Features:

  1. Full Android environment with super fast android simulator
  2. An iPhone/iPad simulator with easy to take iPhone apps to large screen iPad in minutes.
  3. Full support for standard java debugging, profiling for apps on any platform.
  4. Easy themeing / styling – Only a click away

More at Develop Android, iOS iPhone, WP8 apps using Java

Get encoding of a file in Windows

The only way that I have found to do this is VIM or Notepad++.

Convert A String (like testing123) To Binary In Java

A String in Java can be converted to "binary" with its getBytes(Charset) method.

byte[] encoded = "????????!".getBytes(StandardCharsets.UTF_8);

The argument to this method is a "character-encoding"; this is a standardized mapping between a character and a sequence of bytes. Often, each character is encoded to a single byte, but there aren't enough unique byte values to represent every character in every language. Other encodings use multiple bytes, so they can handle a wider range of characters.

Usually, the encoding to use will be specified by some standard or protocol that you are implementing. If you are creating your own interface, and have the freedom to choose, "UTF-8" is an easy, safe, and widely supported encoding.

  • It's easy, because rather than including some way to note the encoding of each message, you can default to UTF-8.
  • It's safe, because UTF-8 can encode any character that can be used in a Java character string.
  • It's widely supported, because it is one of a small handful of character encodings that is required to be present in any Java implementation, all the way down to J2ME. Most other platforms support it too, and it's used as a default in standards like XML.

Byte array to image conversion

In one line:

Image.FromStream(new MemoryStream(byteArrayIn));

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

How to create a CPU spike with a bash command

Although I'm late to the party, this post is among the top results in the google search "generate load in linux".

The result marked as solution could be used to generate a system load, i'm preferring to use sha1sum /dev/zero to impose a load on a cpu-core.

The idea is to calculate a hash sum from an infinite datastream (eg. /dev/zero, /dev/urandom, ...) this process will try to max out a cpu-core until the process is aborted. To generate a load for more cores, multiple commands can be piped together.

eg. generate a 2 core load: sha1sum /dev/zero | sha1sum /dev/zero

Execution failed for task ':app:processDebugResources' even with latest build tools

Another possible reason

resConfigs "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"

can be source of this issue

Run multiple python scripts concurrently

I am working in Windows 7 with Python IDLE. I have two programs,

# progA
while True:
    m = input('progA is running ')
    print (m)

and

# progB
while True:
    m = input('progB is running ')
    print (m)

I open up IDLE and then open file progA.py. I run the program, and when prompted for input I enter "b" + <Enter> and then "c" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progA.py =
progA is running b
b
progA is running c
c
progA is running 

Next, I go back to Windows Start and open up IDLE again, this time opening file progB.py. I run the program, and when prompted for input I enter "x" + <Enter> and then "y" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progB.py =
progB is running x
x
progB is running y
y
progB is running 

Now two IDLE Python 3.6.3 Shell programs are running at the same time, one shell running progA while the other one is running progB.

What is the difference between $routeProvider and $stateProvider?

$route: This is used for deep-linking URLs to controllers and views (HTML partials) and watches $location.url() in order to map the path from an existing definition of route.

When we use ngRoute, the route is configured with $routeProvider and when we use ui-router, the route is configured with $stateProvider and $urlRouterProvider.

<div ng-view></div>
    $routeProvider
        .when('/contact/', {
            templateUrl: 'app/views/core/contact/contact.html',
            controller: 'ContactCtrl'
        });


<div ui-view>
    <div ui-view='abc'></div>
    <div ui-view='abc'></div>
   </div>
    $stateProvider
        .state("contact", {
            url: "/contact/",
            templateUrl: '/app/Aisel/Contact/views/contact.html',
            controller: 'ContactCtrl'
        });

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can call a stored procedure from another stored procedure by using the EXECUTE command.

Say your procedure is X. Then in X you can use

EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"

configure: error: C compiler cannot create executables

I just had this issue building react-native app when I try to install Pod. I had to export 2 variables:

export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
CPP='/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -E'

What does Html.HiddenFor do?

It creates a hidden input on the form for the field (from your model) that you pass it.

It is useful for fields in your Model/ViewModel that you need to persist on the page and have passed back when another call is made but shouldn't be seen by the user.

Consider the following ViewModel class:

public class ViewModel
{
    public string Value { get; set; }
    public int Id { get; set; }
}

Now you want the edit page to store the ID but have it not be seen:

<% using(Html.BeginForm() { %>
    <%= Html.HiddenFor(model.Id) %><br />
    <%= Html.TextBoxFor(model.Value) %>
<% } %>

This results in the equivalent of the following HTML:

<form name="form1">
    <input type="hidden" name="Id">2</input>
    <input type="text" name="Value" value="Some Text" />
</form>

JSON Java 8 LocalDateTime format in Spring Boot

This work fine:

Add the dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>

Add the annotation:

@JsonFormat(pattern="yyyy-MM-dd")

Now, you must get the correct format.

To use object mapper, you need register the JavaTime

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

Trying to start a service on boot on Android

Before mounting external storage BOOT_COMPLETE is sent execute.if your app is installed to external storage it won't receive BOOT_COMPLETE broadcast message. To prevent this you can install your application in internal storage. you can do this just adding this line in menifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly"
... >

Some HTC devices can enable a "fast boot" feature that is more like a deep hibernation and not a real reboot and therefore should not give the BOOT_COMPLETE intent. To recover this you can add this intent filter inside your receiver:

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>

Excel SUMIF between dates

this works, and can be adapted for weeks or anyother frequency i.e. weekly, quarterly etc...

=SUMIFS(B12:B11652,A12:A11652,">="&DATE(YEAR(C12),MONTH(C12),1),A12:A11652,"<"&DATE(YEAR(C12),MONTH(C12)+1,1))

Create a batch file to run an .exe with an additional parameter

in batch file abc.bat

cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3 

I am assuming that your executible.exe is present in c:\user\ben_dchost\documents\ I am also assuming that the parameters it takes are -flag1 -flag2 -flag3

Edited:

For the command you say you want to execute, do:

cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause

Hope this helps

Jquery : Refresh/Reload the page on clicking a button

If your button is loading from an AJAX call, you should use

$(document).on("click", ".delegate_update_success", function(){
    location.reload(true);
});

instead of

$( ".delegate_update_success" ).click(function() {
    location.reload();
});

Also note the true parameter for the location.reload function.

Set value of hidden input with jquery

var test = $('input[name="testing"]:hidden');
test.val('work!');

What are the pros and cons of parquet format compared to other formats?

Choosing the right file format is important to building performant data applications. The concepts outlined in this post carry over to Pandas, Dask, Spark, and Presto / AWS Athena.

Column pruning

Column pruning is a big performance improvement that's possible for column-based file formats (Parquet, ORC) and not possible for row-based file formats (CSV, Avro).

Suppose you have a dataset with 100 columns and want to read two of them into a DataFrame. Here's how you can perform this with Pandas if the data is stored in a Parquet file.

import pandas as pd

pd.read_parquet('some_file.parquet', columns = ['id', 'firstname'])

Parquet is a columnar file format, so Pandas can grab the columns relevant for the query and can skip the other columns. This is a massive performance improvement.

If the data is stored in a CSV file, you can read it like this:

import pandas as pd

pd.read_csv('some_file.csv', usecols = ['id', 'firstname'])

usecols can't skip over entire columns because of the row nature of the CSV file format.

Spark doesn't require users to explicitly list the columns that'll be used in a query. Spark builds up an execution plan and will automatically leverage column pruning whenever possible. Of course, column pruning is only possible when the underlying file format is column oriented.

Popularity

Spark and Pandas have built-in readers writers for CSV, JSON, ORC, Parquet, and text files. They don't have built-in readers for Avro.

Avro is popular within the Hadoop ecosystem. Parquet has gained significant traction outside of the Hadoop ecosystem. For example, the Delta Lake project is being built on Parquet files.

Arrow is an important project that makes it easy to work with Parquet files with a variety of different languages (C, C++, Go, Java, JavaScript, MATLAB, Python, R, Ruby, Rust), but doesn't support Avro. Parquet files are easier to work with because they are supported by so many different projects.

Schema

Parquet stores the file schema in the file metadata. CSV files don't store file metadata, so readers need to either be supplied with the schema or the schema needs to be inferred. Supplying a schema is tedious and inferring a schema is error prone / expensive.

Avro also stores the data schema in the file itself. Having schema in the files is a huge advantage and is one of the reasons why a modern data project should not rely on JSON or CSV.

Column metadata

Parquet stores metadata statistics for each column and lets users add their own column metadata as well.

The min / max column value metadata allows for Parquet predicate pushdown filtering that's supported by the Dask & Spark cluster computing frameworks.

Here's how to fetch the column statistics with PyArrow.

import pyarrow.parquet as pq

parquet_file = pq.ParquetFile('some_file.parquet')
print(parquet_file.metadata.row_group(0).column(1).statistics)
<pyarrow._parquet.Statistics object at 0x11ac17eb0>
  has_min_max: True
  min: 1
  max: 9
  null_count: 0
  distinct_count: 0
  num_values: 3
  physical_type: INT64
  logical_type: None
  converted_type (legacy): NONE

Complex column types

Parquet allows for complex column types like arrays, dictionaries, and nested schemas. There isn't a reliable method to store complex types in simple file formats like CSVs.

Compression

Columnar file formats store related types in rows, so they're easier to compress. This CSV file is relatively hard to compress.

first_name,age
ken,30
felicia,36
mia,2

This data is easier to compress when the related types are stored in the same row:

ken,felicia,mia
30,36,2

Parquet files are most commonly compressed with the Snappy compression algorithm. Snappy compressed files are splittable and quick to inflate. Big data systems want to reduce file size on disk, but also want to make it quick to inflate the flies and run analytical queries.

Mutable nature of file

Parquet files are immutable, as described here. CSV files are mutable.

Adding a row to a CSV file is easy. You can't easily add a row to a Parquet file.

Data lakes

In a big data environment, you'll be working with hundreds or thousands of Parquet files. Disk partitioning of the files, avoiding big files, and compacting small files is important. The optimal disk layout of data depends on your query patterns.

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

As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }

How do you simulate Mouse Click in C#?

they are some needs i can't see to dome thing like Keith or Marcos Placona did instead of just doing

using System;
using System.Windows.Forms;

namespace WFsimulateMouseClick
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1_Click(button1, new MouseEventArgs(System.Windows.Forms.MouseButtons.Left, 1, 1, 1, 1));

            //by the way
            //button1.PerformClick();
            // and
            //button1_Click(button1, new EventArgs());
            // are the same
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
        }
    }
}

How do you add PostgreSQL Driver as a dependency in Maven?

Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml file.

For PostgreSQL 9.1 this would be:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
    </dependencies>
</project>

You can get the code for the dependency (as well as any other dependency) from maven's central repository

If you are using postgresql 9.2+:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.1</version>
        </dependency>
    </dependencies>
</project>

You can check the latest versions and dependency snippets from:

Relative Paths in Javascript in an external file

For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:

<body>

<script>
    var templatesPath = "@Url.Content("~/Templates/")";
</script>

<div class="page">
    <div id="header">

       <span id="title">

        </span>
    </div>
    <div id="main">


        @RenderBody()
    </div>
    <div id="footer">
        <span></span>
    </div>
</div>

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

Java decimal formatting using String.format?

You want java.text.DecimalFormat

How do I delete an item or object from an array using ng-click?

This is a correct answer:

<a class="btn" ng-click="remove($index)">Delete</a>
$scope.remove=function($index){ 
  $scope.bdays.splice($index,1);     
}

In @charlietfl's answer. I think it's wrong since you pass $index as paramter but you use the wish instead in controller. Correct me if I'm wrong :)

Android studio - Failed to find target android-18

Check the local.properties file in your Studio Project. Chances are that the property sdk.dir points to the wrong folder if you had set/configured a previous android sdk from pre-studio era. This was the solution in my case.

return in for loop or outside loop

Since there is no issue with GC. I prefer this.

for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind)
        return true;
}

Cookie blocked/not saved in IFRAME in Internet Explorer

I've implemented a full P3P policy before but didn't want go through the hassle again for a new project I was working on. I found this link useful for a simple solution to the problem, only having to specify a minimal compact P3P policy of "CAO PSA OUR":

http://blog.sweetxml.org/2007/10/minimal-p3p-compact-policy-suggestion.html

The article quotes a (now broken) link to a Microsoft kb article. The policy did the trick for me!

Difference between two DateTimes C#?

You can do the following:

TimeSpan duration = b - a;

There's plenty of built in methods in the timespan class to do what you need, i.e.

duration.TotalSeconds
duration.TotalMinutes

More info can be found here.

How does collections.defaultdict work?

My own 2¢: you can also subclass defaultdict:

class MyDict(defaultdict):
    def __missing__(self, key):
        value = [None, None]
        self[key] = value
        return value

This could come in handy for very complex cases.

Counter in foreach loop in C#

This is only true if you're iterating through an array; what if you were iterating through a different kind of collection that has no notion of accessing by index? In the array case, the easiest way to retain the index is to simply use a vanilla for loop.

How can I split a text into sentences?

Was working on similar task and came across this query, by following few links and working on few exercises for nltk the below code worked for me like magic.

from nltk.tokenize import sent_tokenize 
  
text = "Hello everyone. Welcome to GeeksforGeeks. You are studying NLP article"
sent_tokenize(text) 

output:

['Hello everyone.',
 'Welcome to GeeksforGeeks.',
 'You are studying NLP article']

Source: https://www.geeksforgeeks.org/nlp-how-tokenizing-text-sentence-words-works/

Convert utf8-characters to iso-88591 and back in PHP

First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere.

Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use iconv or mb_convert_encoding.

Nevertheless, utf8_encode and utf8_decode should work for ISO-8859-1. It would be nice if you could post a link to a file or a uuencoded or base64 example string for which the conversion fails or yields unexpected results.

Image convert to Base64

Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.

The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)

Callback version

        File.prototype.convertToBase64 = function(callback){
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    callback(e.target.result, e.target.error);
                };   
                reader.readAsDataURL(this);
        };

        $("#asd").on('change',function(){
          var selectedFile = this.files[0];
          selectedFile.convertToBase64(function(base64){
               alert(base64);
          }) 
        });

Promise version

    File.prototype.convertToBase64 = function(){
         return new Promise(function(resolve, reject) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    resolve({
                      fileName: this.name,
                      result: e.target.result, 
                      error: e.target.error
                    });
                };   
                reader.readAsDataURL(this);
        }.bind(this)); 
    };

    FileList.prototype.convertAllToBase64 = function(regexp){
      // empty regexp if not set
      regexp = regexp || /.*/;
      //making array from FileList
      var filesArray = Array.prototype.slice.call(this);
      var base64PromisesArray = filesArray.
           filter(function(file){
             return (regexp).test(file.name)
           }).map(function(file){
             return file.convertToBase64();
           });
      return Promise.all(base64PromisesArray);
    };

    $("#asd").on('change',function(){
      //for one file
      var selectedFile = this.files[0];
      selectedFile.convertToBase64().
          then(function(obj){
            alert(obj.result);
          });
      });
      //for all files that have file extention png, jpeg, jpg, gif
      this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
            objArray.forEach(function(obj, i){
                  console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
            });
      });
    })

html

<input type="file" id="asd" multiple/>

get everything between <tag> and </tag> with php

this function worked for me

<?php

function everything_in_tags($string, $tagname)
{
    $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

?>

MVC 3: How to render a view without its layout page when loaded via ajax?

All you need is to create two layouts:

  1. an empty layout

  2. main layout

Then write the code below in _viewStart file:

@{
   if (Request.IsAjaxRequest())
   {
      Layout = "~/Areas/Dashboard/Views/Shared/_emptyLayout.cshtml";
   }
   else
   {
      Layout = "~/Areas/Dashboard/Views/Shared/_Layout.cshtml";
   }
 }

of course, maybe it is not the best solution

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

What is in your .vimrc?

Here's mine ! Thanks for sharing. You can find other stuff about vim plugins here: http://github.com/ametaireau/dotfiles/

Hope it helps.

" My .vimrc configuration file.
" =============================
"
" Plugins
" -------
" Comes with a set of utilities to enhance the user experience.
" Django and python snippets are possible thanks to the snipmate
" plugin.
"
" A also uses taglist and NERDTree vim plugins.
"
" Shortcuts
" ----------
" Here are some shortcuts I like to use when editing text using VIM:
"
" <alt-left/right> to navigate trough tabs
" <ctrl-e> to display the explorator
" <ctrl-p> for the code explorator
" <ctrl-space> to autocomplete
" <ctrl-n> enter tabnew to open a new file
" <alt-h> highlight the lines of more than 80 columns
" <ctrl-h> set textwith to 80 cols
" <maj-k> when on a python file, open the related pydoc documentation
" ,v and ,V to show/edit and reload the vimrc configuration file

colorscheme evening 
syntax on                       " syntax highlighting
filetype on                     " to consider filetypes ...
filetype plugin on              " ... and in plugins
set directory=~/.vim/swp        " store the .swp files in a specific path
set expandtab                   " enter spaces when tab is pressed
set tabstop=4                   " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4                " number of spaces to use for auto indent
set autoindent                  " copy indent from current line on new line
set number                      " show line numbers
set backspace=indent,eol,start  " make backspaces more powerful 
set ruler                       " show line and column number
set showcmd                     " show (partial) command in status line
set incsearch                   " highlight search
set noignorecase
set infercase
set nowrap

" shortcuts
map <c-n> :tabnew 
map <silent><c-e> :NERDTreeToggle <cr>
map <silent><c-p> :TlistToggle <cr>
nnoremap <a-right> gt
nnoremap <a-left>  gT
command W w !sudo tee % > /dev/null
map <buffer> K :execute "!pydoc " . expand("<cword>")<CR>
map <F2> :set textwidth=80 <cr>
" Replace trailing slashes
map <F3> :%s/\s\+$//<CR>:exe ":echo'trailing slashes removes'"<CR>
map <silent><F6> :QFix<CR>

" edit vim quickly
map ,v :sp ~/.vimrc<CR><C-W>_
map <silent> ,V :source ~/.vimrc<CR>:filetype detect<CR>:exe ":echo'vimrc reloaded'"<CR> 

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set noexpandtab
au BufRead,BufNewFile *.h set noexpandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" remap CTRL+N to CTRL + space
inoremap <Nul> <C-n>

" Omnifunc completers
autocmd FileType python set omnifunc=pythoncomplete#Complete

" Tlist configuration
let Tlist_GainFocus_On_ToggleOpen = 1
let Tlist_Close_On_Select = 0
let Tlist_Auto_Update = 1
let Tlist_Process_File_Always = 1
let Tlist_Use_Right_Window = 1
let Tlist_WinWidth = 40
let Tlist_Show_One_File = 1
let Tlist_Show_Menu = 0
let Tlist_File_Fold_Auto_Close = 0
let Tlist_Ctags_Cmd = '/usr/bin/ctags'
let tlist_css_settings = 'css;e:SECTIONS'

" NerdTree configuration
let NERDTreeIgnore = ['\.pyc$', '\.pyo$']

" Highlight more than 80 columns lines on demand
nnoremap <silent><F1>
\    :if exists('w:long_line_match') <Bar>
\        silent! call matchdelete(w:long_line_match) <Bar>
\        unlet w:long_line_match <Bar>
\    elseif &textwidth > 0 <Bar>
\        let w:long_line_match = matchadd('ErrorMsg', '\%>'.&tw.'v.\+', -1) <Bar>
\    else <Bar>
\        let w:long_line_match = matchadd('ErrorMsg', '\%>80v.\+', -1) <Bar>
\    endif<CR>

command -bang -nargs=? QFix call QFixToggle(<bang>0)
function! QFixToggle(forced)
  if exists("g:qfix_win") && a:forced == 0
    cclose
    unlet g:qfix_win
  else
    copen 10
    let g:qfix_win = bufnr("$")
  endif
endfunction

How to write to files using utl_file in oracle

Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.

PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS

              vLine VARCHAR2(30000);
              vFile UTL_FILE.file_type; 
              vExists boolean;
              vLength number;
              vBlockSize number;
    BEGIN

        UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);

                 FETCH p_Input INTO vLine;
         IF p_input%ROWCOUNT > 0
         THEN
            IF vExists THEN
               vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
            ELSE
               --even if the append flag is passed if the file doesn't exist open it with W.
                vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
            END IF;
            --GET HANDLE TO FILE
            IF p_Header IS NOT NULL THEN 
              UTL_FILE.PUT_LINE(vFile, p_Header);
            END IF;
            UTL_FILE.PUT_LINE(vFile, vLine);
            DBMS_OUTPUT.PUT_LINE('Record count > 0');

             --LOOP THROUGH CURSOR VAR
             LOOP
                FETCH p_Input INTO vLine;

                EXIT WHEN p_Input%NOTFOUND;

                UTL_FILE.PUT_LINE(vFile, vLine);

             END LOOP;


             IF p_Footer IS NOT NULL THEN 
                UTL_FILE.PUT_LINE(vFile, p_Footer);
             END IF;

             CLOSE p_Input;
             UTL_FILE.FCLOSE(vFile);
        ELSE
          DBMS_OUTPUT.PUT_LINE('Record count = 0');

        END IF; 


    EXCEPTION
       WHEN UTL_FILE.INVALID_PATH THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_path'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_MODE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_mode'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_FILEHANDLE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_filehandle'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_OPERATION THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_operation'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.READ_ERROR THEN  
           DBMS_OUTPUT.PUT_LINE ('read_error');
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.WRITE_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('write_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INTERNAL_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('internal_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;            
       WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE ('other write error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;
    END;

With MySQL, how can I generate a column containing the record index in a table?

You may want to try the following:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r;

The JOIN (SELECT @curRow := 0) part allows the variable initialization without requiring a separate SET command.

Test case:

CREATE TABLE league_girl (position int, username varchar(10), score int);
INSERT INTO league_girl VALUES (1, 'a', 10);
INSERT INTO league_girl VALUES (2, 'b', 25);
INSERT INTO league_girl VALUES (3, 'c', 75);
INSERT INTO league_girl VALUES (4, 'd', 25);
INSERT INTO league_girl VALUES (5, 'e', 55);
INSERT INTO league_girl VALUES (6, 'f', 80);
INSERT INTO league_girl VALUES (7, 'g', 15);

Test query:

SELECT  l.position, 
        l.username, 
        l.score,
        @curRow := @curRow + 1 AS row_number
FROM    league_girl l
JOIN    (SELECT @curRow := 0) r
WHERE   l.score > 50;

Result:

+----------+----------+-------+------------+
| position | username | score | row_number |
+----------+----------+-------+------------+
|        3 | c        |    75 |          1 |
|        5 | e        |    55 |          2 |
|        6 | f        |    80 |          3 |
+----------+----------+-------+------------+
3 rows in set (0.00 sec)

How do I avoid the specification of the username and password at every git push?

If you already have your SSH keys set up and are still getting the password prompt, make sure your repo URL is in the form

git+ssh://[email protected]/username/reponame.git

as opposed to

https://github.com/username/reponame.git

To see your repo URL, run:

git remote show origin

You can change the URL with git remote set-url like so:

git remote set-url origin git+ssh://[email protected]/username/reponame.git

ProcessStartInfo hanging on "WaitForExit"? Why?

The documentation for Process.StandardOutput says to read before you wait otherwise you can deadlock, snippet copied below:

 // Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

How to create a signed APK file using Cordova command line interface?

For Windows, I've created a build.cmd file:

(replace the keystore path and alias)

For Cordova:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

And for Ionic:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

Save it in the ptoject's directory, you can double click or open it with cmd.

How do I repair an InnoDB table?

Step 1.

Stop MySQL server

Step 2.

add this line to my.cnf ( In windows it is called my.ini )

set-variable=innodb_force_recovery=6

Step 3.

delete ib_logfile0 and ib_logfile1

Step 4.

Start MySQL server

Step 5.

Run this command:

mysqlcheck --database db_name table_name -uroot -p

After you have successfully fixed the crashed innodb table, don't forget to remove #set-variable=innodb_force_recovery=6 from my.cnf and then restart MySQL server again.

Is it good practice to use the xor operator for boolean checks?

str.contains("!=") ^ str.startsWith("not(")

looks better for me than

str.contains("!=") != str.startsWith("not(")

How can I restart a Java application?

System.err.println("Someone is Restarting me...");
setVisible(false);
try {
    Thread.sleep(600);
} catch (InterruptedException e1) {
    e1.printStackTrace();
}
setVisible(true);

I guess you don't really want to stop the application, but to "Restart" it. For that, you could use this and add your "Reset" before the sleep and after the invisible window.

Is it possible to append to innerHTML without destroying descendants' event listeners?

You could do it like this:

var anchors = document.getElementsByTagName('a'); 
var index_a = 0;
var uls = document.getElementsByTagName('UL'); 
window.onload=function()          {alert(anchors.length);};
for(var i=0 ; i<uls.length;  i++)
{
    lis = uls[i].getElementsByTagName('LI');
    for(var j=0 ;j<lis.length;j++)
    {
        var first = lis[j].innerHTML; 
        string = "<img src=\"http://g.etfv.co/" +  anchors[index_a++] + 
            "\"  width=\"32\" 
        height=\"32\" />   " + first;
        lis[j].innerHTML = string;
    }
}

convert string to specific datetime format?

No need to apply anything. Just add this code at the end of variable to which date is assigned. For example

   @todaydate = "2011-05-19 10:30:14"
   @todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')

You will get proper format as you like. You can check this at Rails Console

Loading development environment (Rails 3.0.4)
ruby-1.9.2-p136 :001 > todaytime = "2011-05-19 10:30:14"
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :002 > todaytime
 => "2011-05-19 10:30:14" 
ruby-1.9.2-p136 :003 > todaytime.to_time
 => 2011-05-19 10:30:14 UTC
ruby-1.9.2-p136 :008 > todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y')
 => "Thu May 19 10:30:14 UTC 2011"

Try 'date_format' gem to show date in different format.

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Put this formula in cell d31 and copy down to d39

 =iferror(vlookup(b31,$f$3:$g$12,2,0),"")

Here's what is going on. VLOOKUP:

  • Takes a value (here the contents of b31),
  • Looks for it in the first column of a range (f3:f12 in the range f3:g12), and
  • Returns the value for the corresponding row in a column in that range (in this case, the 2nd column or g3:g12 of the range f3:g12).

As you know, the last argument of VLOOKUP sets the match type, with FALSE or 0 indicating an exact match.

Finally, IFERROR handles the #N/A when VLOOKUP does not find a match.

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

On most installs you can find it here:

/etc/php.ini

How do you reverse a string in place in C or C++?

void reverseString(vector<char>& s) {
        int l = s.size();
        char ch ;
        int i = 0 ;
        int j = l-1;
        while(i < j){
                s[i] = s[i]^s[j];
                s[j] = s[i]^s[j];
                s[i] = s[i]^s[j];
                i++;
                j--;
        }
        for(char c : s)
                cout <<c ;
        cout<< endl;
}

Capturing count from an SQL query

int count = 0;    
using (new SqlConnection connection = new SqlConnection("connectionString"))
{
    sqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM table_name", connection);
    connection.Open();
    count = (int32)cmd.ExecuteScalar();
}

Android sample bluetooth code to send a simple string via bluetooth

I made the following code so that even beginners can understand. Just copy the code and read comments. Note that message to be send is declared as a global variable which you can change just before sending the message. General changes can be done in Handler function.

multiplayerConnect.java

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

public class multiplayerConnect extends AppCompatActivity {

public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;


String bluetooth_message="00";




@SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
    @Override
    public void handleMessage(Message msg_type) {
        super.handleMessage(msg_type);

        switch (msg_type.what){
            case MESSAGE_READ:

                byte[] readbuf=(byte[])msg_type.obj;
                String string_recieved=new String(readbuf);

                //do some task based on recieved string

                break;
            case MESSAGE_WRITE:

                if(msg_type.obj!=null){
                    ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
                    connectedThread.write(bluetooth_message.getBytes());

                }
                break;

            case CONNECTED:
                Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
                break;

            case CONNECTING:
                Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
                break;

            case NO_SOCKET_FOUND:
                Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
                break;
        }
    }
};



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.multiplayer_bluetooth);
    initialize_layout();
    initialize_bluetooth();
    start_accepting_connection();
    initialize_clicks();

}

public void start_accepting_connection()
{
    //call this on button click as suited by you

    AcceptThread acceptThread = new AcceptThread();
    acceptThread.start();
    Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
    lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Object[] objects = set_pairedDevices.toArray();
            BluetoothDevice device = (BluetoothDevice) objects[position];

            ConnectThread connectThread = new ConnectThread(device);
            connectThread.start();

            Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
        }
    });
}

public void initialize_layout()
{
    lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
    adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
    lv_paired_devices.setAdapter(adapter_paired_devices);
}

public void initialize_bluetooth()
{
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        // Device doesn't support Bluetooth
        Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
        finish();
    }

    //Add these permisions before
//        <uses-permission android:name="android.permission.BLUETOOTH" />
//        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
//        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
//        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    if (!bluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    else {
        set_pairedDevices = bluetoothAdapter.getBondedDevices();

        if (set_pairedDevices.size() > 0) {

            for (BluetoothDevice device : set_pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress(); // MAC address

                adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
            }
        }
    }
}


public class AcceptThread extends Thread
{
    private final BluetoothServerSocket serverSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
        } catch (IOException e) { }
        serverSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                break;
            }

            // If a connection was accepted
            if (socket != null)
            {
                // Do work to manage the connection (in a separate thread)
                mHandler.obtainMessage(CONNECTED).sendToTarget();
            }
        }
    }
}


private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        bluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mHandler.obtainMessage(CONNECTING).sendToTarget();

            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)
//            bluetooth_message = "Initial message"
//            mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[2];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

multiplayer_bluetooth.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Challenge player"/>

    <ListView
        android:id="@+id/lv_paired_devices"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </ListView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Make sure Device is paired"/>

</LinearLayout>

Removing the fragment identifier from AngularJS urls (# symbol)

To remove the Hash tag for a pretty URL and also for your code to work after minification you need to structure your code like the example below:

jobApp.config(['$routeProvider','$locationProvider',
    function($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'views/job-list.html',
                controller: 'JobListController'
            }).
            when('/menus', {
                templateUrl: 'views/job-list.html',
                controller: 'JobListController'
            }).
            when('/menus/:id', {
                templateUrl: 'views/job-detail.html',
                controller: 'JobDetailController'
            });

         //you can include a fallback by  including .otherwise({
          //redirectTo: '/jobs'
        //});


        //check browser support
        if(window.history && window.history.pushState){
            //$locationProvider.html5Mode(true); will cause an error $location in HTML5 mode requires a  tag to be present! Unless you set baseUrl tag after head tag like so: <head> <base href="/">

         // to know more about setting base URL visit: https://docs.angularjs.org/error/$location/nobase

         // if you don't wish to set base URL then use this
         $locationProvider.html5Mode({
                 enabled: true,
                 requireBase: false
          });
        }
    }]);

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

The Concat method will return an object which implements IEnumerable<T> by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList() on Cat and use the resulting List<T> (which will represent a snapshot of the contents of A and B).

Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.

find without recursion

I think you'll get what you want with the -maxdepth 1 option, based on your current command structure. If not, you can try looking at the man page for find.

Relevant entry (for convenience's sake):

-maxdepth levels
          Descend at most levels (a non-negative integer) levels of direc-
          tories below the command line arguments.   `-maxdepth  0'  means
          only  apply the tests and actions to the command line arguments.

Your options basically are:

# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f

Or:

#  DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f

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

I love jtbandes answer, but since it is pretty long, I will add my own compact answer:

==, ===, eql?, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:

== (value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:

{a: 'z'}  ==  {a: 'Z'}    # => false
{a: 1}    ==  {a: 1.0}    # => true

=== (case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:

case foo
  when bar;  p 'do something'
end

if bar === foo
  p 'do something'
end

eql? (Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:

class Equ
  attr_accessor :val
  alias_method  :initialize, :val=
  def hash()           self.val % 2             end
  def eql?(other)      self.hash == other.hash  end
end

h = {Equ.new(3) => 3,  Equ.new(8) => 8,  Equ.new(15) => 15}    #3 entries, but 2 are :eql?
h.size            # => 2
h[Equ.new(27)]    # => 15

Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.

equal? (object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.

obj = obj2 = 'a'
obj.equal? obj2       # => true
obj.equal? obj.dup    # => false

Is there a vr (vertical rule) in html?

An <hr> inside a display:flex will make it display vertically.

JSFiddle: https://jsfiddle.net/w6y5t1kL/

Example:

<div style="display:flex;">
  <div>
    Content
    <ul>
      <li>Continued content...</li>
    </ul>
  </div>
  <hr>
  <div>
    Content
    <ul>
      <li>Continued content...</li>
    </ul>
  </div>
</div>

Yarn: How to upgrade yarn version using terminal?

For macOS users, if you installed yarn via brew, you can upgrade it using the below command:

brew upgrade yarn

On Linux, just run the below command at the terminal:

$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

On Windows, upgrade with Chocolatey

choco upgrade yarn

Credits: Added answers with the help of the below answers

printf with std::string?

It's compiling because printf isn't type safe, since it uses variable arguments in the C sense1. printf has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.

The easiest way to fix this, since you're using C++, is printing it normally with std::cout, since std::string supports that through operator overloading:

std::cout << "Follow this command: " << myString;

If, for some reason, you need to extract the C-style string, you can use the c_str() method of std::string to get a const char * that is null-terminated. Using your example:

#include <iostream>
#include <string>
#include <stdio.h>

int main()
{
    using namespace std;

    string myString = "Press ENTER to quit program!";
    cout << "Come up and C++ me some time." << endl;
    printf("Follow this command: %s", myString.c_str()); //note the use of c_str
    cin.get();

    return 0;
}

If you want a function that is like printf, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format.


[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf, that means a string with encoded type information like %d meaning int. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.

Closing a Userform with Unload Me doesn't work

Without seeing your full code, this is impossible to answer with any certainty. The error usually occurs when you are trying to unload a control rather than the form.

Make sure that you don't have the "me" in brackets.

Also if you can post the full code for the userform it would help massively.

Get file name from URL

If you don't need to get rid of the file extension, here's a way to do it without resorting to error-prone String manipulation and without using external libraries. Works with Java 1.7+:

import java.net.URI
import java.nio.file.Paths

String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()

Removing address bar from browser (to view on Android)

Finally I Try with this. Its worked for me..

  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ebook);

    //webview use to call own site
    webview =(WebView)findViewById(R.id.webView1);

    webview.setWebViewClient(new WebViewClient());       
    webview .getSettings().setJavaScriptEnabled(true);
    webview .getSettings().setDomStorageEnabled(true);     
    webview.loadUrl("http://www.google.com"); 
}

and your entire main.xml(res/layout) look should like this:

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

don't go to add layouts.

SQL 'like' vs '=' performance

If value is unindexed, both result in a table-scan. The performance difference in this scenario will be negligible.

If value is indexed, as Daniel points out in his comment, the = will result in an index lookup which is O(log N) performance. The LIKE will (most likely - depending on how selective it is) result in a partial scan of the index >= 'abc' and < 'abd' which will require more effort than the =.

Note that I'm talking SQL Server here - not all DBMSs will be nice with LIKE.

How to mount a host directory in a Docker container

I'm just experimenting with getting my SailsJS app running inside a Docker container to keep my physical machine clean.

I'm using the following command to mount my SailsJS/NodeJS application under /app:

cd my_source_code_folder
docker run -it -p 1337:1337 -v $(pwd):/app my_docker/image_with_nodejs_etc

Write to UTF-8 file in Python

@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.

Jon Skeet is right (unusual) about the codecs module - it contains byte strings:

>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>> 

Picking another nit, the BOM has a standard Unicode name, and it can be entered as:

>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'

It is also accessible via unicodedata:

>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>> 

org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 15

I've had the same problem when running my spring boot application with tomcat7:run

It gives error with the following dependency in maven pom.xml:

    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
    </dependency>
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/.m2/repository/org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19

Jul 09, 2020 1:28:09 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [module-info.class] from Jar [jar:file:/.m2/repository/org/apiguardian/apiguardian-api/1.1.0/apiguardian-api-1.1.0.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19

But when I correctly specify it in test scope, it does not give error:

    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <scope>test</scope>
    </dependency>

Font awesome is not showing icon

You needed to close your `<link />` 
As you can see in your <head></head> tag. This will solve your problem

<head>
    <link rel="stylesheet" href="../css/font-awesome.css" />
    <link rel="stylesheet" href="../css/font-awesome.min.css" />
</head>

How to get HTTP response code for a URL in Java?

URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();

Showing all errors and warnings

PHP errors can be displayed by any of below methods:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For more details:

Displaying PHP errors

How to access model hasMany Relation with where condition?

//lower for v4 some version

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}

//v5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}

get path for my .exe

In addition:

AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location

Draw on HTML5 Canvas using a mouse

Here's the most straightforward way to create a drawing application with canvas:

  1. Attach a mousedown, mousemove, and mouseup event listener to the canvas DOM
  2. on mousedown, get the mouse coordinates, and use the moveTo() method to position your drawing cursor and the beginPath() method to begin a new drawing path.
  3. on mousemove, continuously add a new point to the path with lineTo(), and color the last segment with stroke().
  4. on mouseup, set a flag to disable the drawing.

From there, you can add all kinds of other features like giving the user the ability to choose a line thickness, color, brush strokes, and even layers.

Best practices for circular shift (rotate) operations in C++

#define ROTATE_RIGHT(x) ( (x>>1) | (x&1?0x8000:0) )

Use dynamic (variable) string as regex pattern in JavaScript

I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:

    str = "1x";
    var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
    inv=inv.replace(regex, "");

How can I suppress the newline after a print statement?

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

Git clone particular version of remote repository

uploadpack.allowReachableSHA1InWant

Since Git 2.5.0 this configuration variable can be enabled on the server, here the GitHub feature request and the GitHub commit enabling this feature.

Bitbucket Server enabled it since version 5.5+.

Usage:

# Make remote with 4 commits, and local with just one.
mkdir server
cd server
git init
touch 1
git add 1
git commit -m 1
git clone ./ ../local
for i in {2..4}; do
    touch "$i"
    git add "$i"
    git commit -m "$i"
done

# Before last commit.
SHA3="$(git log --format='%H' --skip=1 -n1)"
# Last commit.
SHA4="$(git log --format='%H' -n1)"

# Failing control without feature.
cd ../local
# Does not give an error, but does not fetch either.
git fetch origin "$SHA3"
# Error.
git checkout "$SHA3"

# Enable the feature.
cd ../server
git config uploadpack.allowReachableSHA1InWant true

# Now it works.
cd ../local
git fetch origin "$SHA3"
git checkout "$SHA3"
# Error.
git checkout "$SHA4"

Resource files not found from JUnit test cases

Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.

<maven.test.skip>false</maven.test.skip>

How much faster is C++ than C#?

In my experience (and I have worked a lot with both languages), the main problem with C# compared to C++ is high memory consumption, and I have not found a good way to control it. It was the memory consumption that would eventually slow down .NET software.

Another factor is that JIT compiler cannot afford too much time to do advanced optimizations, because it runs at runtime, and the end user would notice it if it takes too much time. On the other hand, a C++ compiler has all the time it needs to do optimizations at compile time. This factor is much less significant than memory consumption, IMHO.

'setInterval' vs 'setTimeout'

setInterval repeats the call, setTimeout only runs it once.

How to change the default encoding to UTF-8 for Apache?

This is untested but will probably work.

In your .htaccess file put:

<Files ~ "\.html?$">  
     Header set Content-Type "text/html; charset=utf-8"
</Files>

However, this will require mod_headers on the server.

PHP: How to remove specific element from an array?

I would prefer to use array_key_exists to search for keys in arrays like:

Array([0]=>'A',[1]=>'B',['key'=>'value'])

to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().

I think it will help someone.

CodeIgniter -> Get current URL relative to base url

you can use the some Codeigniter functions and some core functions and make combination to achieve your URL with query string. I found solution of this problem.

base_url($this->uri->uri_string()).strrchr($_SERVER['REQUEST_URI'], "?");

and if you loaded URL helper so you can also do this current_url().strrchr($_SERVER['REQUEST_URI'], "?");

How to present UIActionSheet iOS Swift?

Updated for Swift 4

Works for iOS 11

Some of the other answers are okay but I ended up mixing and matching a few of them to rather come up with this :

@IBAction func showAlert(sender: AnyObject) {
    let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)
    
    alert.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
        print("User click Approve button")
    }))
    
    alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
        print("User click Edit button")
    }))

    alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
        print("User click Delete button")
    }))
    
    alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler:{ (UIAlertAction)in
        print("User click Dismiss button")
    }))

    
    //uncomment for iPad Support
    //alert.popoverPresentationController?.sourceView = self.view

    self.present(alert, animated: true, completion: {
        print("completion block")
    })
}

Enjoy :)

How to change the default GCC compiler in Ubuntu?

I used just the lines below and it worked. I just wanted to compile VirtualBox and VMWare WorkStation using kernel 4.8.10 on Ubuntu 14.04. Initially, most things were not working for example graphics and networking. I was lucky that VMWare workstation requested for gcc 6.2.0. I couldn't start my Genymotion Android emulators because virtualbox was down. Will post results later if necessary.

VER=4.6 ; PRIO=60
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=6 ; PRIO=50
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER
VER=4.8 ; PRIO=40
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-$VER $PRIO --slave /usr/bin/g++ g++ /usr/bin/g++-$VER

How to convert entire dataframe to numeric while preserving decimals?

df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))

Check if a value is in an array (C#)

Add necessary namespace

using System.Linq;

Then you can use linq Contains() method

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
    Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

i also facing this same problem in django server.So i changed DEBUG = True in settings.py file its working

How to convert a char to a String?

Below are various ways to convert to char c to String s (in decreasing order of speed and efficiency)

char c = 'a';
String s = String.valueOf(c);             // fastest + memory efficient
String s = Character.toString(c);
String s = new String(new char[]{c});
String s = String.valueOf(new char[]{c});
String s = new Character(c).toString();
String s = "" + c;                        // slowest + memory inefficient

python replace single backslash with double backslash

Use:

string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")

Escape the \ character.

Apache won't start in wamp

That is what I did and it helped me to find out what my Apache-PHP needed:

C:\Users\Admin>cd C:\wamp\bin\apache\apache2.4.9\bin

C:\wamp\bin\apache\apache2.4.9\bin>httpd -t
Syntax OK

C:\wamp\bin\apache\apache2.4.9\bin>httpd -k start
[Thu Apr 23 14:14:52.150189 2015] [mpm_winnt:error] [pid 3184:tid 112] 
(OS 2)The system cannot find the file specified.  : AH00436: 
No installed service named "Apache2.4".

C:\wamp\bin\apache\apache2.4.9\bin>

The most simple solution:

Uninstall and reinstall WAMP (do not even try to set it up on top of existing installation - it would not help)

P.S.

If you wonder how did I get to this situation, here is the answer: I was trying to install WAMP and it throws me an error in the middle of installation saying:

httpd.exe - System Error

The program can't start because MSVCR110.dll is missing from your computer. 
Try reinstalling the program to fix this problem.

OK

I got and installed Microsoft Visual C++ 2012 Redistributable from here http://www.microsoft.com/en-us/download/details.aspx?id=30679#

And it gave me the "dll" and the MYSQL started working, but not Apache. To make Apache to work I uninstalled and reinstalled WAMP.

Android - How to get application name? (Not package name)

Java

public static String getApplicationName(Context context) {
    return context.getApplicationInfo().loadLabel(context.getPackageManager()).toString();
}

Kotlin (as extension)

fun Context.getAppName(): String = applicationInfo.loadLabel(packageManager).toString()

What is the Simplest Way to Reverse an ArrayList?

Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

 public ArrayList<Object> reverse(ArrayList<Object> list) {

   for (int i = 0; i < list.size() / 2; i++) {
     Object temp = list.get(i);
     list.set(i, list.get(list.size() - i - 1));
     list.set(list.size() - i - 1, temp);
   }

   return list;
 }

Read large files in Java

You can consider using memory-mapped files, via FileChannels .

Generally a lot faster for large files. There are performance trade-offs that could make it slower, so YMMV.

Related answer: Java NIO FileChannel versus FileOutputstream performance / usefulness

jQuery post() with serialize and extra data

When you want to add a javascript object to the form data, you can use the following code

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
    if (data.hasOwnProperty(key)) {
        postData.push({name:key, value:data[key]});
    }
}
$.post(url, postData, function(){});

Or if you add the method serializeObject(), you can do the following

var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});

HTML tag inside JavaScript

You will either have to document.write it or use the Document Object Model:

Example using document.write

<script type="text/javascript">
if(document.getElementById('number1').checked) {
    document.write("<h1>Hello member</h1>");
}
</script>

Example using DOM

<h1></h1> <!-- We are targeting this tag with JS. See code below -->
<input type="checkbox" id="number1" checked /><label for="number1">Agree</label>
<div id="container"> <p>Content</p> </div>

<script type="text/javascript">
window.onload = function() {
    if( document.getElementById('number1').checked ) {
        var h1 = document.createElement("h1");
        h1.appendChild(document.createTextNode("Hello member"));
        document.getElementById("container").appendChild(h1);
    }
}
</script>

jQuery - How to dynamically add a validation rule

To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like

$("#DivIdContainer .classToValidate").each(function () {
    $(this).rules('add', {
        required: true
    });
});

How do I download a tarball from GitHub using cURL?

All the other solutions require specifying a release/version number which obviously breaks automation.

This solution- currently tested and known to work with Github API v3- however can be used programmatically to grab the LATEST release without specifying any tag or release number and un-TARs the binary to an arbitrary name you specify in switch --one-top-level="pi-ap". Just swap-out user f1linux and repo pi-ap in below example with your own details and Bob's your uncle:

curl -L https://api.github.com/repos/f1linux/pi-ap/tarball | tar xzvf - --one-top-level="pi-ap" --strip-components 1

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);

What is the problem with shadowing names defined in outer scopes?

A good workaround in some cases may be to move the variables and code to another function:

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

Can I get the name of the currently running function in JavaScript?

For non-anonymous functions

function foo()
{ 
    alert(arguments.callee.name)
}

But in case of an error handler the result would be the name of the error handler function, wouldn't it?

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

Search for an item in a Lua list

You're seeing firsthand one of the cons of Lua having only one data structure---you have to roll your own. If you stick with Lua you will gradually accumulate a library of functions that manipulate tables in the way you like to do things. My library includes a list-to-set conversion and a higher-order list-searching function:

function table.set(t) -- set of list
  local u = { }
  for _, v in ipairs(t) do u[v] = true end
  return u
end

function table.find(f, l) -- find element v of l satisfying f(v)
  for _, v in ipairs(l) do
    if f(v) then
      return v
    end
  end
  return nil
end

Razor View throwing "The name 'model' does not exist in the current context"

In my case, the issue was that after upgrading the project from MVC 4 to MVC 5 I somehow missed a version change in the Views/web.config:

    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">            

It still had the old 2.0.0.0 version. After changing the version to 3.0.0.0 everything started working just right.

Also, because of this problem, Visual Studio 2015 Community Edition would start bashing the CPU (30-40% usage at idle) every time I would open a .cshtml file.

Regular cast vs. static_cast vs. dynamic_cast

Avoid using C-Style casts.

C-style casts are a mix of const and reinterpret cast, and it's difficult to find-and-replace in your code. A C++ application programmer should avoid C-style cast.

Splitting a string into separate variables

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

Get connection status on Socket.io client

Track the state of the connection yourself. With a boolean. Set it to false at declaration. Use the various events (connect, disconnect, reconnect, etc.) to reassign the current boolean value. Note: Using undocumented API features (e.g., socket.connected), is not a good idea; the feature could get removed in a subsequent version without the removal being mentioned.

In Python, how do you convert a `datetime` object to seconds?

Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:

>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0

# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)

Note that different timezones have impact on results, e.g. my current TZ/DST returns:

>>>  time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h

therefore one should consider normalizing to UTC by using UTC versions of the functions.

Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.

References:

How do I escape a single quote in SQL Server?

Just insert a ' before anything to be inserted. It will be like a escape character in sqlServer

Example: When you have a field as, I'm fine. you can do: UPDATE my_table SET row ='I''m fine.';

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

"inconsistent use of tabs and spaces in indentation"

With the IDLE editor you can use this:

  • Menu Edit ? Select All
  • Menu Format ? Untabify Region
  • Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
  • Hit select, and it fixes the entire document.

Maven and adding JARs to system scope

Thanks to Ging3r i got solution:

follow these steps:

  1. don't use in dependency tag. Use following in dependencies tag in pom.xml file::

    <dependency>
    <groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
    <artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
    <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
        <artifactId>suitetalk-client-v2019_1</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.netsuite.suitetalk.client.common</groupId>
        <artifactId>suitetalk-client-common</artifactId>
        <version>1.0.0</version>
    </dependency>
    
  2. use following code in plugins tag in pom.xml file:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.5.2</version>
            <executions>
                <execution>
                    <id>suitetalk-proxy</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-axis-proxy-v2019_1-1.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
                        <artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
                        <version>1.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>suitetalk-client</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-client-v2019_1-2.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
                        <artifactId>suitetalk-client-v2019_1</artifactId>
                        <version>2.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>suitetalk-client-common</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-client-common-1.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.client.common</groupId>
                        <artifactId>suitetalk-client-common</artifactId>
                        <version>1.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    

I am including 3 jars from lib folder:

including external jar in spring boot project

Finally, use mvn clean and then mvn install or 'mvn clean install' and just run jar file from target folder or the path where install(see mvn install log):

java -jar abc.jar

note: Remember one thing if you are working at jenkins then first use mvn clean and then mvn clean install command work for you because with previous code mvn clean install command store cache for dependency.

How to invert a grep expression

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

How to store images in mysql database using php

<!-- 
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])


CREATE TABLE  `images` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `image` longblob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

-->
<!-- this form is user to store images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />

<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>



<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
        mysql_connect("", "", "") OR DIE (mysql_error());
        mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
    header("location:search.php");

}

//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
        $name=$_POST['image_name'];
        $email=$_POST['mail'];
        $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
        }
                // our sql query
                $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
                            mysql_query($sql) or die("Error in Query insert: " . mysql_error());
} 
?>



<?php
//SEARCH.PHP PAGE
    //connect to database.db name = images
         mysql_connect("localhost", "root", "") OR DIE (mysql_error());
        mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database

        $msg="";
        $sql="select * from images";
        if(mysql_query($sql))
        {
            $res=mysql_query($sql);
            while($row=mysql_fetch_array($res))
            {
                    $id=$row['id'];
                    $name=$row['name'];
                    $image=$row['image'];

                  $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " />   </a>';

            }
        }
        else
            $msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

Read file As String

public static String readFileToString(String filePath) {
    InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
    try {
        return IOUtils.toString(in, StandardCharsets.UTF_8);
    } catch (IOException e) {
        logger.error("Failed to read the xml : ", e);
    }
    return null;
}

Python: Get HTTP headers from urllib2.urlopen call?

Use the response.info() method to get the headers.

From the urllib2 docs:

urllib2.urlopen(url[, data][, timeout])

...

This function returns a file-like object with two additional methods:

  • geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
  • info() — return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)

So, for your example, try stepping through the result of response.info().headers for what you're looking for.

Note the major caveat to using httplib.HTTPMessage is documented in python issue 4773.

ADB - Android - Getting the name of the current activity

If you want to filter out only your app's activities currently running/paused, you can use this command:

adb shell dumpsys activity activities | grep 'Hist #' | grep 'YOUR_PACKAGE_NAME'

For example:

adb shell dumpsys activity activities | grep 'Hist #' | grep 'com.supercell.clashroyale'

The output will be something like:

* Hist #2: ActivityRecord{26ba44b u10 com.supercell.clashroyale/StartActivity t27770}
* Hist #1: ActivityRecord{2f3a0236 u10 com.supercell.clashroyale/SomeActivity t27770}
* Hist #0: ActivityRecord{20bbb4ae u10 com.supercell.clashroyale/OtherActivity t27770}

Do notice that the output shows the actual stack of activities i.e. the topmost activity is the one that is currently being displayed.

Git - push current branch shortcut

The simplest way: run git push -u origin feature/123-sandbox-tests once. That pushes the branch the way you're used to doing it and also sets the upstream tracking info in your local config. After that, you can just git push to push tracked branches to their upstream remote(s).

You can also do this in the config yourself by setting branch.<branch name>.merge to the remote branch name (in your case the same as the local name) and optionally, branch.<branch name>.remote to the name of the remote you want to push to (defaults to origin). If you look in your config, there's most likely already one of these set for master, so you can follow that example.

Finally, make sure you consider the push.default setting. It defaults to "matching", which can have undesired and unexpected results. Most people I know find "upstream" more intuitive, which pushes only the current branch.

Details on each of these settings can be found in the git-config man page.

On second thought, on re-reading your question, I think you know all this. I think what you're actually looking for doesn't exist. How about a bash function something like (untested):

function pushCurrent {
  git config push.default upstream
  git push
  git config push.default matching
}

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.

$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);

EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)

<?php
if(!isset($_GET['json']))
    die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>

how to convert binary string to decimal?

parseInt() with radix is a best solution (as was told by many):

But if you want to implement it without parseInt, here is an implementation:

  function bin2dec(num){
    return num.split('').reverse().reduce(function(x, y, i){
      return (y === '1') ? x + Math.pow(2, i) : x;
    }, 0);
  }

How to set environment variable for everyone under my linux system?

As well as /etc/profile which others have mentioned, some Linux systems now use a directory /etc/profile.d/; any .sh files in there will be sourced by /etc/profile. It's slightly neater to keep your custom environment stuff in these files than to just edit /etc/profile.

Function to check if a string is a date

I use this function as a parameter to the PHP filter_var function.

  • It checks for dates in yyyy-mm-dd hh:mm:ss format
  • It rejects dates that match the pattern but still invalid (e.g. Apr 31)

function filter_mydate($s) {
    if (preg_match('@^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$@', $s, $m) == false) {
        return false;
    }
    if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
        return false;
    }
    return $s;
}

Multi-gradient shapes

Try this method then you can do every thing you want.
It is like a stack so be careful which item comes first or last.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:right="50dp" android:start="10dp" android:left="10dp">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <corners android:radius="3dp" />
        <solid android:color="#012d08"/>
    </shape>
</item>
<item android:top="50dp">
    <shape android:shape="rectangle">
        <solid android:color="#7c4b4b" />
    </shape>
</item>
<item android:top="90dp" android:end="60dp">
    <shape android:shape="rectangle">
        <solid android:color="#e2cc2626" />
    </shape>
</item>
<item android:start="50dp" android:bottom="20dp" android:top="120dp">
    <shape android:shape="rectangle">
        <solid android:color="#360e0e" />
    </shape>
</item>

Stopping fixed position scrolling at a certain point?

Here's a quick jQuery plugin I just wrote that can do what you require:

$.fn.followTo = function (pos) {
    var $this = this,
        $window = $(window);

    $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('#yourDiv').followTo(250);

See working example →

Finishing current activity from a fragment

Every time I use finish to close the fragment, the entire activity closes. According to the docs, fragments should remain as long as the parent activity remains.

Instead, I found that I can change views back the the parent activity by using this statement: setContentView(R.layout.activity_main);

This returns me back to the parent activity.

I hope that this helps someone else who may be looking for this.

Get key from a HashMap using the value

You mixed the keys and the values.

Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();

hashmap.put(100, "one");
hashmap.put(200, "two");

Afterwards a

hashmap.get(100);

will give you "one"

Python: SyntaxError: keyword can't be an expression

I guess many of us who came to this page have a problem with Scikit Learn, one way to solve it is to create a dictionary with parameters and pass it to the model:

params = {'C': 1e9, 'gamma': 1e-07}
cls = SVC(**params)    

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

Calling a JSON API with Node.js

Problems with other answers:

  • unsafe JSON.parse
  • no response code checking

All of the answers here use JSON.parse() in an unsafe way. You should always put all calls to JSON.parse() in a try/catch block especially when you parse JSON coming from an external source, like you do here.

You can use request to parse the JSON automatically which wasn't mentioned here in other answers. There is already an answer using request module but it uses JSON.parse() to manually parse JSON - which should always be run inside a try {} catch {} block to handle errors of incorrect JSON or otherwise the entire app will crash. And incorrect JSON happens, trust me.

Other answers that use http also use JSON.parse() without checking for exceptions that can happen and crash your application.

Below I'll show few ways to handle it safely.

All examples use a public GitHub API so everyone can try that code safely.

Example with request

Here's a working example with request that automatically parses JSON:

'use strict';
var request = require('request');

var url = 'https://api.github.com/users/rsp';

request.get({
    url: url,
    json: true,
    headers: {'User-Agent': 'request'}
  }, (err, res, data) => {
    if (err) {
      console.log('Error:', err);
    } else if (res.statusCode !== 200) {
      console.log('Status:', res.statusCode);
    } else {
      // data is already parsed as JSON:
      console.log(data.html_url);
    }
});

Example with http and try/catch

This uses https - just change https to http if you want HTTP connections:

'use strict';
var https = require('https');

var options = {
    host: 'api.github.com',
    path: '/users/rsp',
    headers: {'User-Agent': 'request'}
};

https.get(options, function (res) {
    var json = '';
    res.on('data', function (chunk) {
        json += chunk;
    });
    res.on('end', function () {
        if (res.statusCode === 200) {
            try {
                var data = JSON.parse(json);
                // data is available here:
                console.log(data.html_url);
            } catch (e) {
                console.log('Error parsing JSON!');
            }
        } else {
            console.log('Status:', res.statusCode);
        }
    });
}).on('error', function (err) {
      console.log('Error:', err);
});

Example with http and tryjson

This example is similar to the above but uses the tryjson module. (Disclaimer: I am the author of that module.)

'use strict';
var https = require('https');
var tryjson = require('tryjson');

var options = {
    host: 'api.github.com',
    path: '/users/rsp',
    headers: {'User-Agent': 'request'}
};

https.get(options, function (res) {
    var json = '';

    res.on('data', function (chunk) {
        json += chunk;
    });

    res.on('end', function () {
        if (res.statusCode === 200) {
            var data = tryjson.parse(json);
            console.log(data ? data.html_url : 'Error parsing JSON!');
        } else {
            console.log('Status:', res.statusCode);
        }
    });
}).on('error', function (err) {
      console.log('Error:', err);
});

Summary

The example that uses request is the simplest. But if for some reason you don't want to use it then remember to always check the response code and to parse JSON safely.

Format date and Subtract days using Moment.js

You have multiple oddities happening. The first has been edited in your post, but it had to do with the order that the methods were being called.

.format returns a string. String does not have a subtract method.

The second issue is that you are subtracting the day, but not actually saving that as a variable.

Your code, then, should look like:

var startdate = moment();
startdate = startdate.subtract(1, "days");
startdate = startdate.format("DD-MM-YYYY");

However, you can chain this together; this would look like:

var startdate = moment().subtract(1, "days").format("DD-MM-YYYY");

The difference is that we're setting startdate to the changes that you're doing on startdate, because moment is destructive.

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

Use this code (taken from css-tricks) that will work on all browser

overflow-wrap: break-word;
word-wrap: break-word;

-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;

/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;

How to draw circle by canvas in Android?

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity 
{

     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(new MyView(this));
     }

     public class MyView extends View
     {
         Paint paint = null;
         public MyView(Context context) 
         {
              super(context);
              paint = new Paint();
         }

         @Override
         protected void onDraw(Canvas canvas) 
         {
            super.onDraw(canvas);
            int x = getWidth();
            int y = getHeight();
            int radius;
            radius = 100;
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            canvas.drawPaint(paint);
            // Use Color.parseColor to define HTML colors
            paint.setColor(Color.parseColor("#CD5C5C"));
            canvas.drawCircle(x / 2, y / 2, radius, paint);
        }
     }
}

Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using

canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);

These two link also help

http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o

http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html

Regex to replace everything except numbers and a decimal point

Try this:

document.getElementById(target).value = newVal.replace(/^\d+(\.\d{0,2})?$/, "");

How to pad a string to a fixed length with spaces in Python?

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

After doing a lot of things, I upgraded pip, setuptools and virtualenv.

  1. python -m pip install -U pip
  2. pip install -U setuptools
  3. pip install -U virtualenv

I did steps 1, 2 in my virtual environment as well as globally. Next, I installed the package through pip and it worked.

Javascript : array.length returns undefined

try this

Object.keys(data).length

If IE < 9, you can loop through the object yourself with a for loop

var len = 0;
var i;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        len++;
    }
}

How to force a view refresh without having it trigger automatically from an observable?

In some circumstances it might be useful to simply remove the bindings and then re-apply:

ko.cleanNode(document.getElementById(element_id))
ko.applyBindings(viewModel, document.getElementById(element_id))

In Java, how do I call a base class's method from the overriding method in a derived class?

I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.

class A
{
    public void myMethod()
    { /* ... */ }
}

class B extends A
{
    public void myMethod()
    {
        super.myMethod(); // calling parent method
    }
}

Spring MVC + JSON = 406 Not Acceptable

With Spring 4 you only add @EnableWebMvc, for example:

@Controller
@EnableWebMvc
@RequestMapping(value = "/articles/action", headers="Accept=*/*",  produces="application/json")
public class ArticlesController {

}

HTTP authentication logout via PHP

Workaround

You can do this using Javascript:

<html><head>
<script type="text/javascript">
function logout() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
          xmlhttp = new XMLHttpRequest();
    }
    // code for IE
    else if (window.ActiveXObject) {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (window.ActiveXObject) {
      // IE clear HTTP Authentication
      document.execCommand("ClearAuthenticationCache");
      window.location.href='/where/to/redirect';
    } else {
        xmlhttp.open("GET", '/path/that/will/return/200/OK', true, "logout", "logout");
        xmlhttp.send("");
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {window.location.href='/where/to/redirect';}
        }


    }


    return false;
}
</script>
</head>
<body>
<a href="#" onclick="logout();">Log out</a>
</body>
</html>

What is done above is:

  • for IE - just clear auth cache and redirect somewhere

  • for other browsers - send an XMLHttpRequest behind the scenes with 'logout' login name and password. We need to send it to some path that will return 200 OK to that request (i.e. it shouldn't require HTTP authentication).

Replace '/where/to/redirect' with some path to redirect to after logging out and replace '/path/that/will/return/200/OK' with some path on your site that will return 200 OK.

adding multiple entries to a HashMap at once in one statement

You could add this utility function to a utility class:

public static <K, V> Map<K, V> mapOf(Object... keyValues) {
    Map<K, V> map = new HashMap<>();

    for (int index = 0; index < keyValues.length / 2; index++) {
        map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]);
    }

    return map;
}

Map<Integer, String> map1 = YourClass.mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = YourClass.mapOf("key1", "value1", "key2", "value2");

Note: in Java 9 you can use Map.of

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 

where

P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

How to remove html special chars?

A plain vanilla strings way to do it without engaging the preg regex engine:

function remEntities($str) {
  if(substr_count($str, '&') && substr_count($str, ';')) {
    // Find amper
    $amp_pos = strpos($str, '&');
    //Find the ;
    $semi_pos = strpos($str, ';');
    // Only if the ; is after the &
    if($semi_pos > $amp_pos) {
      //is a HTML entity, try to remove
      $tmp = substr($str, 0, $amp_pos);
      $tmp = $tmp. substr($str, $semi_pos + 1, strlen($str));
      $str = $tmp;
      //Has another entity in it?
      if(substr_count($str, '&') && substr_count($str, ';'))
        $str = remEntities($tmp);
    }
  }
  return $str;
}

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

How to change Java version used by TOMCAT?

test open the termenal or cmd. go to the [tomcat-home]\bin directory. ex: c:\tomcat8\bin write the following command: Tomcat8W //ES//Tomcat8 will open dialog, select the java tap(top tap). change the Java virtual Machine value.

find all the name using mysql query which start with the letter 'a'

I would go for substr() functionality in MySql.

Basically, this function takes account of three parameters i.e. substr(str,pos,len)

http://www.w3resource.com/mysql/string-functions/mysql-substr-function.php

SELECT * FROM artists 
WHERE lower(substr(name,1,1)) in ('a','b','c');

no debugging symbols found when using gdb

Hope the sytem you compiled on and the system you are debugging on have the same architecture. I ran into an issue where debugging symbols of 32 bit binary refused to load up on my 64 bit machine. Switching to a 32 bit system worked for me.

Resolve host name to an ip address

You could use a C function getaddrinfo() to get the numerical address - both ipv4 and ipv6. See the example code here

Best way to create unique token in Rails?

This may be helpful :

SecureRandom.base64(15).tr('+/=', '0aZ')

If you want to remove any special character than put in first argument '+/=' and any character put in second argument '0aZ' and 15 is the length here .

And if you want to remove the extra spaces and new line character than add the things like :

SecureRandom.base64(15).tr('+/=', '0aZ').strip.delete("\n")

Hope this will help to anybody.

How to force R to use a specified factor level as reference in a regression?

The relevel() command is a shorthand method to your question. What it does is reorder the factor so that whatever is the ref level is first. Therefore, reordering your factor levels will also have the same effect but gives you more control. Perhaps you wanted to have levels 3,4,0,1,2. In that case...

bFactor <- factor(b, levels = c(3,4,0,1,2))

I prefer this method because it's easier for me to see in my code not only what the reference was but the position of the other values as well (rather than having to look at the results for that).

NOTE: DO NOT make it an ordered factor. A factor with a specified order and an ordered factor are not the same thing. lm() may start to think you want polynomial contrasts if you do that.

How to increase Bootstrap Modal Width?

In Bootstrap 3 you need to change the modal-dialog. So, in this case, you can add the class modal-admin in the place where modal-dialog stands.

@media (min-width: 768px) {
  .modal-dialog {
    width: 600;
    margin: 30px auto;
  }
  .modal-content {
    -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
            box-shadow: 0 5px 15px rgba(0, 0, 0, .5);
  }
  .modal-sm {
    width: 300px;
  }
}

How to get jQuery to wait until an effect is finished?

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

How to enable LogCat/Console in Eclipse for Android?

In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.

Logcat is nothing but a console of your Emulator or Device.

System.out.println does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.

Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.

Making a Sass mixin with optional arguments

I am new to css compilers, hope this helps,

        @mixin positionStyle($params...){

            $temp:nth($params,1);
            @if $temp != null{
            position:$temp;
            }

             $temp:nth($params,2);
            @if $temp != null{
            top:$temp;
            }

             $temp:nth($params,3);
            @if $temp != null{
            right:$temp;
            }

             $temp:nth($params,4);
            @if $temp != null{
            bottom:$temp;
            }

            $temp:nth($params,5);
            @if $temp != null{
            left:$temp;
            }

    .someClass{
    @include positionStyle(absolute,30px,5px,null,null);
    }

//output

.someClass{
position:absolute;
 top: 30px;
 right: 5px;
}

Use CSS3 transitions with gradient backgrounds

::before, the CSS pseudo-element can easily do the trick!

All you have to do is use the ::before pseudo-element with zero opacity.

On :hover, switch opacity to 1 and if you follow a few simple steps, you should get your transition working.


.element {
  position: relative;
  width: 500px;
  height: 400px;
  background-image: linear-gradient(45deg, blue, aqua);
  z-index: 2;
}

.element::before {
  position: absolute;
  content: "";
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-image: linear-gradient(to bottom, red, orange);
  z-index: 1;
  opacity: 0;
  transition: opacity 0.4s linear;
}

.element:hover::before {
  opacity: 1;
}


  1. target the element and set it's default gradient using background-image
  2. targeting the same element, use ::before to set it's next gradient with background-image and it's opacity to zero
  3. use now :hover::before and set opacity to 1
  4. Back on the ::before block use:
    • position absolute
    • content: ""
    • a lower z-index than the default element
    • set top, bottom, right and left to zero
    • set transition attribute targeting the opacity property
  5. Now everything should be done and you can tweak your transition with whatever duration / delay / timing-function you like!

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Trying to run a servlet in Eclipse (right-click + "Run on Server") I encountered the very same problem: "HTTP Status: 404 / Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists." Adding an index.html did not help, neither changing various settings of the tomcat.

Finally, I found the problem in an unexpected place: In Eclipse, the Option "Build automatically" was not set. Thus the servlet was not compiled, and no File "myServlet.class" was deployed to the server (in my case in the path .wtpwebapps/projectXX/WEB-INF/classes/XXpackage/). Building the project manually and restarting the server solved the problem.

My environment: Eclipse Neon.3 Release 4.6.3, Tomcat-Version 8.5.14., OS Linux Mint 18.1.

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

Show row number in row header of a DataGridView

private void ShowRowNumber(DataGridView dataGridView)
{
   dataGridView.RowHeadersWidth = 50;
   for (int i = 0; i < dataGridView.Rows.Count; i++)
   {
        dataGridView.Rows[i].HeaderCell.Value = (i + 1).ToString();
   }
}

How does Java import work?

In dynamic languages, when the interpreter imports, it simply reads a file and evaluates it.

In C, external libraries are located by the linker at compile time to build the final object if the library is statically compiled, while for dynamic libraries a smaller version of the linker is called at runtime which remaps addresses and so makes code in the library available to the executable.

In Java, import is simply used by the compiler to let you name your classes by their unqualified name, let's say String instead of java.lang.String. You don't really need to import java.lang.* because the compiler does it by default. However this mechanism is just to save you some typing. Types in Java are fully qualified class names, so a String is really a java.lang.String object when the code is run. Packages are intended to prevent name clashes and allow two classes to have the same simple name, instead of relying on the old C convention of prefixing types like this. java_lang_String. This is called namespacing.

BTW, in Java there's the static import construct, which allows to further save typing if you use lots of constants from a certain class. In a compilation unit (a .java file) which declares

import static java.lang.Math.*;

you can use the constant PI in your code, instead of referencing it through Math.PI, and the method cos() instead of Math.cos(). So for example you can write

double r = cos(PI * theta);

Once you understand that classes are always referenced by their fully qualified name in the final bytecode, you must understand how the class code is actually loaded. This happens the first time an object of that class is created, or the first time a static member of the class is accessed. At this time, the ClassLoader tries to locate the class and instantiate it. If it can't find the class a NoClassDefFoundError is thrown (or a a ClassNotFoundException if the class is searched programmatically). To locate the class, the ClassLoader usually checks the paths listed in the $CLASSPATH environment variable.

To solve your problem, it seems you need an applet element like this

<applet
  codebase = "http://san.redenetimoveis.com"
  archive="test.jar, core.jar"
  code="com.colorfulwolf.webcamapplet.WebcamApplet"      
  width="550" height="550" >

BTW, you don't need to import the archives in the standard JRE.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)

Why would you use String.Equals over ==?

String.Equals does offer overloads to handle casing and culture-aware comparison. If your code doesn't make use of these, the devs may just be used to Java, where (as Matthew says), you must use the .Equals method to do content comparisons.

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

I actually used to check window.parent and it worked for me, but lately window is a cyclic object and always has a parent key, iframe or no iframe.

As the comments suggest hard comparing with window.parent works. Not sure if this will work if iframe is exactly the same webpage as parent.

window === window.parent;

How to track down access violation "at address 00000000"

I will second madExcept and similar tools, like Eurekalog, but I think you can come a good way with FastMM also. With full debugmode enabled, it should give you some clues of whats wrong.

Anyway, even though Delphi uses FastMM as default, it's worth getting the full FastMM for it's additional control over logging.

Invisible characters - ASCII

I just went through the character map to get these. They are all in Calibri.

Number    Name                   HTML Code    Appearance
------    --------------------   ---------    ----------
U+2000    En Quad                &#8192;      " "
U+2001    Em Quad                &#8193;      " "
U+2002    En Space               &#8194;      " "
U+2003    Em Space               &#8195;      " "
U+2004    Three-Per-Em Space     &#8196;      " "
U+2005    Four-Per-Em Space      &#8197;      " "
U+2006    Six-Per-Em Space       &#8198;      " "
U+2007    Figure Space           &#8199;      " "
U+2008    Punctuation Space      &#8200;      " "
U+2009    Thin Space             &#8201;      " "
U+200A    Hair Space             &#8202;      " "
U+200B    Zero-Width Space       &#8203;      "​"
U+200C    Zero Width Non-Joiner  &#8204;      "‌"
U+200D    Zero Width Joiner      &#8205;      "‍"
U+200E    Left-To-Right Mark     &#8206;      "‎"
U+200F    Right-To-Left Mark     &#8207;      "‏"
U+202F    Narrow No-Break Space  &#8239;      " "

What is the Gradle artifact dependency graph command?

For those looking to debug gradle dependencies in react-native projects, the command is (executed from projectname/android)

./gradlew app:dependencies --configuration compile

How do I check the difference, in seconds, between two dates?

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

would that work for you?

What is the maximum possible length of a .NET string?

For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…

The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.

The problem with s += "stuff" is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff" is extremely costly. If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:

StringBuilder sb = new StringBuilder(5000);
for (; ; )
    {
        sb.Append("stuff");
    }

StringBuilder will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.

How can I clear the NuGet package cache using the command line?

You can use PowerShell too (same as me).

For example:

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg

Or 'quiet' mode (without error messages):

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg 2> $null

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

Implementing a Custom Error page on an ASP.Net website

Is it a spelling error in your closing tag ie:

</CustomErrors> instead of </CustomError>?

What static analysis tools are available for C#?

  • Gendarme is an open source rules based static analyzer (similar to FXCop, but finds a lot of different problems).
  • Clone Detective is a nice plug-in for Visual Studio that finds duplicate code.
  • Also speaking of Mono, I find the act of compiling with the Mono compiler (if your code is platform independent enough to do that, a goal you might want to strive for anyway) finds tons of unreferenced variables and other Warnings that Visual Studio completely misses (even with the warning level set to 4).

Split Java String by New Line

The above code doesnt actually do anything visible - it just calcualtes then dumps the calculation. Is it the code you used, or just an example for this question?

try doing textAreaDoc.insertString(int, String, AttributeSet) at the end?

How to format dateTime in django template?

You can use this:

addedDate = datetime.now().replace(microsecond=0)

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

How do you append rows to a table using jQuery?

Maybe this is the answer you are looking for. It finds the last instance of <tr /> and appends the new row after it:

<script type="text/javascript">
    $('a').click(function() {
        $('#myTable tr:last').after('<tr class="child"><td>blahblah<\/td></tr>');
    });
</script>

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

UITextField border color

Try this:

UITextField *theTextFiels=[[UITextField alloc]initWithFrame:CGRectMake(40, 40, 150, 30)];
    theTextFiels.borderStyle=UITextBorderStyleNone;
    theTextFiels.layer.cornerRadius=8.0f;
    theTextFiels.layer.masksToBounds=YES;
        theTextFiels.backgroundColor=[UIColor redColor];
    theTextFiels.layer.borderColor=[[UIColor blackColor]CGColor];
    theTextFiels.layer.borderWidth= 1.0f;

    [self.view addSubview:theTextFiels];
    [theTextFiels release];

and import QuartzCore:

#import <QuartzCore/QuartzCore.h>