Programs & Examples On #Domparser

querySelector, wildcard element match?

[id^='someId'] will match all ids starting with someId.

[id$='someId'] will match all ids ending with someId.

[id*='someId'] will match all ids containing someId.

If you're looking for the name attribute just substitute id with name.

If you're talking about the tag name of the element I don't believe there is a way using querySelector

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

What is the difference between SAX and DOM?

Well, you are close.

In SAX, events are triggered when the XML is being parsed. When the parser is parsing the XML, and encounters a tag starting (e.g. <something>), then it triggers the tagStarted event (actual name of event might differ). Similarly when the end of the tag is met while parsing (</something>), it triggers tagEnded. Using a SAX parser implies you need to handle these events and make sense of the data returned with each event.

In DOM, there are no events triggered while parsing. The entire XML is parsed and a DOM tree (of the nodes in the XML) is generated and returned. Once parsed, the user can navigate the tree to access the various data previously embedded in the various nodes in the XML.

In general, DOM is easier to use but has an overhead of parsing the entire XML before you can start using it.

How to save RecyclerView's scroll position using RecyclerView.State?

You don't have to save and restore the state by yourself anymore. If you set unique ID in xml and recyclerView.setSaveEnabled(true) (true by default) system will automatically do it. Here is more about this: http://trickyandroid.com/saving-android-view-state-correctly/

Responsive Google Map?

It's better to use Google Map API. I've created an example here: http://jsfiddle.net/eugenebolotin/8m1s69e5/1/

Key features are using of functions:

//Full example is here: http://jsfiddle.net/eugenebolotin/8m1s69e5/1/

map.setCenter(map_center);
// Scale map to fit specified points
map.fitBounds(path_bounds);

It handles resize event and automaticaly adjusts size.

Using SSIS BIDS with Visual Studio 2012 / 2013

Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.

There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.

There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are

None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals

enter image description here

Configure hibernate to connect to database via JNDI Datasource

Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">



  <jee:jndi-lookup id="dataSource"
                 jndi-name="Give_DataSource_Path_From_Your_Server"
                 expected-type="javax.sql.DataSource" />


Hope It will help someone.Thanks!

How to read input with multiple lines in Java

Use BufferedReader, you can make it read from standard input like this:

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;

while ((line = stdin.readLine()) != null && line.length()!= 0) {
    String[] input = line.split(" ");
    if (input.length == 2) {
        System.out.println(calculateAnswer(input[0], input[1]));
    }
}

Reordering Chart Data Series

These are the buttons UP/DOWN

enter image description here

How to split a file into equal parts, without breaking individual lines?

A simple solution for a simple question:

split -n l/5 your_file.txt

no need for scripting here.

From the man file, CHUNKS may be:

l/N     split into N files without splitting lines

Update

Not all unix dist include this flag. For example, it will not work in OSX. To use it, you can consider replacing the Mac OS X utilities with GNU core utilities.

Can I scroll a ScrollView programmatically in Android?

ScrollView sv = (ScrollView)findViewById(R.id.scrl);
sv.scrollTo(0, sv.getBottom());

or

sv.scrollTo(5, 10);

How do you count the elements of an array in java

You can declare an array of booleans with the same length of your array:

true: is used
false: is not used

and change the value of the same cell number to true. Then you can count how many cells are used by using a for loop.

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

How to stop line breaking in vim

:set tw=0

VIM won't auto-insert line breaks, but will keep line wrapping.

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

It could also be as simple as the fact that your database is not actually MS SQL Server. If your database is actually MySql, for instance, and you try to connect to it with System.Data.SqlClient you will get this error.

By far most examples of ADO.Net will be for MSSQL and the inexperienced user may not know that you can't use SqlConnection, SqlCommand, etc., with MySql.

While all ADO.Net data providers conform to the same interface, you have to use the provider made for your database.

How to compare data between two table in different databases using Sql Server 2008?

In order to compare two databases, I've written the procedures bellow. If you want to compare two tables you can use procedure 'CompareTables'. Example :

EXEC master.dbo.CompareTables 'DB1', 'dbo', 'table1', 'DB2', 'dbo', 'table2'

If you want to compare two databases, use the procedure 'CompareDatabases'. Example :

EXEC master.dbo.CompareDatabases 'DB1', 'DB2'

Note : - I tried to make the procedures secure, but anyway, those procedures are only for testing and debugging. - If you want a complete solution for comparison use third party like (Visual Studio, ...)

USE [master]
GO

create proc [dbo].[CompareDatabases]
    @FirstDatabaseName nvarchar(50),
    @SecondDatabaseName nvarchar(50)
    as
begin
    -- Check that databases exist
    if not exists(SELECT name FROM sys.databases WHERE name=@FirstDatabaseName)
        return 0
    if not exists(SELECT name FROM sys.databases WHERE name=@SecondDatabaseName)
        return 0

    declare @result table (TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('(Select distinct TABLE_NAME from ' + @FirstDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')'
                            + 'intersect'
                            + '(Select distinct TABLE_NAME from ' + @SecondDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')')

    DECLARE @TABLE_NAME nvarchar(256)
    DECLARE curseur CURSOR FOR
        SELECT TABLE_NAME FROM @result
    OPEN curseur
    FETCH curseur INTO @TABLE_NAME
        WHILE @@FETCH_STATUS = 0
            BEGIN
                print 'TABLE : ' + @TABLE_NAME
                EXEC master.dbo.CompareTables @FirstDatabaseName, 'dbo', @TABLE_NAME, @SecondDatabaseName, 'dbo', @TABLE_NAME
                FETCH curseur INTO @TABLE_NAME
            END
        CLOSE curseur
    DEALLOCATE curseur
    SET NOCOUNT OFF
end
GO

.

USE [master]
GO

CREATE PROC [dbo].[CompareTables]
    @FirstTABLE_CATALOG nvarchar(256),
    @FirstTABLE_SCHEMA nvarchar(256),
    @FirstTABLE_NAME nvarchar(256),
    @SecondTABLE_CATALOG nvarchar(256),
    @SecondTABLE_SCHEMA nvarchar(256),
    @SecondTABLE_NAME nvarchar(256)
    AS
BEGIN
    -- Verify if first table exist
    DECLARE @table1 nvarchar(256) = @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME
    DECLARE @return_status int
    EXEC @return_status = master.dbo.TableExist @FirstTABLE_CATALOG, @FirstTABLE_SCHEMA, @FirstTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table1 + ' : Table Not FOUND'
            RETURN 0
        END



    -- Verify if second table exist
    DECLARE @table2 nvarchar(256) = @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME
    EXEC @return_status = master.dbo.TableExist @SecondTABLE_CATALOG, @SecondTABLE_SCHEMA, @SecondTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table2 + ' : Table Not FOUND'
            RETURN 0
        END

    -- Compare the two tables
    DECLARE @sql AS NVARCHAR(MAX)
    SELECT @sql = '('
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + ')'
                + 'UNION'
                + '('
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + ')'
    DECLARE @wrapper AS NVARCHAR(MAX) = 'if exists (' + @sql + ')' + char(10) + '    (' + @sql + ')ORDER BY 2'
    Exec(@wrapper)
END
GO

.

USE [master]
GO

CREATE PROC [dbo].[TableExist]
    @TABLE_CATALOG nvarchar(256),
    @TABLE_SCHEMA nvarchar(256),
    @TABLE_NAME nvarchar(256)
    AS
BEGIN
    IF NOT EXISTS(SELECT name FROM sys.databases WHERE name=@TABLE_CATALOG)
        RETURN 0

    declare @result table (TABLE_SCHEMA nvarchar(256), TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('Select TABLE_SCHEMA, TABLE_NAME from ' + @TABLE_CATALOG  + '.INFORMATION_SCHEMA.COLUMNS')
    SET NOCOUNT OFF

    IF EXISTS(SELECT TABLE_SCHEMA, TABLE_NAME FROM @result
                WHERE TABLE_SCHEMA=@TABLE_SCHEMA AND TABLE_NAME=@TABLE_NAME)
        RETURN 1

    RETURN 0
END

GO

Is it possible to create a temporary table in a View and drop it after select?

You can achieve what you are trying to do, using a Stored Procedure which returns a query result. Views are not suitable / developed for operations like this one.

Java - sending HTTP parameters via POST method easily

I higly recomend http-request built on apache http api.

For your case you can see example:

private static final HttpRequest<String.class> HTTP_REQUEST = 
      HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
           .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
           .build();

public void sendRequest(String request){
     String parameters = request.split("\\?")[1];
     ResponseHandler<String> responseHandler = 
            HTTP_REQUEST.executeWithQuery(parameters);

   System.out.println(responseHandler.getStatusCode());
   System.out.println(responseHandler.get()); //prints response body
}

If you are not interested in the response body

private static final HttpRequest<?> HTTP_REQUEST = 
     HttpRequestBuilder.createPost("http://example.com/index.php").build();

public void sendRequest(String request){
     ResponseHandler<String> responseHandler = 
           HTTP_REQUEST.executeWithQuery(parameters);
}

For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java

How to use RecyclerView inside NestedScrollView?

UPDATE 1

Since Android Support Library 23.2.0 there were added method setAutoMeasureEnabled(true) for LayoutManagers. It makes RecyclerView to wrap it's content and works like a charm.
http://android-developers.blogspot.ru/2016/02/android-support-library-232.html

So just add something like this:

    LayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setAutoMeasureEnabled(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setNestedScrollingEnabled(false);


UPDATE 2

Since 27.1.0 setAutoMeasureEnabled is deprecated, so you should provide custom implementation of LayoutManager with overridden method isAutoMeasureEnabled()

But after many cases of usage RecyclerView I strongly recommend not to use it in wrapping mode, cause this is not what it is intended for. Try to refactor whole your layout using normal single RecyclerView with several items' types. Or use approach with LinearLayout that I described below as last resort


Old answer (not recommended)

You can use RecyclerView inside NestedScrollView. First of all you should implement your own custom LinearLayoutManager, it makes your RecyclerView to wrap its content. For example:

public class WrappingLinearLayoutManager extends LinearLayoutManager
{

    public WrappingLinearLayoutManager(Context context) {
        super(context);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public boolean canScrollVertically() {
        return false;
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
            int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);

        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            if (getOrientation() == HORIZONTAL) {
                measureScrapChild(recycler, i,
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        heightSpec,
                        mMeasuredDimension);

                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                measureScrapChild(recycler, i,
                        widthSpec,
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        mMeasuredDimension);

                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
            int heightSpec, int[] measuredDimension) {

        View view = recycler.getViewForPosition(position);
        if (view.getVisibility() == View.GONE) {
            measuredDimension[0] = 0;
            measuredDimension[1] = 0;
            return;
        }
        // For adding Item Decor Insets to view
        super.measureChildWithMargins(view, 0, 0);
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(
                widthSpec,
                getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view),
                p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(
                heightSpec,
                getPaddingTop() + getPaddingBottom() + getDecoratedTop(view) + getDecoratedBottom(view),
                p.height);
        view.measure(childWidthSpec, childHeightSpec);

        // Get decorated measurements
        measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
        measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
        recycler.recycleView(view);
    }
}

After that use this LayoutManager for your RecyclerView

recyclerView.setLayoutManager(new WrappingLinearLayoutManager(getContext()));

But you also should call those two methods:

recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(false);

Here setNestedScrollingEnabled(false) disable scrolling for RecyclerView, so it doesn't intercept scrolling event from NestedScrollView. And setHasFixedSize(false) determine that changes in adapter content can change the size of the RecyclerView

Important note: This solution is little buggy in some cases and has problems with perfomance, so if you have a lot of items in your RecyclerView I'd recommend to use custom LinearLayout-based implementation of list view, create analogue of Adapter for it and make it behave like ListView or RecyclerView

What's a clean way to stop mongod on Mac OS X?

Simple way is to get the process id of mongodb and kill it. Please note DO NOT USE kill -9 pid for this as it may cause damage to the database.

so, 1. get the pid of mongodb

$ pgrep mongo

you will get pid of mongo, Now

$ kill

You may use kill -15 as well

Violation Long running JavaScript task took xx ms

This is violation error from Google Chrome that shows when the Verbose logging level is enabled.

Example of error message:

screenshot of the warning

Explanation:

Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Because reflow is a user-blocking operation in the browser, it is useful for developers to understand how to improve reflow time and also to understand the effects of various document properties (DOM depth, CSS rule efficiency, different types of style changes) on reflow time. Sometimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.

Original article: Minimizing browser reflow by Lindsey Simon, UX Developer, posted on developers.google.com.

And this is the link Google Chrome gives you in the Performance profiler, on the layout profiles (the mauve regions), for more info on the warning.

Evaluate empty or null JSTL c tags

if you check only null or empty then you can use the with default option for this: <c:out default="var1 is empty or null." value="${var1}"/>

How to mark a build unstable in Jenkins when running shell scripts

Duplicating my answer from here because I spent some time looking for this:

This is now possible in newer versions of Jenkins, you can do something like this:

#!/usr/bin/env groovy

properties([
  parameters([string(name: 'foo', defaultValue: 'bar', description: 'Fails job if not bar (unstable if bar)')]),
])


stage('Stage 1') {
  node('parent'){
    def ret = sh(
      returnStatus: true, // This is the key bit!
      script: '''if [ "$foo" = bar ]; then exit 2; else exit 1; fi'''
    )
    // ret can be any number/range, does not have to be 2.
    if (ret == 2) {
      currentBuild.result = 'UNSTABLE'
    } else if (ret != 0) {
      currentBuild.result = 'FAILURE'
      // If you do not manually error the status will be set to "failed", but the
      // pipeline will still run the next stage.
      error("Stage 1 failed with exit code ${ret}")
    }
  }
}

The Pipeline Syntax generator shows you this in the advanced tab:

Pipeline Syntax Example

Possible heap pollution via varargs parameter

Heap pollution is a technical term. It refers to references which have a type that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();
List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can lead to "unexplainable" ClassCastExceptions.

// if the heap never gets polluted, this should never throw a CCE
B b = listOfBs.get(0); 

@SafeVarargs does not prevent this at all. However, there are methods which provably will not pollute the heap, the compiler just can't prove it. Previously, callers of such APIs would get annoying warnings that were completely pointless but had to be suppressed at every call site. Now the API author can suppress it once at the declaration site.

However, if the method actually is not safe, users will no longer be warned.

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

Please check the following file

%SystemRoot%\system32\drivers\etc\host

The line which bind the host name with ip is probably missing a line which bind them togather

127.0.0.1  localhost

If the given line is missing. Add the line in the file


Could you also check your MySQL database's user table and tell us the host column value for the user which you are using. You should have user privilege for both the host "127.0.0.1" and "localhost" and use % as it is a wild char for generic host name.

How do I create a SQL table under a different schema?

When I create a table using SSMS 2008, I see 3 panes:

  • The column designer
  • Column properties
  • The table properties

In the table properties pane, there is a field: Schema which allows you to select the schema.

Authentication plugin 'caching_sha2_password' cannot be loaded

Here is the solution which worked for me after MySQL 8.0 Installation on Windows 10.

Suppose MySQL username is root and password is admin

Open command prompt and enter the following commands:

cd C:\Program Files\MySQL\MySQL Server 8.0\bin

mysql_upgrade -uroot -padmin

mysql -uroot -padmin

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'admin'

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

How do I connect to a specific Wi-Fi network in Android programmatically?

I also tried to connect to the network. None of the solutions proposed above works for hugerock t70. Function wifiManager.disconnect(); doesn't disconnect from current network. ?nd therefore cannot reconnect to the specified network. I have modified the above code. For me the code bolow works perfectly:

String networkSSID = "test";
String networkPass = "pass";

WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";   
conf.wepKeys[0] = "\"" + networkPass + "\""; 
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 
conf.preSharedKey = "\""+ networkPass +"\"";

WifiManager wifiManager =         
(WifiManager)context.getSystemService(Context.WIFI_SERVICE);    

int networkId = wifiManager.addNetwork(conf);
wifi_inf = wifiManager.getConnectionInfo();

/////important!!!
wifiManager.disableNetwork(wifi_inf.getNetworkId());
/////////////////

wifiManager.enableNetwork(networkId, true);

How do servlets work? Instantiation, sessions, shared variables and multithreading

No. Servlets are not Thread safe

This is allows accessing more than one threads at a time

if u want to make it Servlet as Thread safe ., U can go for

Implement SingleThreadInterface(i) which is a blank Interface there is no

methods

or we can go for synchronize methods

we can make whole service method as synchronized by using synchronized

keyword in front of method

Example::

public Synchronized class service(ServletRequest request,ServletResponse response)throws ServletException,IOException

or we can the put block of the code in the Synchronized block

Example::

Synchronized(Object)

{

----Instructions-----

}

I feel that Synchronized block is better than making the whole method

Synchronized

Jenkins Pipeline Wipe Out Workspace

You can use deleteDir() as the last step of the pipeline Jenkinsfile (assuming you didn't change the working directory).

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

How to get image height and width using java?

So unfortunately, after trying all the answers from above, I did not get them to work after tireless times of trying. So I decided to do the real hack myself and I go this to work for me. I trust it would work perfectly for you too.

I am using this simple method to get the width of an image generated by the app and yet to be upload later for verification :

Pls. take note : you would have to enable permissions in manifest for access storage.

/I made it static and put in my Global class so I can reference or access it from just one source and if there is any modification, it would all have to be done at just one place. Just maintaining a DRY concept in java. (anyway) :)/

public static int getImageWidthOrHeight(String imgFilePath) {

            Log.d("img path : "+imgFilePath);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgFilePath, o);

            int width_tmp = o.outWidth, height_tmp = o.outHeight;

            Log.d("Image width : ", Integer.toString(width_tmp) );

            //you can decide to rather return height_tmp to get the height.

            return width_tmp;

}

What is the iOS 5.0 user agent string?

I use the following to detect different mobile devices, viewport and screen. Works quite well for me, might be helpful to others:

var pixelRatio = window.devicePixelRatio || 1;

var viewport = {
    width: window.innerWidth,
    height: window.innerHeight
};

var screen = {
    width: window.screen.availWidth * pixelRatio,
    height: window.screen.availHeight * pixelRatio
};

var iPhone = /iPhone/i.test(navigator.userAgent);
var iPhone4 = (iPhone && pixelRatio == 2);
var iPhone5 = /iPhone OS 5_0/i.test(navigator.userAgent);
var iPad = /iPad/i.test(navigator.userAgent);
var android = /android/i.test(navigator.userAgent);
var webos = /hpwos/i.test(navigator.userAgent);
var iOS = iPhone || iPad;
var mobile = iOS || android || webos;

window.devicePixelRatio is the ratio between physical pixels and device-independent pixels (dips) on the device. window.devicePixelRatio = physical pixels / dips.

More info here.

ValueError: unconverted data remains: 02:05

Best answer is to use the from dateutil import parser.

usage:

from dateutil import parser
datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
# output: datetime.datetime(2018, 2, 6, 13, 12, 18, 127801, tzinfo=tzutc())

Handling the TAB character in Java

Yes the tab character is one character. You can match it in java with "\t".

React Native Error: ENOSPC: System limit for number of file watchers reached

Please refer this link[1]. Visual Studio code has mentioned a brief explanation for this error message. I also encountered the same error. Adding the below parameter in the relavant file will fix this issue.

 fs.inotify.max_user_watches=524288

[1] https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-changes-in-this-large-workspace-error-enospc

A regex for version number parsing

I'd express the format as:

"1-3 dot-separated components, each numeric except that the last one may be *"

As a regexp, that's:

^(\d+\.)?(\d+\.)?(\*|\d+)$

[Edit to add: this solution is a concise way to validate, but it has been pointed out that extracting the values requires extra work. It's a matter of taste whether to deal with this by complicating the regexp, or by processing the matched groups.

In my solution, the groups capture the "." characters. This can be dealt with using non-capturing groups as in ajborley's answer.

Also, the rightmost group will capture the last component, even if there are fewer than three components, and so for example a two-component input results in the first and last groups capturing and the middle one undefined. I think this can be dealt with by non-greedy groups where supported.

Perl code to deal with both issues after the regexp could be something like this:

@version = ();
@groups = ($1, $2, $3);
foreach (@groups) {
    next if !defined;
    s/\.//;
    push @version, $_;
}
($major, $minor, $mod) = (@version, "*", "*");

Which isn't really any shorter than splitting on "." ]

What does `ValueError: cannot reindex from a duplicate axis` mean?

Indices with duplicate values often arise if you create a DataFrame by concatenating other DataFrames. IF you don't care about preserving the values of your index, and you want them to be unique values, when you concatenate the the data, set ignore_index=True.

Alternatively, to overwrite your current index with a new one, instead of using df.reindex(), set:

df.index = new_index

compare differences between two tables in mysql

I found another solution in this link

SELECT MIN (tbl_name) AS tbl_name, PK, column_list
FROM
 (
  SELECT ' source_table ' as tbl_name, S.PK, S.column_list
  FROM source_table AS S
  UNION ALL
  SELECT 'destination_table' as tbl_name, D.PK, D.column_list
  FROM destination_table AS D 
)  AS alias_table
GROUP BY PK, column_list
HAVING COUNT(*) = 1
ORDER BY PK

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the earliest release of the Android SDK that your application can run on. Usually this is because of a problem with the earlier APIs, lacking functionality, or some other behavioural issue.

The target sdk version is the version your application was targeted to run on. Ideally, this is because of some sort of optimal run conditions. If you were to "make your app for version 19", this is where that would be specified. It may run on earlier or later releases, but this is what you were aiming for. This is mostly to indicate how current your application is for use in the marketplace, etc.

The compile sdk version is the version of android your IDE (or other means of compiling I suppose) uses to make your app when you publish a .apk file. This is useful for testing your application as it is a common need to compile your app as you develop it. As this will be the version to compile to an APK, it will naturally be the version of your release. Likewise, it is advisable to have this match your target sdk version.

Calculating Page Table Size

Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***

How to convert jsonString to JSONObject in Java

If you are using http://json-lib.sourceforge.net (net.sf.json.JSONObject)

it is pretty easy:

String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);

or

JSONObject json = JSONSerializer.toJSON(myJsonString);

get the values then with json.getString(param), json.getInt(param) and so on.

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.

Model:

public class MyViewModel
{
    [PlaceHolder("Enter title here")]
    public string Title { get; set; }
}

Html helper extension:

   public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
    var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var metadata = modelMetadata;

    var viewData = new
    {
        HtmlAttributes = new
            {
                @class = htmlClass,
                placeholder = metadata.Watermark,
            }
    };
    return htmlHelper.EditorFor(expression, viewData);

}

A corresponding view:

@Html.BsEditorFor(x => x.Title)

Printing string variable in Java

If you have tried all the other answers, and it still hasn't work, you can try skipping a line:

Scanner scan = new Scanner(System.in);
scan.nextLine();
String s = scan.nextLine();
System.out.println("String is " + s);

What is the best (idiomatic) way to check the type of a Python variable?

I think I will go for the duck typing approach - "if it walks like a duck, it quacks like a duck, its a duck". This way you will need not worry about if the string is a unicode or ascii.

Here is what I will do:

In [53]: s='somestring'

In [54]: u=u'someunicodestring'

In [55]: d={}

In [56]: for each in s,u,d:
    if hasattr(each, 'keys'):
        print list(set(each.values()))
    elif hasattr(each, 'lower'):
        print [each]
    else:
        print "error"
   ....:         
   ....:         
['somestring']
[u'someunicodestring']
[]

The experts here are welcome to comment on this type of usage of ducktyping, I have been using it but got introduced to the exact concept behind it lately and am very excited about it. So I would like to know if thats an overkill to do.

get enum name from enum value

Say we have:

public enum MyEnum {
  Test1, Test2, Test3
}

To get the name of a enum variable use name():

MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"

To get the enum from a (string) name, use valueOf():

String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);

If you require integer values to match enum fields, extend the enum class:

public enum MyEnum {
  Test1(1), Test2(2), Test3(3);

  public final int value;

  MyEnum(final int value) {
     this.value = value;
  }
}

Now you can use:

MyEnum e = MyEnum.Test1;
int value = e.value; // = 1

And lookup the enum using the integer value:

MyEnum getValue(int value) {
  for(MyEnum e: MyEunm.values()) {
    if(e.value == value) {
      return e;
    }
  }
  return null;// not found
}

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):

var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false

and changing the console.log to alert, I still get the desired output in IE6.

Execute Python script via crontab

Put your script in a file foo.py starting with

#!/usr/bin/python

Then give execute permission to that script using

chmod a+x foo.py

and use the full path of your foo.py file in your crontab.

See documentation of execve(2) which is handling the shebang.

Recommended add-ons/plugins for Microsoft Visual Studio

It's not a Visual Studio add in, but it is a tool that I couldn't use Visual Studio without it...

ClipX - it's works with the normal clipboard, but saves the entries to a searchable list, you can use copy and paste as ususal, but you can hit CTRL+SHIFT+V and the list pops up. It works with images, text, etc. It even persists after you reboot your computer.

How to print an exception in Python?

(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)

I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:

except Exception as e:
    print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
    print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.

I haven't used the traceback module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.

Add attribute 'checked' on click jquery

If .attr() isn't working for you (especially when checking and unchecking boxes in succession), use .prop() instead of .attr().

html script src="" triggering redirection with button

First you are linking the file that is here:

<script src="../Script/login.js"> 

Which would lead the website to a file in the Folder Script, but then in the second paragraph you are saying that the folder name is

and also i have onother folder named scripts that contains the the following login.js file

So, this won't work! Because you are not accessing the correct file. To do that please write the code as

<script src="/script/login.js"></script>

Try removing the .. from the beginning of the code too.

This way, you'll reach the js file where the function would run!

Just to make sure:

Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!

Good luck.

android set button background programmatically

Further from @finnmglas, the Java answer as of 2021 is:

    if (Build.VERSION.SDK_INT >= 29)
        btn.getBackground().setColorFilter(new BlendModeColorFilter(color, BlendMode.MULTIPLY));
    else
        btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

Octave/Matlab: Adding new elements to a vector

Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:

big = 1e5;
tic;
x = rand(big,1);
toc

x = zeros(big,1);
tic;
for ii = 1:big
    x(ii) = rand;
end
toc

x = []; 
tic; 
for ii = 1:big
    x(end+1) = rand; 
end; 
toc 

x = []; 
tic; 
for ii = 1:big
    x = [x rand]; 
end; 
toc

   Elapsed time is 0.004611 seconds.
   Elapsed time is 0.016448 seconds.
   Elapsed time is 0.034107 seconds.
   Elapsed time is 12.341434 seconds.

I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get

Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.

So I guess the speed advantage only applies to more recent versions of Matlab

Get list of all input objects using JavaScript, without accessing a form object

(See update at end of answer.)

You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it:

var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

There I've used it on the document, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:

var container, inputs, index;

// Get the container element
container = document.getElementById('container');

// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

...but you've said you don't want to use the parent form, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).


Update: getElementsByTagName is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input elements?

That's where the useful querySelectorAll comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:

var checkboxes = document.querySelectorAll("input[type=checkbox]");

You can also use it at the element level. For instance, if we have a div element in our element variable, we can find all of the spans with the class foo that are inside that div like this:

var fooSpans = element.querySelectorAll("span.foo");

querySelectorAll and its cousin querySelector (which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

Make the class serializable by implementing the interface java.io.Serializable.

  • java.io.Serializable - Marker Interface which does not have any methods in it.
  • Purpose of Marker Interface - to tell the ObjectOutputStream that this object is a serializable object.

String delimiter in string.split method

String[] splitArray = subjectString.split("\\|\\|");

You use a function:

public String[] stringSplit(String string){

    String[] splitArray = string.split("\\|\\|");
    return splitArray;
}

Android: Difference between Parcelable and Serializable?

In Parcelable, developers write custom code for marshalling and unmarshalling so it creates fewer garbage objects in comparison to Serialization. The performance of Parcelable over Serialization dramatically improves (around two times faster), because of this custom implementation.

Serializable is a marker interface, which implies that user cannot marshal the data according to their requirements. In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API. This helps identify the Java object's member and behavior, but also ends up creating a lot of garbage objects. Due to this, the Serialization process is slow in comparison to Parcelable.

Edit: What is the meaning of marshalling and unmarshalling?

In few words, "marshalling" refers to the process of converting the data or the objects into a byte-stream, and "unmarshalling" is the reverse process of converting the byte-stream back to their original data or object. The conversion is achieved through "serialization".

http://www.jguru.com/faq/view.jsp?EID=560072

How can I inject a property value into a Spring Bean which was configured using annotations?

You also can annotate you class:

@PropertySource("classpath:/com/myProject/config/properties/database.properties")

And have a variable like this:

@Autowired
private Environment env;

Now you can access to all your properties in this way:

env.getProperty("database.connection.driver")

Java Returning method which returns arraylist?

MyClass obj = new MyClass();
ArrayList<Integer> numbers = obj.myNumbers();

Shorthand for if-else statement

Using the ternary :? operator [spec].

var hasName = (name === 'true') ? 'Y' :'N';

The ternary operator lets us write shorthand if..else statements exactly like you want.

It looks like:

(name === 'true') - our condition

? - the ternary operator itself

'Y' - the result if the condition evaluates to true

'N' - the result if the condition evaluates to false

So in short (question)?(result if true):(result is false) , as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I had a similar issue with PNG files. and I tried the solutions above without success. this one worked for me in python 3.8

with open(path, "rb") as f:

Uncaught ReferenceError: function is not defined with onclick

I was receiving the error (I'm using Vue) and I switched my onclick="someFunction()" to @click="someFunction" and now they are working.

JBoss AS 7: How to clean up tmp?

I do not have experience with version 7 of JBoss but with 5 I often had issues when redeploying apps which went away when I cleaned the work and tmp folder. I wrote a script for that which was executed everytime the server shut down. Maybe executing it before startup is better considering abnormal shutdowns (which weren't uncommon with Jboss 5 :))

How to programmatically send a 404 response with Express/Node?

Updated Answer for Express 4.x

Rather than using res.send(404) as in old versions of Express, the new method is:

res.sendStatus(404);

Express will send a very basic 404 response with "Not Found" text:

HTTP/1.1 404 Not Found
X-Powered-By: Express
Vary: Origin
Content-Type: text/plain; charset=utf-8
Content-Length: 9
ETag: W/"9-nR6tc+Z4+i9RpwqTOwvwFw"
Date: Fri, 23 Oct 2015 20:08:19 GMT
Connection: keep-alive

Not Found

add new element in laravel collection object

As mentioned above if you wish to as a new element your queried collection you can use:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
        $product = DB::select(DB::raw(' select * from product
               where product_id = '. $id.';' ));

        $items->push($product);
        // or 
        // $items->put('products', $product);
    }

but if you wish to add new element to each queried element you need to do like:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
           $product = DB::select(DB::raw(' select * from product
                 where product_id = '. $id.';' ));

          $item->add_whatever_element_you_want = $product;
    }

add_whatever_element_you_want can be whatever you wish that your element is named (like product for example).

Error ITMS-90717: "Invalid App Store Icon"

Dumb mistake from my part, didn't archive the app after removing alpha. Just kept submitting my old archived app and finding same alpha/transparency error. Hope it helps someone.

How can I make a program wait for a variable change in javascript?

JavaScript interpreters are single threaded, so a variable can never change, when the code is waiting in some other code that does not change the variable.

In my opinion it would be the best solution to wrap the variable in some kind of object that has a getter and setter function. You can then register a callback function in the object that is called when the setter function of the object is called. You can then use the getter function in the callback to retrieve the current value:

function Wrapper(callback) {
    var value;
    this.set = function(v) {
        value = v;
        callback(this);
    }
    this.get = function() {
        return value;
    }  
}

This could be easily used like this:

<html>
<head>
<script type="text/javascript" src="wrapper.js"></script>
<script type="text/javascript">
function callback(wrapper) {
    alert("Value is now: " + wrapper.get());
}

wrapper = new Wrapper(callback);
</script>
</head>
<body>
    <input type="text" onchange="wrapper.set(this.value)"/>
</body>
</html>

How can I make an image transparent on Android?

android:alpha does this in XML:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/blah"
    android:alpha=".75"/>

Efficient way to insert a number into a sorted array of numbers?

Very good and remarkable question with a very interesting discussion! I also was using the Array.sort() function after pushing a single element in an array with some thousands of objects.

I had to extend your locationOf function for my purpose because of having complex objects and therefore the need for a compare function like in Array.sort():

function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return -1;

    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // should be faster than dividing by 2

    var c = comparer(element, array[pivot]);
    if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

// sample for objects like {lastName: 'Miller', ...}
var patientCompare = function (a, b) {
    if (a.lastName < b.lastName) return -1;
    if (a.lastName > b.lastName) return 1;
    return 0;
};

Javascript how to split newline

Here is example with console.log instead of alert(). It is more convenient :)

var parse = function(){
  var str = $('textarea').val();
  var results = str.split("\n");
  $.each(results, function(index, element){
    console.log(element);
  });
};

$(function(){
  $('button').on('click', parse);
});

You can try it here

Error in finding last used cell in Excel with VBA

Since the original question is about problems with finding the last cell, in this answer I will list the various ways you can get unexpected results; see my answer to "How can I find last row that contains data in the Excel sheet with a macro?" for my take on solving this.

I'll start by expanding on the answer by sancho.s and the comment by GlennFromIowa, adding even more detail:

[...] one has first to decide what is considered used. I see at least 6 meanings. Cell has:

  • 1) data, i.e., a formula, possibly resulting in a blank value;
  • 2) a value, i.e., a non-blank formula or constant;
  • 3) formatting;
  • 4) conditional formatting;
  • 5) a shape (including Comment) overlapping the cell;
  • 6) involvement in a Table (List Object).

Which combination do you want to test for? Some (such as Tables) may be more difficult to test for, and some may be rare (such as a shape outside of data range), but others may vary based on the situation (e.g., formulas with blank values).

Other things you might want to consider:

  • A) Can there be hidden rows (e.g. autofilter), blank cells or blank rows?
  • B) What kind of performance is acceptable?
  • C) Can the VBA macro affect the workbook or the application settings in any way?

With that in mind, let's see how the common ways of getting the "last cell" can produce unexpected results:

  • The .End(xlDown) code from the question will break most easily (e.g. with a single non-empty cell or when there are blank cells in between) for the reasons explained in the answer by Siddharth Rout here (search for "xlDown is equally unreliable.")
  • Any solution based on Counting (CountA or Cells*.Count) or .CurrentRegion will also break in presence of blank cells or rows
  • A solution involving .End(xlUp) to search backwards from the end of a column will, just as CTRL+UP, look for data (formulas producing a blank value are considered "data") in visible rows (so using it with autofilter enabled might produce incorrect results ??).

    You have to take care to avoid the standard pitfalls (for details I'll again refer to the answer by Siddharth Rout here, look for the "Find Last Row in a Column" section), such as hard-coding the last row (Range("A65536").End(xlUp)) instead of relying on sht.Rows.Count.

  • .SpecialCells(xlLastCell) is equivalent to CTRL+END, returning the bottom-most and right-most cell of the "used range", so all caveats that apply to relying on the "used range", apply to this method as well. In addition, the "used range" is only reset when saving the workbook and when accessing worksheet.UsedRange, so xlLastCell might produce stale results?? with unsaved modifications (e.g. after some rows were deleted). See the nearby answer by dotNET.
  • sht.UsedRange (described in detail in the answer by sancho.s here) considers both data and formatting (though not conditional formatting) and resets the "used range" of the worksheet, which may or may not be what you want.

    Note that a common mistake ?is to use .UsedRange.Rows.Count??, which returns the number of rows in the used range, not the last row number (they will be different if the first few rows are blank), for details see newguy's answer to How can I find last row that contains data in the Excel sheet with a macro?

  • .Find allows you to find the last row with any data (including formulas) or a non-blank value in any column. You can choose whether you're interested in formulas or values, but the catch is that it resets the defaults in the Excel's Find dialog ????, which can be highly confusing to your users. It also needs to be used carefully, see the answer by Siddharth Rout here (section "Find Last Row in a Sheet")
  • More explicit solutions that check individual Cells' in a loop are generally slower than re-using an Excel function (although can still be performant), but let you specify exactly what you want to find. See my solution based on UsedRange and VBA arrays to find the last cell with data in the given column -- it handles hidden rows, filters, blanks, does not modify the Find defaults and is quite performant.

Whatever solution you pick, be careful

  • to use Long instead of Integer to store the row numbers (to avoid getting Overflow with more than 65k rows) and
  • to always specify the worksheet you're working with (i.e. Dim ws As Worksheet ... ws.Range(...) instead of Range(...))
  • when using .Value (which is a Variant) avoid implicit casts like .Value <> "" as they will fail if the cell contains an error value.

jQuery change input text value

When set the new value of element, you need call trigger change.

$('element').val(newValue).trigger('change');

Can I simultaneously declare and assign a variable in VBA?

You can sort-of do that with objects, as in the following.

Dim w As New Widget

But not with strings or variants.

How do I clear/delete the current line in terminal?

I'm not sure if you love it but I use Ctrl+A (to go beginning the line) and Ctrl+K (to delete the line) I was familiar with these commands from emacs, and figured out them accidently.

Java 8 forEach with index

It works with params if you capture an array with one element, that holds the current index.

int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));

The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.

If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:

int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));

jQuery - replace all instances of a character in a string

'some+multi+word+string'.replace(/\+/g, ' ');
                                   ^^^^^^

'g' = "global"

Cheers

YouTube embedded video: set different thumbnail

No. Most YouTube videos only have one pre-generated "poster" thumbnail (480x360). They usually have several other lower resolution thumbnails (120x90). So even if there were an embedding parameter to use an alternate poster image (which there isn't), it's result wouldn't be acceptable.

You can theoretically use the Player API to seek the video to whatever location you want, but this would be a major hack for a minor result.

How to negate specific word in regex?

Solution:

^(?!.*STRING1|.*STRING2|.*STRING3).*$

xxxxxx OK

xxxSTRING1xxx KO (is whether it is desired)

xxxSTRING2xxx KO (is whether it is desired)

xxxSTRING3xxx KO (is whether it is desired)

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

Subtract one day from datetime

To be honest I just use:

select convert(nvarchar(max), GETDATE(), 112)

which gives YYYYMMDD and minus one from it.

Or more correctly

select convert(nvarchar(max), GETDATE(), 112) - 1 

for yesterdays date.

Replace Getdate() with your value OrderDate

select convert(nvarchar (max),OrderDate,112)-1 AS SubtractDate FROM Orders

should do it.

How can a divider line be added in an Android RecyclerView?

The way how I'm handling the Divider view and also Divider Insets is by adding a RecyclerView extension.

1.

Add a new extension file by naming View or RecyclerView:

RecyclerViewExtension.kt

and add the setDivider extension method inside the RecyclerViewExtension.kt file.

/*
* RecyclerViewExtension.kt
* */
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView


fun RecyclerView.setDivider(@DrawableRes drawableRes: Int) {
    val divider = DividerItemDecoration(
        this.context,
        DividerItemDecoration.VERTICAL
    )
    val drawable = ContextCompat.getDrawable(
        this.context,
        drawableRes
    )
    drawable?.let {
        divider.setDrawable(it)
        addItemDecoration(divider)
    }
}

2.

Create a Drawable resource file inside of drawable package like recycler_view_divider.xml:

<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="10dp"
    android:insetRight="10dp">

    <shape>
        <size android:height="0.5dp" />
        <solid android:color="@android:color/darker_gray" />
    </shape>

</inset>

where you can specify the left and right margin on android:insetLeft and android:insetRight.

3.

On your Activity or Fragment where the RecyclerView is initialized, you can set the custom drawable by calling:

recyclerView.setDivider(R.drawable.recycler_view_divider)

4.

Cheers

RecyclerView row with divider.

Convert HashBytes to VarChar

Contrary to what David Knight says, these two alternatives return the same response in MS SQL 2008:

SELECT CONVERT(VARCHAR(32),HashBytes('MD5', 'Hello World'),2)
SELECT UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('MD5', 'Hello World'), 1, 0))

So it looks like the first one is a better choice, starting from version 2008.

How to change an Eclipse default project into a Java project

You can do it directly from eclipse using the Navigator view (Window -> Show View -> Navigator). In the Navigator view select the project and open it so that you can see the file .project. Right click -> Open. You will get a XML editor view. Edit the content of the node natures and insert a new child nature with org.eclipse.jdt.core.javanature as content. Save.

Now create a file .classpath, it will open in the XML editor. Add a node named classpath, add a child named classpathentry with the attributes kind with content con and another one named path and content org.eclipse.jdt.launching.JRE_CONTAINER. Save-

Much easier: copy the files .project and .classpath from an existing Java project and edit the node result name to the name of this project. Maybe you have to refresh the project (F5).

You'll get the same result as with the solution of Chris Marasti-Georg.

Edit

enter image description here

creating json object with variables

if you need double quoted JSON use JSON.stringify( object)

var $items = $('#firstName, #lastName,#phoneNumber,#address ')
var obj = {}
$items.each(function() {
    obj[this.id] = $(this).val();
})

var json= JSON.stringify( obj);

DEMO: http://jsfiddle.net/vANKa/1

Find the index of a dict within a list, by matching the dict's value

Seems most logical to use a filter/index combo:

names=[{}, {'name': 'Tom'},{'name': 'Tony'}]
names.index(filter(lambda n: n.get('name') == 'Tom', names)[0])
1

And if you think there could be multiple matches:

[names.index(n) for item in filter(lambda n: n.get('name') == 'Tom', names)]
[1]

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

Creating files in C++

Do this with a file stream. When a std::ofstream is closed, the file is created. I personally like the following code, because the OP only asks to create a file, not to write in it:

#include <fstream>

int main()
{
    std::ofstream file { "Hello.txt" };
    // Hello.txt has been created here
}

The temporary variable file is destroyed right after its creation, so the stream is closed and thus the file is created.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

I've had the same problem, but in my case Apache was already running and for some reason the XAMPP config tool didn't show that. It happened after I started XAMPP for the first time after the installation. After crashing the other Apache instances all was fine and ports 80 and 443 were free again.

So before making changes to your systeem, make sure something as obvious as the above isn't happening.

Capturing URL parameters in request.GET

I would like to share a tip that may save you some time.
If you plan to use something like this in your urls.py file:

url(r'^(?P<username>\w+)/$', views.profile_page,),

Which basically means www.example.com/<username>. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them will give you the nice error: User matching query does not exist.

I've just experienced it myself; hope it helps!

Connecting to Microsoft SQL server using Python

This is how I do it...

import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=server_name;"
                      "Database=db_name;"
                      "Trusted_Connection=yes;")


cursor = cnxn.cursor()
cursor.execute('SELECT * FROM Table')

for row in cursor:
    print('row = %r' % (row,))

Relevant resources:

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

Is it possible to cast a Stream in Java 8?

I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

Stream.of(objects)
    .filter(c -> c instanceof Client)
    .map(c -> (Client) c)
    .map(Client::getID)
    .forEach(System.out::println);

or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

Stream.of(objects)
    .filter(Client.class::isInstance)
    .map(Client.class::cast)
    .map(Client::getID)
    .forEach(System.out::println);

How to convert string to integer in C#

You can use either,

    int i = Convert.ToInt32(myString);

or

    int i =int.Parse(myString);

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

How to use data-binding with Fragment

You are actually encouraged to use the inflate method of your generated Binding and not the DataBindingUtil:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    MainFragmentBinding binding = MainFragmentBinding.inflate(inflater, container, false);
    //set variables in Binding
    return binding.getRoot();
}

Docs for DataBindingUtil.inflate():

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

Show/Hide Multiple Divs with Jquery

Just a small side-note... If you are using this with other scripts, the $ on the last line will cause a conflict. Just replace it with jQuery and you're good.

jQuery(function(){
     jQuery('#showall').click(function(){
           jQuery('.targetDiv').show();
    });
    jQuery('.showSingle').click(function(){
          jQuery('.targetDiv').hide();
          jQuery('#div'+jQuery(this).attr('target')).show();
    });
});

http://jsfiddle.net/XwN2L/4764/

SQL Server Express CREATE DATABASE permission denied in database 'master'

For SQL server 2012,

  1. First, log in to the SQL server as an administrator and go to Security tab

  2. Then move into Server Roles and double click on sysadmin role

  3. Now add user which you want to give permission to create Database by clicking Add button

  4. Click OK button and now run the query

Hope this will help for someone

Rounding a double value to x number of decimal places in swift

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

To round totalWorkTimeInHours to 3 digits for printing, use the String constructor which takes a format string:

print(String(format: "%.3f", totalWorkTimeInHours))

Read CSV with Scanner()

Please stop writing faulty CSV parsers!

I've seen hundreds of CSV parsers and so called tutorials for them online.

Nearly every one of them gets it wrong!

This wouldn't be such a bad thing as it doesn't affect me but people who try to write CSV readers and get it wrong tend to write CSV writers, too. And get them wrong as well. And these ones I have to write parsers for.

Please keep in mind that CSV (in order of increasing not so obviousness):

  1. can have quoting characters around values
  2. can have other quoting characters than "
  3. can even have other quoting characters than " and '
  4. can have no quoting characters at all
  5. can even have quoting characters on some values and none on others
  6. can have other separators than , and ;
  7. can have whitespace between seperators and (quoted) values
  8. can have other charsets than ascii
  9. should have the same number of values in each row, but doesn't always
  10. can contain empty fields, either quoted: "foo","","bar" or not: "foo",,"bar"
  11. can contain newlines in values
  12. can not contain newlines in values if they are not delimited
  13. can not contain newlines between values
  14. can have the delimiting character within the value if properly escaped
  15. does not use backslash to escape delimiters but...
  16. uses the quoting character itself to escape it, e.g. Frodo's Ring will be 'Frodo''s Ring'
  17. can have the quoting character at beginning or end of value, or even as only character ("foo""", """bar", """")
  18. can even have the quoted character within the not quoted value; this one is not escaped

If you think this is obvious not a problem, then think again. I've seen every single one of these items implemented wrongly. Even in major software packages. (e.g. Office-Suites, CRM Systems)

There are good and correctly working out-of-the-box CSV readers and writers out there:

If you insist on writing your own at least read the (very short) RFC for CSV.

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

how to check if a form is valid programmatically using jQuery Validation Plugin

For a group of inputs you can use an improved version based in @mikemaccana's answer

$.fn.isValid = function(){
    var validate = true;
    this.each(function(){
        if(this.checkValidity()==false){
            validate = false;
        }
    });
};

now you can use this to verify if the form is valid:

if(!$(".form-control").isValid){
    return;
}

You could use the same technique to get all the error messages:

$.fn.getVelidationMessage = function(){
    var message = "";
    var name = "";
    this.each(function(){
        if(this.checkValidity()==false){
            name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
            message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
        }
    })
    return message;
}

Android SDK manager won't open

I have solved this issue. If you are not able to open "SDK Manager.exe" from explorer or if you are facing any problem with SDK Manager.

Firstly check Java path is given in Environment Variable. (run Java command on CMD, or run Where Java on CMD as Administrator). If Java command is recognized, there might not be problem with Java

This might be due to broken SDK Tools. To fix it firstly rename tools folder (Android\Sdk\tools) to tools.old. Now download https://dl.google.com/android /repository/tools_r25.2.3-windows.zip?hl=id. After that Extract the downloaded zip files to Android\Sdk\ hence new tools folder would be extracted with all the contents for SDK. Now open SDK Manager.exe. If it opens your issue is solved. Please note that SDK Manager.exe is a launcher file that launches Android\Sdk\tools\bin\sdkmanager.bat. if you are satisfied with the answer please Upvote so that maximum users would solve the issue. For further help visit this page https://answers.unity.com/questions/1320150/unable-to-list-target-platform.html

Git keeps asking me for my ssh key passphrase

Another possible solution that is not mentioned above is to check your remote with the following command:

git remote -v

If the remote does not start with git but starts with https you might want to change it to git by following the example below.

git remote -v // origin is https://github.com/user/myrepo.git
git remote set-url origin [email protected]:user/myrepo.git
git remote -v // check if remote is changed

How to send json data in the Http request using NSURLRequest

Most of you already know this by now, but I am posting this, just incase, some of you are still struggling with JSON in iOS6+.

In iOS6 and later, we have the NSJSONSerialization Class that is fast and has no dependency on including "outside" libraries.

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

This is the way iOS6 and later can now parse JSON efficiently.The use of SBJson is also pre-ARC implementation and brings with it those issues too if you are working in an ARC environment.

I hope this helps!

How do I ignore files in a directory in Git?

It would be the former. Go by extensions as well instead of folder structure.

I.e. my example C# development ignore file:

#OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

Update

I thought I'd provide an update from the comments below. Although not directly answering the OP's question, see the following for more examples of .gitignore syntax.

Community wiki (constantly being updated):

.gitignore for Visual Studio Projects and Solutions

More examples with specific language use can be found here (thanks to Chris McKnight's comment):

https://github.com/github/gitignore

Parsing string as JSON with single quotes?

If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.

var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');

The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

CSS selector for disabled input type="submit"

As said by jensgram, IE6 does not support attribute selector. You could add a class="disabled" to select the disabled inputs so that this can work in IE6.

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

This is what I did to get iframe scrolling to work on iPad. Note that this solution only works if you control the html that is displayed inside the iframe.

It actually turns off the default iframe scrolling, and instead causes the body tag inside the iframe to scroll.

main.html:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 400px;
    height: 300px;
    overflow: hidden;
}
#iframe {
    width: 400px;
    height: 300px;
}
</style>
</head>
<body>

    <div id="container">
        <iframe src="test.html" id="iframe" scrolling="no"></iframe>
    </div>

</body>
</html>

test.html:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { 
    overflow: auto; 
    -webkit-overflow-scrolling: touch; 
}
body {
    height: 100%;
    overflow: auto; 
    -webkit-overflow-scrolling: touch;
    margin: 0;
    padding: 8px;
}
</style>
</head>
<body>
…
</body>
</html>

The same could probably be accomplished using jQuery if you prefer:

$("#iframe").contents().find("body").css({
    "height": "100%",
    "overflow": "auto", 
    "-webkit-overflow-scrolling": "touch"
});

I used this solution to get TinyMCE (wordpress editor) to scroll properly on the iPad.

Getting the exception value in Python

If you don't know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you'll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

Get file size before uploading

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#openFile').on('change', function(evt) {_x000D_
    console.log(this.files[0].size);_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">_x000D_
  <input id="openFile" name="img" type="file" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Python: How to pip install opencv2 with specific version 2.4.9?

First, get the correct opencv version extension which you want to install. If you want to install 3.4.9.20 then run pip install opencv-python==3.4.5.20.

ORA-01653: unable to extend table by in tablespace ORA-06512

To resolve this error:

ORA-01653 unable to extend table by 1024 in tablespace your-tablespace-name

Just run this PL/SQL command for extended tablespace size automatically on-demand:

alter database datafile '<your-tablespace-name>.dbf' autoextend on maxsize unlimited;

I get this error in import big dump file, just run this command without stopping import routine or restarting the database.

Note: each data file has a limit of 32GB of size if you need more than 32GB you should add a new data file to your existing tablespace.

More info: alter_autoextend_on

What is the difference between Select and Project Operations

The difference between the project operator (p) in relational algebra and the SELECT keyword in SQL is that if the resulting table/set has more than one occurrences of the same tuple, then p will return only one of them, while SQL SELECT will return all.

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

Create 3D array using Python

You should use a list comprehension:

>>> import pprint
>>> n = 3
>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][1]
[0, 0, 0]
>>> distance[0][1][2]
0

You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:

>>> distance=[[[0]*n]*n]*n
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][0][0] = 1
>>> pprint.pprint(distance)
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

Eclipse/Java code completion not working

Just in case anyone got to a desperate point where nothing works... It happened to us that the content assist somehow shrunk so no suggestion was shown, just the "Press Ctrl+Space for non-Java..." could be seen. So, it was just a matter of dragging the corner of the content assist to enlarge the pop-up.

I know, embarrassing. Hope it helps.

Note: this was an Ubuntu server with Xfce4 using Eclipse Oxygen.

Git Pull While Ignoring Local Changes?

this worked for me

git fetch --all
git reset --hard origin/master
git pull origin master

with the accepted answer I get conflict errors

Big-O summary for Java Collections Framework implementations?

The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).

List implementations:

                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)

Set implementations:

                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)

Map implementations:

                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)

Queue implementations:

                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

The bottom of the javadoc for the java.util package contains some good links:

How to get bitmap from a url in android?

This should do the trick:

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
} // Author: silentnuke

Don't forget to add the internet permission in your manifest.

How do I find a default constraint using INFORMATION_SCHEMA?

Object Catalog View : sys.default_constraints

The information schema views INFORMATION_SCHEMA are ANSI-compliant, but the default constraints aren't a part of ISO standard. Microsoft SQL Server provides system catalog views for getting information about SQL Server object metadata.

sys.default_constraints system catalog view used to getting the information about default constraints.

SELECT so.object_id TableName,
       ss.name AS TableSchema,
       cc.name AS Name,
       cc.object_id AS ObjectID,              
       sc.name AS ColumnName,
       cc.parent_column_id AS ColumnID,
       cc.definition AS Defination,
       CONVERT(BIT,
               CASE cc.is_system_named
                   WHEN 1
                   THEN 1
                   ELSE 0
               END) AS IsSystemNamed,
       cc.create_date AS CreationDate,
       cc.modify_date AS LastModifiednDate
FROM sys.default_constraints cc WITH (NOLOCK)
     INNER JOIN sys.objects so WITH (NOLOCK) ON so.object_id = cc.parent_object_id
     LEFT JOIN sys.schemas ss WITH (NOLOCK) ON ss.schema_id = so.schema_id
     LEFT JOIN sys.columns sc WITH (NOLOCK) ON sc.column_id = cc.parent_column_id
                                               AND sc.object_id = cc.parent_object_id
ORDER BY so.name,
         cc.name;

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

Loop through files in a folder using VBA?

The Dir function is the way to go, but the problem is that you cannot use the Dir function recursively, as stated here, towards the bottom.

The way that I've handled this is to use the Dir function to get all of the sub-folders for the target folder and load them into an array, then pass the array into a function that recurses.

Here's a class that I wrote that accomplishes this, it includes the ability to search for filters. (You'll have to forgive the Hungarian Notation, this was written when it was all the rage.)

Private m_asFilters() As String
Private m_asFiles As Variant
Private m_lNext As Long
Private m_lMax As Long

Public Function GetFileList(ByVal ParentDir As String, Optional ByVal sSearch As String, Optional ByVal Deep As Boolean = True) As Variant
    m_lNext = 0
    m_lMax = 0

    ReDim m_asFiles(0)
    If Len(sSearch) Then
        m_asFilters() = Split(sSearch, "|")
    Else
        ReDim m_asFilters(0)
    End If

    If Deep Then
        Call RecursiveAddFiles(ParentDir)
    Else
        Call AddFiles(ParentDir)
    End If

    If m_lNext Then
        ReDim Preserve m_asFiles(m_lNext - 1)
        GetFileList = m_asFiles
    End If

End Function

Private Sub RecursiveAddFiles(ByVal ParentDir As String)
    Dim asDirs() As String
    Dim l As Long
    On Error GoTo ErrRecursiveAddFiles
    'Add the files in 'this' directory!


    Call AddFiles(ParentDir)

    ReDim asDirs(-1 To -1)
    asDirs = GetDirList(ParentDir)
    For l = 0 To UBound(asDirs)
        Call RecursiveAddFiles(asDirs(l))
    Next l
    On Error GoTo 0
Exit Sub
ErrRecursiveAddFiles:
End Sub
Private Function GetDirList(ByVal ParentDir As String) As String()
    Dim sDir As String
    Dim asRet() As String
    Dim l As Long
    Dim lMax As Long

    If Right(ParentDir, 1) <> "\" Then
        ParentDir = ParentDir & "\"
    End If
    sDir = Dir(ParentDir, vbDirectory Or vbHidden Or vbSystem)
    Do While Len(sDir)
        If GetAttr(ParentDir & sDir) And vbDirectory Then
            If Not (sDir = "." Or sDir = "..") Then
                If l >= lMax Then
                    lMax = lMax + 10
                    ReDim Preserve asRet(lMax)
                End If
                asRet(l) = ParentDir & sDir
                l = l + 1
            End If
        End If
        sDir = Dir
    Loop
    If l Then
        ReDim Preserve asRet(l - 1)
        GetDirList = asRet()
    End If
End Function
Private Sub AddFiles(ByVal ParentDir As String)
    Dim sFile As String
    Dim l As Long

    If Right(ParentDir, 1) <> "\" Then
        ParentDir = ParentDir & "\"
    End If

    For l = 0 To UBound(m_asFilters)
        sFile = Dir(ParentDir & "\" & m_asFilters(l), vbArchive Or vbHidden Or vbNormal Or vbReadOnly Or vbSystem)
        Do While Len(sFile)
            If Not (sFile = "." Or sFile = "..") Then
                If m_lNext >= m_lMax Then
                    m_lMax = m_lMax + 100
                    ReDim Preserve m_asFiles(m_lMax)
                End If
                m_asFiles(m_lNext) = ParentDir & sFile
                m_lNext = m_lNext + 1
            End If
            sFile = Dir
        Loop
    Next l
End Sub

What are all the possible values for HTTP "Content-Type" header?

You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml

The most common type are:

  1. Type application

    application/java-archive
    application/EDI-X12   
    application/EDIFACT   
    application/javascript   
    application/octet-stream   
    application/ogg   
    application/pdf  
    application/xhtml+xml   
    application/x-shockwave-flash    
    application/json  
    application/ld+json  
    application/xml   
    application/zip  
    application/x-www-form-urlencoded  
    
  2. Type audio

    audio/mpeg   
    audio/x-ms-wma   
    audio/vnd.rn-realaudio   
    audio/x-wav   
    
  3. Type image

    image/gif   
    image/jpeg   
    image/png   
    image/tiff    
    image/vnd.microsoft.icon    
    image/x-icon   
    image/vnd.djvu   
    image/svg+xml    
    
  4. Type multipart

    multipart/mixed    
    multipart/alternative   
    multipart/related (using by MHTML (HTML mail).)  
    multipart/form-data  
    
  5. Type text

    text/css    
    text/csv    
    text/html    
    text/javascript (obsolete)    
    text/plain    
    text/xml    
    
  6. Type video

    video/mpeg    
    video/mp4    
    video/quicktime    
    video/x-ms-wmv    
    video/x-msvideo    
    video/x-flv   
    video/webm   
    
  7. Type vnd :

    application/vnd.android.package-archive
    application/vnd.oasis.opendocument.text    
    application/vnd.oasis.opendocument.spreadsheet  
    application/vnd.oasis.opendocument.presentation   
    application/vnd.oasis.opendocument.graphics   
    application/vnd.ms-excel    
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet   
    application/vnd.ms-powerpoint    
    application/vnd.openxmlformats-officedocument.presentationml.presentation    
    application/msword   
    application/vnd.openxmlformats-officedocument.wordprocessingml.document   
    application/vnd.mozilla.xul+xml   
    

Breaking up long strings on multiple lines in Ruby without stripping newlines

I had this problem when I try to write a very long url, the following works.

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

JSON Post with Customized HTTPHeader Field

I tried as you mentioned, but only first parameter is going through and rest all are appearing in the server as undefined. I am passing JSONWebToken as part of header.

.ajax({
    url: 'api/outletadd',
    type: 'post',
    data: { outletname:outletname , addressA:addressA , addressB:addressB, city:city , postcode:postcode , state:state , country:country , menuid:menuid },
    headers: {
        authorization: storedJWT
    },
    dataType: 'json',
    success: function (data){
        alert("Outlet Created");
    },
    error: function (data){
        alert("Outlet Creation Failed, please try again.");        
    }

    });

Best /Fastest way to read an Excel Sheet into a DataTable?

I've used this method and for me, it is so efficient and fast.

// Step 1. Download NuGet source of Generic Parsing by Andrew Rissing
// Step 2. Reference this to your project
// Step 3. Reference Microsoft.Office.Interop.Excel to your project
// Step 4. Follow the logic below

public static DataTable ExcelSheetToDataTable(string filePath) {

    // Save a copy of the Excel file as CSV
    var xlApp = new XL.Application();
    var xlWbk = xlApp.Workbooks.Open(filePath);
    var tempPath =
        Path.Combine(Environment
            .GetFolderPath(Environment.SpecialFolder.UserProfile)
            , "AppData"
            , "Local",
            , "Temp"
            , Path.GetFileNameWithoutExtension(filePath) + ".csv");

    xlApp.DisplayAlerts = false;
    xlWbk.SaveAs(tempPath, XL.XlFileFormat.xlCSV);
    xlWbk.Close(SaveChanges: false);
    xlApp.Quit();

    // The actual parsing
    using (var parser = new GenericParserAdapter(tempPath)) {
        parser.FirstRowHasHeader = true;
        return parser.GetDataTable();
    }

}

Generic Parsing by Andrew Rissing

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

If anyone stumbles across this as it is the first result in google,

remember to specify the filename too in the SaveAs method.

Won't work

file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation));

You need this:

filename = Path.GetFileName(file_upload.PostedFile.FileName);
file_upload.PostedFile.SaveAs(Server.MapPath(SaveLocation + "\\" + filename));

I assumed the SaveAs method will automatically use the filename uploaded. Kept getting "Access denied" error. Not very descriptive of the actual problem

Notepad++ Multi editing

Notepad++ also handles multiple cursors now.

Go into Settings => Preferences => Editing and check "Enable" in "Multi editing settings" Then, just use Ctrl+click to use multiple cursors.

Feature demo on official website here : https://npp-user-manual.org/docs/editing/

Visual Studio 2015 doesn't have cl.exe

For me that have Visual Studio 2015 this works:
Search this in the start menu: Developer Command Prompt for VS2015 and run the program in the search result.
You can now execute your command in it, for example: cl /?

How do I set headers using python's urllib?

Use urllib2 and create a Request object which you then hand to urlopen. http://docs.python.org/library/urllib2.html

I dont really use the "old" urllib anymore.

req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()

untested....

Get the _id of inserted document in Mongo database in NodeJS

Mongo sends the complete document as a callbackobject so you can simply get it from there only.

for example

collection.save(function(err,room){
  var newRoomId = room._id;
  });

Fixed footer in Bootstrap

Add z-index:-9999; to this method, or it will cover your top bar if you have 1.

Pure CSS animation visibility with delay

Use animation-delay:

div {
    width: 100px;
    height: 100px;
    background: red;
    opacity: 0;

    animation: fadeIn 3s;
    animation-delay: 5s;
    animation-fill-mode: forwards;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

Fiddle

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

I dont think default backup location is stored within the SQL server itself. The settings are stored in Registry. Look for "BackupDirectory" key and you'll find the default backup.

The "msdb.dbo.backupset" table consists of list of backups taken, if no backup is taken for a database, it won't show you anything

Flutter position stack widget in center

You can use the Positioned.fill with Align inside a Stack:

Stack(
  children: <Widget>[      
    Positioned.fill(
      child: Align(
        alignment: Alignment.centerRight,
        child: ....                
      ),
    ),
  ],
),

jQuery scroll() detect when user stops scrolling

You could set an interval that runs every 500 ms or so, along the lines of the following:

var curOffset, oldOffset;
oldOffset = $(window).scrollTop();
var $el = $('.slides_layover'); // cache jquery ref
setInterval(function() {
  curOffset = $(window).scrollTop();
  if(curOffset != oldOffset) {
    // they're scrolling, remove your class here if it exists
    if($el.hasClass('showing_layover')) $el.removeClass('showing_layover');
  } else {
    // they've stopped, add the class if it doesn't exist
    if(!$el.hasClass('showing_layover')) $el.addClass('showing_layover');
  }
  oldOffset = curOffset;
}, 500);

I haven't tested this code, but the principle should work.

Setting POST variable without using form

If you want to set $_POST['text'] to another value, why not use:

$_POST['text'] = $var;

on next.php?

How to edit data in result grid in SQL Server Management Studio

The way you can do this is by:

  • turning your select query into a view
  • right click on the view and choose Edit All Rows (you will get a grid of values you can edit - even if the values are from different tables).

You can also add Insert/Update triggers to your view that will allow you to grab the values from your view fields and then use T-SQL to manage updates to multiple tables.

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

Why won't bundler install JSON gem?

Switch ruby version from 1.9 to 2.2 with rvm did the job for me

Android. WebView and loadData

The safest way to load htmlContent in a Web view is to:

  1. use base64 encoding (official recommendation)
  2. specify UFT-8 for html content type, i.e., "text/html; charset=utf-8" instead of "text/html" (personal advice)

"Base64 encoding" is an official recommendation that has been written again (already present in Javadoc) in the latest 01/2019 bug in Chrominium (present in WebView M72 (72.0.3626.76)):

https://bugs.chromium.org/p/chromium/issues/detail?id=929083

Official statement from Chromium team:

"Recommended fix:
Our team recommends you encode data with Base64. We've provided examples for how to do so:

This fix is backwards compatible (it works on earlier WebView versions), and should also be future-proof (you won't hit future compatibility problems with respect to content encoding)."

Code sample:

webView.loadData(
    Base64.encodeToString(
        htmlContent.getBytes(StandardCharsets.UTF_8),
        Base64.DEFAULT), // encode in Base64 encoded 
    "text/html; charset=utf-8", // utf-8 html content (personal recommendation)
    "base64"); // always use Base64 encoded data: NEVER PUT "utf-8" here (using base64 or not): This is wrong! 

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

Converting an integer to binary in C

void intToBin(int digit) {
    int b;
    int k = 0;
    char *bits;

    bits= (char *) malloc(sizeof(char));
    printf("intToBin\n");
    while (digit) {
        b = digit % 2;
        digit = digit / 2;
        bits[k] = b;
        k++;

        printf("%d", b);
    }
    printf("\n");
    for (int i = k - 1; i >= 0; i--) {
        printf("%d", bits[i]);

    }

}

addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

Get pixel color from canvas, on mousemove

calling getImageData every time will slow the process ... to speed up things i recommend store image data and then you can get pix value easily and quickly, so do something like this for better performance

// keep it global
let imgData = false;  // initially no image data we have

// create some function block 
if(imgData === false){   
  // fetch once canvas data     
  var ctx = canvas.getContext("2d");
  imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
    // Prepare your X Y coordinates which you will be fetching from your mouse loc
    let x = 100;   // 
    let y = 100;
    // locate index of current pixel
    let index = (y * imgData.width + x) * 4;

        let red = imgData.data[index];
        let green = imgData.data[index+1];
        let blue = imgData.data[index+2];
        let alpha = imgData.data[index+3];
   // Output
   console.log('pix x ' + x +' y '+y+ ' index '+index +' COLOR '+red+','+green+','+blue+','+alpha);

Java: how to use UrlConnection to post request with authorization?

HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?

Effective way to find any file's Encoding

It may be useful

string path = @"address/to/the/file.extension";

using (StreamReader sr = new StreamReader(path))
{ 
    Console.WriteLine(sr.CurrentEncoding);                        
}

Android 8: Cleartext HTTP traffic not permitted

Simple and Easiest Solution [Xamarin Form]

For Android

  1. Goto Android Project, then Click on Properties,

enter image description here

  1. Open AssemblyInfo.cs and paste this code right there:

    [assembly: Application(UsesCleartextTraffic =true)]

enter image description here

For iOS

Use NSAppTransportSecurity:

Enter image description here

You have to set the NSAllowsArbitraryLoads key to YES under NSAppTransportSecurity dictionary in your info.plist file.

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

Plist configuration

Android EditText delete(backspace) key event

for some one who's using Kotlin

addOnTextChanged is not flexible enought to handle some cases (ex: detect if user press delete when edit text was empty)

setOnkeyListener worked even soft keyboard or hardkeyboard! but just on some devices. In my case, it work on Samsung s8 but not work on Xiaomi mi8 se.

if you using kotlin, you can use crossline function doOnTextChanged, it's the same as addOnTextChanged but callback is triggered even edit text was empty.

NOTE: doOnTextChanged is a part of Android KTX library

How do I "commit" changes in a git submodule?

$ git submodule status --recursive

Is also a life saver in this situation. You can use it and gitk --all to keep track of your sha1's and verify your sub-modules are pointing at what you think they are.

Where's the DateTime 'Z' format specifier?

Round tripping dates through strings has always been a pain...but the docs to indicate that the 'o' specifier is the one to use for round tripping which captures the UTC state. When parsed the result will usually have Kind == Utc if the original was UTC. I've found that the best thing to do is always normalize dates to either UTC or local prior to serializing then instruct the parser on which normalization you've chosen.

DateTime now = DateTime.Now;
DateTime utcNow = now.ToUniversalTime();

string nowStr = now.ToString( "o" );
string utcNowStr = utcNow.ToString( "o" );

now = DateTime.Parse( nowStr );
utcNow = DateTime.Parse( nowStr, null, DateTimeStyles.AdjustToUniversal );

Debug.Assert( now == utcNow );

How to Select Min and Max date values in Linq Query

dim mydate = from cv in mydata.t1s
  select cv.date1 asc

datetime mindata = mydate[0];

How to get MAC address of your machine using a C program?

Expanding on the answer given by @user175104 ...

std::vector<std::string> GetAllFiles(const std::string& folder, bool recursive = false)
{
  // uses opendir, readdir, and struct dirent.
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

bool ReadFileContents(const std::string& folder, const std::string& fname, std::string& contents)
{
  // uses ifstream to read entire contents
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

std::vector<std::string> GetAllMacAddresses()
{
  std::vector<std::string> macs;
  std::string address;

  // from: https://stackoverflow.com/questions/9034575/c-c-linux-mac-address-of-all-interfaces
  //  ... just read /sys/class/net/eth0/address

  // NOTE: there may be more than one: /sys/class/net/*/address
  //  (1) so walk /sys/class/net/* to find the names to read the address of.

  std::vector<std::string> nets = GetAllFiles("/sys/class/net/", false);
  for (auto it = nets.begin(); it != nets.end(); ++it)
  {
    // we don't care about the local loopback interface
    if (0 == strcmp((*it).substr(-3).c_str(), "/lo"))
      continue;
    address.clear();
    if (ReadFileContents(*it, "address", address))
    {
      if (!address.empty())
      {
        macs.push_back(address);
      }
    }
  }
  return macs;
}

How to set up subdomains on IIS 7

Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.

*.example.com IN A 1.2.3.4

http://www.webmasterworld.com/microsoft_asp_net/3194877.htm

Html.DropdownListFor selected value not being set

You should forget the class

SelectList

Use this in your Controller:

var customerTypes = new[] 
{ 
    new SelectListItem(){Value = "all", Text= "All"},
    new SelectListItem(){Value = "business", Text= "Business"},
    new SelectListItem(){Value = "private", Text= "Private"},
};

Select the value:

var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private");
if (selectedCustomerType != null)
    selectedCustomerType.Selected = true;

Add the list to the ViewData:

ViewBag.CustomerTypes = customerTypes;

Use this in your View:

@Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes)

-

More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

How to make the web page height to fit screen height

you can use css to set the body tag to these settings:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

C# difference between == and Equals()

Just as an addition to the already good answers: This behaviour is NOT limited to Strings or comparing different numbertypes. Even if both elements are of type object of the same underlying type. "==" won't work.

The following screenshot shows the results of comparing two object {int} - values

Example From VS2017

Can't push image to Amazon ECR - fails with "no basic auth credentials"

Try with:

eval $(aws ecr get-login --no-include-email | sed 's|https://||')

before push.

Convert String to int array in java

String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());

SQL to Entity Framework Count Group-By

Edit: EF Core 2.1 finally supports GroupBy

But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.


Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy() for translation to GROUP BY in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.

Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.

For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.

If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.

https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2

equivalent to push() or pop() for arrays?

You can use LinkedList. It has methods peek, poll and offer.

Sublime 3 - Set Key map for function Goto Definition

To set go to definition to alt + d. From the Menu Preferences > Key Bindings-User. And then add the following JSON.

[
    { "keys": ["alt+d"], "command": "goto_definition" }
]

alternatives to REPLACE on a text or ntext datatype

IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

For SQL Server 2005+:

UPDATE [CMS_DB_test].[dbo].[cms_HtmlText] 
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%' 

Zoom to fit all markers in Mapbox or Leaflet

You have an array of L.Marker:

let markers = [marker1, marker2, marker3]

let latlngs = markers.map(marker => marker.getLatLng())

let latlngBounds = L.latLngBounds(latlngs)

map.fitBounds(latlngBounds)
// OR with a smooth animation
// map.flyToBounds(latlngBounds)

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

How to go back (ctrl+z) in vi/vim

Here is a trick though. You can map the Ctrl+Z keys. This can be achieved by editing the .vimrc file. Add the following lines in the '.vimrc` file.

nnoremap <c-z> :u<CR>      " Avoid using this**
inoremap <c-z> <c-o>:u<CR>

This may not the a preferred way, but can be used.

** Ctrl+Z is used in Linux to suspend the ongoing program/process.

ngFor with index as value in attribute

Try this

<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>

What is meant by the term "hook" in programming?

A chain of hooks is a set of functions in which each function calls the next. What is significant about a chain of hooks is that a programmer can add another function to the chain at run time. One way to do this is to look for a known location where the address of the first function in a chain is kept. You then save the value of that function pointer and overwrite the value at the initial address with the address of the function you wish to insert into the hook chain. The function then gets called, does its business and calls the next function in the chain (unless you decide otherwise). Naturally, there are a number of other ways to create a chain of hooks, from writing directly to memory to using the metaprogramming facilities of languages like Ruby or Python.

An example of a chain of hooks is the way that an MS Windows application processes messages. Each function in the processing chain either processes a message or sends it to the next function in the chain.

Random float number generation

In modern c++ you may use the <random> header that came with c++11.
To get random float's you can use std::uniform_real_distribution<>.

You can use a function to generate the numbers and if you don't want the numbers to be the same all the time, set the engine and distribution to be static.
Example:

float get_random()
{
    static std::default_random_engine e;
    static std::uniform_real_distribution<> dis(0, 1); // rage 0 - 1
    return dis(e);
}

It's ideal to place the float's in a container such as std::vector:

int main()
{
    std::vector<float> nums;
    for (int i{}; i != 5; ++i) // Generate 5 random floats
        nums.emplace_back(get_random());

    for (const auto& i : nums) std::cout << i << " ";
}

Example output:

0.0518757 0.969106 0.0985112 0.0895674 0.895542

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

Java collections maintaining insertion order

I can't cite a reference, but by design the List and Set implementations of the Collection interface are basically extendable Arrays. As Collections by default offer methods to dynamically add and remove elements at any point -- which Arrays don't -- insertion order might not be preserved. Thus, as there are more methods for content manipulation, there is a need for special implementations that do preserve order.

Another point is performance, as the most well performing Collection might not be that, which preserves its insertion order. I'm however not sure, how exactly Collections manage their content for performance increases.

So, in short, the two major reasons I can think of why there are order-preserving Collection implementations are:

  1. Class architecture
  2. Performance

Best way to do a PHP switch with multiple values per case?

You are simply looking for common patterns in strings. I would have thought a regular expression would be a more efficient way of doing this as PHP implements this with preg_match so little code to write and probably massively quicker. For example:

case preg_match('/^users./'):
// do something here
break;

How to make an HTTP get request with parameters

The WebRequest object seems like too much work for me. I prefer to use the WebClient control.

To use this function you just need to create two NameValueCollections holding your parameters and request headers.

Consider the following function:

    private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
    {
        string ResponseText = null;
        using (WebClient client = new WebClient())
        {
            try
            {
                if (RequestHeaders != null)
                {
                    if (RequestHeaders.Count > 0)
                    {
                        foreach (string header in RequestHeaders.AllKeys)
                            client.Headers.Add(header, RequestHeaders[header]);
                    }
                }
                if (QueryStringParameters != null)
                {
                    if (QueryStringParameters.Count > 0)
                    {
                        foreach (string parm in QueryStringParameters.AllKeys)
                            client.QueryString.Add(parm, QueryStringParameters[parm]);
                    }
                }
                byte[] ResponseBytes = client.DownloadData(URL);
                ResponseText = Encoding.UTF8.GetString(ResponseBytes);
            }
            catch (WebException exception)
            {
                if (exception.Response != null)
                {
                    var responseStream = exception.Response.GetResponseStream();

                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            Response.Write(reader.ReadToEnd());
                        }
                    }
                }
            }
        }
        return ResponseText;
    }

Add your querystring parameters (if required) as a NameValueCollection like so.

        NameValueCollection QueryStringParameters = new NameValueCollection();
        QueryStringParameters.Add("id", "123");
        QueryStringParameters.Add("category", "A");

Add your http headers (if required) as a NameValueCollection like so.

        NameValueCollection RequestHttpHeaders = new NameValueCollection();
        RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");

How to use continue in jQuery each() loop?

return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".

Type or namespace name does not exist

I encountered this problem while using Visual Studio's Git integration to manage the project. For some reason the Windows Phone 8 project would compile just fine when targeting x86, but when I set it to target ARM, it would fail compiling with an error indicating that "Advertising" didn't exist in the Microsoft namespace.

I ended up resolving the issue by removing the Microsoft.Advertising.*.dll reference and adding it again.

How to get the real and total length of char * (char array)?

You can't. Not with 100% accuracy, anyway. The pointer has no length/size but its own. All it does is point to a particular place in memory that holds a char. If that char is part of a string, then you can use strlen to determine what chars follow the one currently being pointed to, but that doesn't mean the array in your case is that big.
Basically:

A pointer is not an array, so it doesn't need to know what the size of the array is. A pointer can point to a single value, so a pointer can exist without there even being an array. It doesn't even care where the memory it points to is situated (Read only, heap or stack... doesn't matter). A pointer doesn't have a length other than itself. A pointer just is...
Consider this:

char beep = '\a';
void alert_user(const char *msg, char *signal); //for some reason
alert_user("Hear my super-awsome noise!", &beep); //passing pointer to single char!

void alert_user(const char *msg, char *signal)
{
    printf("%s%c\n", msg, *signal);
}

A pointer can be a single char, as well as the beginning, end or middle of an array...
Think of chars as structs. You sometimes allocate a single struct on the heap. That, too, creates a pointer without an array.

Using only a pointer, to determine how big an array it is pointing to is impossible. The closest you can get to it is using calloc and counting the number of consecutive \0 chars you can find through the pointer. Of course, that doesn't work once you've assigned/reassigned stuff to that array's keys and it also fails if the memory just outside of the array happens to hold \0, too. So using this method is unreliable, dangerous and just generally silly. Don't. Do. It.

Another analogy:
Think of a pointer as a road sign, it points to Town X. The sign doesn't know what that town looks like, and it doesn't know or care (or can care) who lives there. It's job is to tell you where to find Town X. It can only tell you how far that town is, but not how big it is. That information is deemed irrelevant for road-signs. That's something that you can only find out by looking at the town itself, not at the road-signs that are pointing you in its direction

So, using a pointer the only thing you can do is:

char a_str[] = "hello";//{h,e,l,l,o,\0}
char *arr_ptr = &a_str[0];
printf("Get length of string -> %d\n", strlen(arr_ptr));

But this, of course, only works if the array/string is \0-terminated.

As an aside:

int length = sizeof(a)/sizeof(char);//sizeof char is guaranteed 1, so sizeof(a) is enough

is actually assigning size_t (the return type of sizeof) to an int, best write:

size_t length = sizeof(a)/sizeof(*a);//best use ptr's type -> good habit

Since size_t is an unsigned type, if sizeof returns bigger values, the value of length might be something you didn't expect...

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

How can I select checkboxes using the Selenium Java WebDriver?

I tried with various approaches, but nothing worked. I kept getting "Cannot click element" or ElementNotVisibleException.

I was able to find the input, but I couldn't check it. Now, I'm clicking on the div that contains the checkbox and it works with following HTML (CSS based on Bootstrap).

 @foreach (var item in Model)
 {
     <tr>
         <td>
             <div id="@item.Id" class="checkbox">
                 <label><input type="checkbox" class="selectone" value="@item.Id"></label>
             </div>
         </td>
         <td val="@item.Id">
             @item.Detail
         </td>
         <td>
             <div>@item.Desc
             </div>
         </td>
         <td>
             @Html.ActionLink("Edit", "Create", new { EditId = item.Id })
         </td>
     </tr>
 }

This is the code for WebDriver:

var table = driver.FindElement(By.TagName("table"));
var tds = table.FindElements(By.TagName("td"));
var itemTds = tds.Where(t => t.Text == itemtocheck);
foreach (var td in itemTds)
{
    var CheckBoxTd = tds[tds.IndexOf(td) - 1];
    var val = td.GetAttribute("val");
    CheckBoxTd.FindElement(By.Id(val)).Click();
}

In this approach, I give the item id as id for the div and also add an attribute for td with that id. Once I find the td of the item that needs to be checked, I can find the div before that td and click it. We can also use the XPath query that supports before (here is the example http://learn-automation.com/how-to-write-dynamic-xpath-in-selenium/).

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Windows ignores JAVA_HOME: how to set JDK as default?

There's an additional factor here; in addition to the java executables that the java installation puts wherever you ask it to put them, on windows, the java installer also puts copies of some of those executables in your windows system32 directory, so you will likely be using which every java executable was installed most recently.

How do I create a unique constraint that also allows nulls?

Maybe consider an "INSTEAD OF" trigger and do the check yourself? With a non-clustered (non-unique) index on the column to enable the lookup.

Toggle button using two image on different state

You can try something like this. Here on click of image button I toggle the imageview.

holder.imgitem.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if(!onclick){
            mSparseBooleanArray.put((Integer) view.getTag(), true);
            holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_delete_overlay_com);
            onclick=true;}
            else if(onclick)
            {
                 mSparseBooleanArray.put((Integer) view.getTag(), false);
                  holder.imgoverlay.setImageResource(R.drawable.ipad_768x1024_editmode_selection_com);

            onclick=false;
            }
        }
    });

How to download Visual Studio 2017 Community Edition for offline installation?

You should goto the Layout folder and issue the following command:

F:\vs2017c>vs_community.exe /finalizeInstall

Then it will auto pickup cache components bypass downloading.

How can I execute a python script from an html button?

This would require knowledge of a backend website language.

Fortunately, Python's Flask Library is a suitable backend language for the project at hand.

Check out this answer from another thread.

Run JavaScript in Visual Studio Code

I am surprised this has not been mentioned yet:

Simply open the .js file in question in VS Code, switch to the 'Debug Console' tab, hit the debug button in the left nav bar, and click the run icon (play button)!

Requires nodejs to be installed!

Can you center a Button in RelativeLayout?

It's pretty simple, just use Android:CenterInParent="true" to center both in horizontal and vertical, or use Android:Horizontal="true" to center in horizontal and Android:Vertical="true"

And make sure you write all this in RelaytiveLayout

Notification Icon with the new Firebase Cloud Messaging system

if your app is in background the notification icon will be set onMessage Receive method but if you app is in foreground the notification icon will be the one you defined on manifest

enter image description here

Android, landscape only orientation?

When you are in android studio 3 or above you need to add following lines AndroidManifest.xml file

<activity
            android:name=".MainActivity"
            android:configChanges="orientation"
            android:screenOrientation= "sensorLandscape"
            tools:ignore="LockedOrientationActivity">

One thing this is sensor Landscape, means it will work on both landscape sides

But if you only want to work the regular landscape side then, replace sensorLandscape to landscape

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

Incrementing a variable inside a Bash loop

I had the same $count variable in a while loop getting lost issue.

@fedorqui's answer (and a few others) are accurate answers to the actual question: the sub-shell is indeed the problem.

But it lead me to another issue: I wasn't piping a file content... but the output of a series of pipes & greps...

my erroring sample code:

count=0
cat /etc/hosts | head | while read line; do
  ((count++))
  echo $count $line
done
echo $count

and my fix thanks to the help of this thread and the process substitution:

count=0
while IFS= read -r line; do
  ((count++))
  echo "$count $line"
done < <(cat /etc/hosts | head)
echo "$count"

how to avoid extra blank page at end while printing?

I just encountered a case where changing from

    </div>
    <script src="addressofjavascriptfile.js"></script>
</body>
</html>

to

        <script src="addressofjavascriptfile.js"></script>
    </div>
</body>
</html>

fixed this problem.

AngularJS: How can I pass variables between controllers?

I tend to use values, happy for anyone to discuss why this is a bad idea..

var myApp = angular.module('myApp', []);

myApp.value('sharedProperties', {}); //set to empty object - 

Then inject the value as per a service.

Set in ctrl1:

myApp.controller('ctrl1', function DemoController(sharedProperties) {
  sharedProperties.carModel = "Galaxy";
  sharedProperties.carMake = "Ford";
});

and access from ctrl2:

myApp.controller('ctrl2', function DemoController(sharedProperties) {
  this.car = sharedProperties.carModel + sharedProperties.carMake; 

});

Javascript equivalent of php's strtotime()?

_x000D_
_x000D_
var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');_x000D_
var date = moment(strdate).format('DD.MM.YYYY');_x000D_
$("#result").text(date); //07.02.2017
_x000D_
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>_x000D_
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_