Programs & Examples On #Error checking

What is the canonical way to check for errors using the CUDA runtime API?

The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.

The relevant code is copied below:

#include <stdio.h>
#include <stdlib.h>

__global__ void foo(int *ptr)
{
  *ptr = 7;
}

int main(void)
{
  foo<<<1,1>>>(0);

  // make the host block until the device is finished with foo
  cudaDeviceSynchronize();

  // check for error
  cudaError_t error = cudaGetLastError();
  if(error != cudaSuccess)
  {
    // print the CUDA error message and exit
    printf("CUDA error: %s\n", cudaGetErrorString(error));
    exit(-1);
  }

  return 0;
}

jQuery UI Datepicker - Multiple Date Selections

Use this plugin http://multidatespickr.sourceforge.net

  • Select date ranges.
  • Pick multiple dates not in secuence.
  • Define a maximum number of pickable dates.
  • Define a range X days from where it is possible to select Y dates. Define unavailable dates

Python 'list indices must be integers, not tuple"

The problem is that [...] in python has two distinct meanings

  1. expr [ index ] means accessing an element of a list
  2. [ expr1, expr2, expr3 ] means building a list of three elements from three expressions

In your code you forgot the comma between the expressions for the items in the outer list:

[ [a, b, c] [d, e, f] [g, h, i] ]

therefore Python interpreted the start of second element as an index to be applied to the first and this is what the error message is saying.

The correct syntax for what you're looking for is

[ [a, b, c], [d, e, f], [g, h, i] ]

Arrow operator (->) usage in C

struct Node {
    int i;
    int j;
};
struct Node a, *p = &a;

Here the to access the values of i and j we can use the variable a and the pointer p as follows: a.i, (*p).i and p->i are all the same.

Here . is a "Direct Selector" and -> is an "Indirect Selector".

How to create an infinite loop in Windows batch file?

Unlimited loop in one-line command for use in cmd windows:

FOR /L %N IN () DO @echo Oops

enter image description here

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

Wget output document and headers to STDOUT

It works here:

    $ wget -S -O - http://google.com
HTTP request sent, awaiting response... 
  HTTP/1.1 301 Moved Permanently
  Location: http://www.google.com/
  Content-Type: text/html; charset=UTF-8
  Date: Sat, 25 Aug 2012 10:15:38 GMT
  Expires: Mon, 24 Sep 2012 10:15:38 GMT
  Cache-Control: public, max-age=2592000
  Server: gws
  Content-Length: 219
  X-XSS-Protection: 1; mode=block
  X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29--  http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...

  ...skipped a few more redirections ...

    [<=>                                                                                                                                     ] 0           --.-K/s              
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti 

... skipped ...

perhaps you need to update your wget (~$ wget --version GNU Wget 1.14 built on linux-gnu.)

Correct way to push into state array

Using Functional Components and React Hooks

const [array,setArray] = useState([]);

Push value at the end:

setArray(oldArray => [...oldArray,newValue] );

Push value at the begging:

setArray(oldArray => [newValue,...oldArrays] );

PHP Echo text Color

How about writing out some escape sequences?

echo "\033[01;31m Request has been sent. Please wait for my reply! \033[0m";

Won't work through browser though, only from console ;))

Spring jUnit Testing properties file

As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:

@TestPropertySource("classpath:application-test.properties")

Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource

How to set a value for a selectize.js input?

just ran into the same problem and solved it with the following line of code:

selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value"); 

ReactJS - Does render get called any time "setState" is called?

Even though it's stated in many of the other answers here, the component should either:

  • implement shouldComponentUpdate to render only when state or properties change

  • switch to extending a PureComponent, which already implements a shouldComponentUpdate method internally for shallow comparisons.

Here's an example that uses shouldComponentUpdate, which works only for this simple use case and demonstration purposes. When this is used, the component no longer re-renders itself on each click, and is rendered when first displayed, and after it's been clicked once.

_x000D_
_x000D_
var TimeInChild = React.createClass({_x000D_
    render: function() {_x000D_
        var t = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <p>Time in child:{t}</p>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Main = React.createClass({_x000D_
    onTest: function() {_x000D_
        this.setState({'test':'me'});_x000D_
    },_x000D_
_x000D_
    shouldComponentUpdate: function(nextProps, nextState) {_x000D_
      if (this.state == null)_x000D_
        return true;_x000D_
  _x000D_
      if (this.state.test == nextState.test)_x000D_
        return false;_x000D_
        _x000D_
      return true;_x000D_
  },_x000D_
_x000D_
    render: function() {_x000D_
        var currentTime = new Date().getTime();_x000D_
_x000D_
        return (_x000D_
            <div onClick={this.onTest}>_x000D_
            <p>Time in main:{currentTime}</p>_x000D_
            <p>Click me to update time</p>_x000D_
            <TimeInChild/>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(<Main/>, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
_x000D_
_x000D_
_x000D_

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

Horizontal swipe slider with jQuery and touch devices support?

You might be interested in the following:

I realize this is not a jQuery solution, but Sencha Touch framework is pretty good for building your target UI. Example (click the Carousel sidebar link): http://dev.sencha.com/deploy/touch/examples/kitchensink/

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

Regarding the problem with "Optimize code" property being UNCHECKED yet the code still compiling as optimized: What finally helped me after trying everything was checking the "Enable unmanaged code debugging" checkbox on the same settings page (Project properties - Debug). It doesn't directly relate to the code optimization, but with this enabled, VS no longer optimizes my library and I can debug.

Cannot serve WCF services in IIS on Windows 8

For Windows Server 2012, the solution is very similar to faester's (see above). From the Server Manager, click on Add roles and features, select the appropriate server, then select Features. Under .NET Framework 4.5 Features, you'll see WCF Services, and under that, you'll find HTTP Activation.

What does a circled plus mean?

It is XOR. Another name for the XOR function is addition without carry. I suppose that's how the symbol might make sense.

Google Chrome "window.open" workaround?

I believe currently there is no javascript way to force chrome to open as a new window in tab mode. A ticket has been submitted as in here Pop-ups to show as tab by default. But the user can click the chrome icon on the top left corner and select "Show as tab", the address bar then becomes editable.

A similar question asked in javascript open in a new window not tab.

What is this CSS selector? [class*="span"]

.show-grid [class*="span"]

It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.

Is it possible to forward-declare a function in Python?

Import the file itself. Assuming the file is called test.py:

import test

if __name__=='__main__':
    test.func()
else:
    def func():
        print('Func worked')

Getting value of select (dropdown) before change

 $("#dropdownId").on('focus', function () {
    var ddl = $(this);
    ddl.data('previous', ddl.val());
}).on('change', function () {
    var ddl = $(this);
    var previous = ddl.data('previous');
    ddl.data('previous', ddl.val());
});

Responsive font size in CSS

After many conclusions I ended up with this combination:

@media only screen and (max-width: 730px) {

    h2 {
        font-size: 4.3vw;
    }
}

What's the difference between using "let" and "var"?

I just came across one use case that I had to use var over let to introduce new variable. Here's a case:

I want to create a new variable with dynamic variable names.

let variableName = 'a';
eval("let " + variableName + '= 10;');
console.log(a);   // this doesn't work
var variableName = 'a';
eval("var " + variableName + '= 10;');
console.log(a);   // this works

The above code doesn't work because eval introduces a new block of code. The declaration using var will declare a variable outside of this block of code since var declares a variable in the function scope.

let, on the other hand, declares a variable in a block scope. So, a variable will only be visible in eval block.

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

How to use FormData for AJAX file upload?

Good morning.

I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.

<input type="file" name="files[]" multiple>

I did not make any modification on FormData.

How to print variables in Perl

How do I print out my $ids and $nIds?
print "$ids\n";
print "$nIds\n";
I tried simply print $ids, but Perl complains.

Complains about what? Uninitialised value? Perhaps your loop was never entered due to an error opening the file. Be sure to check if open returned an error, and make sure you are using use strict; use warnings;.

my ($ids, $nIds) is a list, right? With two elements?

It's a (very special) function call. $ids,$nIds is a list with two elements.

How do I declare a two dimensional array?

Just declare? You don't have to. Just make sure variable exists:

$d = array();

Arrays are resized dynamically, and attempt to write anything to non-exsistant element creates it (and creates entire array if needed)

$d[1][2] = 3;

This is valid for any number of dimensions without prior declarations.

rename the columns name after cbind the data

It's easy just add the name which you want to use in quotes before adding vector

a_matrix <- cbind(b_matrix,'Name-Change'= c_vector)

Can someone explain Microsoft Unity?

I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:

The screencast shows several common usages of the Unity IoC, such as:

  • Creating Types Not In Container
  • Registering and Resolving TypeMappings
  • Registering and Resolving Named TypeMappings
  • Singletons, LifetimeManagers, and the ContainerControlledLifetimeManager
  • Registering Existing Instances
  • Injecting Dependencies into Existing Instances
  • Populating the UnityContainer via App.config / Web.config
  • Specifying Dependencies via Injection API as opposed to Dependency Attributes
  • Using Nested ( Parent-Child ) Containers

Vbscript list all PDF files in folder and subfolders

There's a well documented answer to your question at this url:

http://blogs.technet.com/b/heyscriptingguy/archive/2005/02/18/how-can-i-list-the-files-in-a-folder-and-all-its-subfolders.aspx

The answer shown at that URL is kind of complicated and uses WMI (Windows Management Instrumentation) to iterate through files and folders. But if you do a lot of Windows administration, it's worth the effort to learn WMI.

I'm posting this now in case you need something right now; but I think I used to use a filesystemobject based approach, and I'll look for some example, and I'll post it later if I find it.

I hope this is helpful.

How do I pass command-line arguments to a WinForms application?

static void Main(string[] args)
{
  // For the sake of this example, we're just printing the arguments to the console.
  for (int i = 0; i < args.Length; i++) {
    Console.WriteLine("args[{0}] == {1}", i, args[i]);
  }
}

The arguments will then be stored in the args string array:

$ AppB.exe firstArg secondArg thirdArg
args[0] == firstArg
args[1] == secondArg
args[2] == thirdArg

Read connection string from web.config

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;  

C#

string constring = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constring))

BELOW WEB.CONFIG FILE CODE

<connectionStrings>
    <add name="ABCD" connectionString="Data Source=DESKTOP-SU3NKUU\MSSQLSERVER2016;Initial Catalog=TESTKISWRMIP;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

In the above Code ABCD is the Connection Name

Should I declare Jackson's ObjectMapper as a static field?

com.fasterxml.jackson.databind.type.TypeFactory._hashMapSuperInterfaceChain(HierarchicType)

com.fasterxml.jackson.databind.type.TypeFactory._findSuperInterfaceChain(Type, Class)
  com.fasterxml.jackson.databind.type.TypeFactory._findSuperTypeChain(Class, Class)
     com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(Class, Class, TypeBindings)
        com.fasterxml.jackson.databind.type.TypeFactory.findTypeParameters(JavaType, Class)
           com.fasterxml.jackson.databind.type.TypeFactory._fromParamType(ParameterizedType, TypeBindings)
              com.fasterxml.jackson.databind.type.TypeFactory._constructType(Type, TypeBindings)
                 com.fasterxml.jackson.databind.type.TypeFactory.constructType(TypeReference)
                    com.fasterxml.jackson.databind.ObjectMapper.convertValue(Object, TypeReference)

The method _hashMapSuperInterfaceChain in class com.fasterxml.jackson.databind.type.TypeFactory is synchronized. Am seeing contention on the same at high loads.

May be another reason to avoid a static ObjectMapper

How to parse JSON array in jQuery?

I know this is pretty long after your post, but wanted to post for others who might be experiencing this issue and stumble across this post as I did.

It seems there's something about jquery's $.each that changes the nature of the elements in the array.

I wanted to do the following:

$.getJSON('/ajax/get_messages.php', function(data) {

    /* data: 

    [{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
    {"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]

    */

    console.log ("Data0Title: " + data[0].title);
    // prints "Data0Title: Failure"

    console.log ("Data0Type: " + data[0].type);
    // prints "Data0Type: error"

    console.log ("Data0Details: " + data[0].details);
    // prints "Data0Details: Unsuccessful. Please try again"


    /* Loop through data array and print messages to console */

});

To accomplish the loop, I first tried using a jquery $.each to loop through the data array. However, as the OP notes, this doesn't work right:

$.each(data, function(nextMsg) {    
    console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
    // prints 
    // "undefined (undefined): undefined
    // "undefined (undefined): undefined
});

This didn't exactly make sense since I am able to access the data[0] elements when using a numeric key on the data array. So since using a numerical index worked, I tried (successfully) replacing the $.each block with a for loop:

var i=0;
for (i=0;i<data.length;i++){
    console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
    // prints
    // "Failure (error): Unsuccessful. Please try again"
    // "Information Message (info): A basic informational message - Please be aware"
}

So I don't know the underlying problem, a basic, old fashioned javascript for loop seems to be a functional alternative to jquery's $.each

How to show all of columns name on pandas dataframe?

To get all column name you can iterate over the data_all2.columns.

columns = data_all2.columns
for col in columns:
    print col

You will get all column names. Or you can store all column names to another list variable and then print list.

How to turn on WCF tracing?

The following configuration taken from MSDN can be applied to enable tracing on your WCF service.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
             <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
        <add name="xml"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="Error.svclog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".

If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:

Windows SDK Download

You don't have to install the entire thing, just the ".NET Development / Tools" part.

When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.

java.util.Date vs java.sql.Date

The only time to use java.sql.Date is in a PreparedStatement.setDate. Otherwise, use java.util.Date. It's telling that ResultSet.getDate returns a java.sql.Date but it can be assigned directly to a java.util.Date.

How do I remove the passphrase for the SSH key without having to create a new key?

Short answer:

$ ssh-keygen -p

This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).


If you would like to do it all on one line without prompts do:

$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

Important: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.

Notice though that you can still use -f keyfile without having to specify -P nor -N, and that the keyfile defaults to ~/.ssh/id_rsa, so in many cases, it's not even needed.

You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.

MySQL skip first 10 results

Use LIMIT with two parameters. For example, to return results 11-60 (where result 1 is the first row), use:

SELECT * FROM foo LIMIT 10, 50

For a solution to return all results, see Thomas' answer.

Replacing NULL and empty string within Select statement

An alternative way can be this: - recommended as using just one expression -

case when address.country <> '' then address.country
else 'United States'
end as country

Note: Result of checking null by <> operator will return false.
And as documented: NULLIF is equivalent to a searched CASE expression
and COALESCE expression is a syntactic shortcut for the CASE expression.
So, combination of those are using two time of case expression.

Selecting non-blank cells in Excel with VBA

The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.

Option Explicit

Public Sub exportDataToNewBook()
    Dim rowIndex As Integer
    Dim colIndex As Integer
    Dim dataRange As Range
    Dim thisBook As Workbook
    Dim newBook As Workbook
    Dim newRow As Integer
    Dim temp

    '// set your data range here
    Set dataRange = Sheet1.Range("A1:B100")

    '// create a new workbook
    Set newBook = Excel.Workbooks.Add

    '// loop through the data in book1, one column at a time
    For colIndex = 1 To dataRange.Columns.Count
        newRow = 0
        For rowIndex = 1 To dataRange.Rows.Count
            With dataRange.Cells(rowIndex, colIndex)

            '// ignore empty cells
            If .value <> "" Then
                newRow = newRow + 1
                temp = doSomethingWith(.value)
                newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
                End If

            End With
        Next rowIndex
    Next colIndex
End Sub


Private Function doSomethingWith(aValue)

    '// This is where you would compute a different value
    '// for use in the new workbook
    '// In this example, I simply add one to it.
    aValue = aValue + 1

    doSomethingWith = aValue
End Function

JQuery datepicker not working

try adjusting the order in which your script runs. Place the script tag below the element it is trying to affect. Or leave it up at the top and wrap it in a $(document).ready() EDIT: and include the right file.

How do I get the height and width of the Android Navigation Bar programmatically?

The NavigationBar height varies for some devices, but as well for some orientations. First you have to check if the device has a navbar, then if the device is a tablet or a not-tablet (phone) and finally you have to look at the orientation of the device in order to get the correct height.

public int getNavBarHeight(Context c) {
         int result = 0;
         boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();
         boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);

         if(!hasMenuKey && !hasBackKey) {
             //The device has a navigation bar
             Resources resources = c.getResources();

             int orientation = resources.getConfiguration().orientation;
             int resourceId;
             if (isTablet(c)){
                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");
             }  else {
                 resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_width", "dimen", "android");     
             }

             if (resourceId > 0) {
                 return resources.getDimensionPixelSize(resourceId);
             }
         }
         return result;
} 


private boolean isTablet(Context c) {
    return (c.getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK)
            >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

jQuery append() vs appendChild()

appendChild is a DOM vanilla-js function.

append is a jQuery function.

They each have their own quirks.

How to add (vertical) divider to a horizontal LinearLayout?

In order to get drawn, divider of LinearLayout must have some height while ColorDrawable (which is essentially #00ff00 as well as any other hardcoded color) doesn't have. Simple (and correct) way to solve this, is to wrap your color into some Drawable with predefined height, such as shape drawable

Change mysql user password using command line

In your code, try enclosing password inside single quote. Alternatively, as per the documentation of mysql, following should work -

SET PASSWORD FOR 'jeffrey'@'localhost' = PASSWORD('cleartext password');

FLUSH PRIVILEGES;

The last line is important or else your password change won't take effect unfortunately.

EDIT:

I ran a test in my local and it worked -

mysql>  set password for 'test' = PASSWORD('$w0rdf1sh');
Query OK, 0 rows affected (0.00 sec)

Mine is version 5. You can use following command to determine your version -

SHOW VARIABLES LIKE "%version%";

Encapsulation vs Abstraction?

in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

How to determine if a point is in a 2D triangle?

Honestly it is as simple as Simon P Steven's answer however with that approach you don't have a solid control on whether you want the points on the edges of the triangle to be included or not.

My approach is a little different but very basic. Consider the following triangle;

enter image description here

In order to have the point in the triangle we have to satisfy 3 conditions

  1. ACE angle (green) should be smaller than ACB angle (red)
  2. ECB angle (blue) should be smaller than ACB angle (red)
  3. Point E and Point C shoud have the same sign when their x and y values are applied to the equation of the |AB| line.

In this method you have full control to include or exclude the point on the edges individually. So you may check if a point is in the triangle including only the |AC| edge for instance.

So my solution in JavaScript would be as follows;

_x000D_
_x000D_
function isInTriangle(t,p){_x000D_
_x000D_
  function isInBorder(a,b,c,p){_x000D_
    var m = (a.y - b.y) / (a.x - b.x);                     // calculate the slope_x000D_
    return Math.sign(p.y - m*p.x + m*a.x - a.y) === Math.sign(c.y - m*c.x + m*a.x - a.y);_x000D_
  }_x000D_
  _x000D_
  function findAngle(a,b,c){                               // calculate the C angle from 3 points._x000D_
    var ca = Math.hypot(c.x-a.x, c.y-a.y),                 // ca edge length_x000D_
        cb = Math.hypot(c.x-b.x, c.y-b.y),                 // cb edge length_x000D_
        ab = Math.hypot(a.x-b.x, a.y-b.y);                 // ab edge length_x000D_
    return Math.acos((ca*ca + cb*cb - ab*ab) / (2*ca*cb)); // return the C angle_x000D_
  }_x000D_
_x000D_
  var pas = t.slice(1)_x000D_
             .map(tp => findAngle(p,tp,t[0])),             // find the angle between (p,t[0]) with (t[1],t[0]) & (t[2],t[0])_x000D_
       ta = findAngle(t[1],t[2],t[0]);_x000D_
  return pas[0] < ta && pas[1] < ta && isInBorder(t[1],t[2],t[0],p);_x000D_
}_x000D_
_x000D_
var triangle = [{x:3, y:4},{x:10, y:8},{x:6, y:10}],_x000D_
      point1 = {x:3, y:9},_x000D_
      point2 = {x:7, y:9};_x000D_
_x000D_
console.log(isInTriangle(triangle,point1));_x000D_
console.log(isInTriangle(triangle,point2));
_x000D_
_x000D_
_x000D_

Can you use @Autowired with static fields?

Generally, setting static field by object instance is a bad practice.

to avoid optional issues you can add synchronized definition, and set it only if private static Logger logger;

@Autowired
public synchronized void setLogger(Logger logger)
{
    if (MyClass.logger == null)
    {
        MyClass.logger = logger;
    }
}

:

Netbeans installation doesn't find JDK

I also had the same problem. So I tried by installing a lesser version say jdk1.5 and running the netbeans installation from command prompt as: Linux: netbeans-5_5-linux.bin -is:javahome /usr/jdk/jdk1.5.0_06 Windows: netbeans-5_5-windows.exe -is:javahome "C:\Program Files\Java\jdk1.5.0_06"

Hope it helps

UICollectionView - dynamic cell height?

It worked for me, hope you too.

*Note: I have used auto layout in Nib, remember add top and bottom contraints for subviews in contentView

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
           let cell = YourCollectionViewCell.instantiateFromNib()
           cell.frame.size.width = collectionView.frame.width
           cell.data = viewModel.data[indexPath.item]
           let resizing = cell.systemLayoutSizeFitting(UILayoutFittingCompressedSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
           return resizing
    }

no match for ‘operator<<’ in ‘std::operator

Object is a collection of methods and variables.You can't print the variables in object by just cout operation . if you want to show the things inside the object you have to declare either a getter or a display text method in class.

ex

#include <iostream>

using namespace std;

class mystruct

{
private:
    int m_a;
    float m_b;

public:
    mystruct(int x, float y)
    {
            m_a = x;
            m_b = y;
    }
    public:
    void getm_aAndm_b()
    {
        cout<<m_a<<endl;
        cout<<m_b<<endl;
    }



};

int main()
{

    mystruct m = mystruct(5,3.14);

    cout << "my structure " << endl;
    m.getm_aAndm_b();
    return 0;

}

Not that this is just a one way of doing it

Can I open a dropdownlist using jQuery

As has been stated, you can't programmatically open a <select> using JavaScript.

However, you could write your own <select> managing the entire look and feel yourself. Something like what you see for the autocomplete search terms on Google or Yahoo! or the Search for Location box at The Weather Network.

I found one for jQuery here. I have no idea whether it would meet your needs, but even if it doesn't completely meet your needs, it should be possible to modify it so it would open as the result of some other action or event. This one actually looks more promising.

How to merge 2 List<T> and removing duplicate values from it in C#

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();

// ulist output : 1, 12, 5, 7, 9

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

mysqli_select_db() should have 2 parameters, the connection link and the database name -

mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));

Using mysqli_error in the die statement will tell you exactly what is wrong as opposed to a generic error message.

Angular 2 Scroll to top on Route Change

Angular 6.1 and later:

Angular 6.1 (released on 2018-07-25) added built-in support to handle this issue, through a feature called "Router Scroll Position Restoration". As described in the official Angular blog, you just need to enable this in the router configuration like this:

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})

Furthermore, the blog states "It is expected that this will become the default in a future major release". So far this hasn't happened (as of Angular 11.0), but eventually you won't need to do anything at all in your code, and this will just work correctly out of the box.

You can see more details about this feature and how to customize this behavior in the official docs.

Angular 6.0 and earlier:

While @GuilhermeMeireles's excellent answer fixes the original problem, it introduces a new one, by breaking the normal behavior you expect when you navigate back or forward (with browser buttons or via Location in code). The expected behavior is that when you navigate back to the page, it should remain scrolled down to the same location it was when you clicked on the link, but scrolling to the top when arriving at every page obviously breaks this expectation.

The code below expands the logic to detect this kind of navigation by subscribing to Location's PopStateEvent sequence and skipping the scroll-to-top logic if the newly arrived-at page is a result of such an event.

If the page you navigate back from is long enough to cover the whole viewport, the scroll position is restored automatically, but as @JordanNelson correctly pointed out, if the page is shorter you need to keep track of the original y scroll position and restored it explicitly when you go back to the page. The updated version of the code covers this case too, by always explicitly restoring the scroll position.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {

    private lastPoppedUrl: string;
    private yScrollStack: number[] = [];

    constructor(private router: Router, private location: Location) { }

    ngOnInit() {
        this.location.subscribe((ev:PopStateEvent) => {
            this.lastPoppedUrl = ev.url;
        });
        this.router.events.subscribe((ev:any) => {
            if (ev instanceof NavigationStart) {
                if (ev.url != this.lastPoppedUrl)
                    this.yScrollStack.push(window.scrollY);
            } else if (ev instanceof NavigationEnd) {
                if (ev.url == this.lastPoppedUrl) {
                    this.lastPoppedUrl = undefined;
                    window.scrollTo(0, this.yScrollStack.pop());
                } else
                    window.scrollTo(0, 0);
            }
        });
    }
}

Drop shadow on a div container?

This works for me on all my browsers:

.shadow {
-moz-box-shadow: 0 0 30px 5px #999;
-webkit-box-shadow: 0 0 30px 5px #999;
}

then just give any div the shadow class, no jQuery required.

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

How to write a PHP ternary operator

PHP 8 (Left-associative ternary operator change)

Left-associative ternary operator deprecation https://wiki.php.net/rfc/ternary_associativity. The ternary operator has some weird quirks in PHP. This RFC adds a deprecation warning for nested ternary statements. In PHP 8, this deprecation will be converted to a compile time error.

1 ? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok

source: https://stitcher.io/blog/new-in-php-74#numeric-literal-separator-rfc

What do Clustered and Non clustered index actually mean?

A very simple, non-technical rule-of-thumb would be that clustered indexes are usually used for your primary key (or, at least, a unique column) and that non-clustered are used for other situations (maybe a foreign key). Indeed, SQL Server will by default create a clustered index on your primary key column(s). As you will have learnt, the clustered index relates to the way data is physically sorted on disk, which means it's a good all-round choice for most situations.

How to get Spinner selected item value to string?

try this

 final Spinner cardStatusSpinner1 = (Spinner) findViewById(R.id.text_interested);
    String cardStatusString;
    cardStatusSpinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent,
                View view, int pos, long id) {
            cardStatusString = parent.getItemAtPosition(pos).toString();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

 final Button saveBtn = (Button) findViewById(R.id.save_button);
    saveBtn .setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            System.out.println("Selected cardStatusString : " + cardStatusString ); //this will print the result
        }
    });

Chrome not rendering SVG referenced via <img> tag

I came here because I had a similar problem, the image was not being rendered. What I found out was that the content type header of my testing server wasn't correct. I fixed it by adding the following to my .htaccess file:

AddType image/svg+xml svg svgz
AddEncoding gzip svgz

Check if URL has certain string with PHP

Starting with PHP 8 (2020-11-24), you can use str_contains:

if (str_contains('www.domain.com/car/', 'car')) {
   echo 'car is exist';
} else {
   echo 'no cars';
}

Download JSON object as a file from browser

Found an answer.

var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

$('<a href="data:' + data + '" download="data.json">download JSON</a>').appendTo('#container');

seems to work fine for me.

** All credit goes to @cowboy-ben-alman, who is the author of the code above **

how to split the ng-repeat data with three columns using bootstrap

The most reliable and technically correct approach is to transform the data in the controller. Here's a simple chunk function and usage.

function chunk(arr, size) {
  var newArr = [];
  for (var i=0; i<arr.length; i+=size) {
    newArr.push(arr.slice(i, i+size));
  }
  return newArr;
}

$scope.chunkedData = chunk(myData, 3);

Then your view would look like this:

<div class="row" ng-repeat="rows in chunkedData">
  <div class="span4" ng-repeat="item in rows">{{item}}</div>
</div>

If you have any inputs within the ng-repeat, you will probably want to unchunk/rejoin the arrays as the data is modified or on submission. Here's how this would look in a $watch, so that the data is always available in the original, merged format:

$scope.$watch('chunkedData', function(val) {
  $scope.data = [].concat.apply([], val);
}, true); // deep watch

Many people prefer to accomplish this in the view with a filter. This is possible, but should only be used for display purposes! If you add inputs within this filtered view, it will cause problems that can be solved, but are not pretty or reliable.

The problem with this filter is that it returns new nested arrays each time. Angular is watching the return value from the filter. The first time the filter runs, Angular knows the value, then runs it again to ensure it is done changing. If both values are the same, the cycle is ended. If not, the filter will fire again and again until they are the same, or Angular realizes an infinite digest loop is occurring and shuts down. Because new nested arrays/objects were not previously tracked by Angular, it always sees the return value as different from the previous. To fix these "unstable" filters, you must wrap the filter in a memoize function. lodash has a memoize function and the latest version of lodash also includes a chunk function, so we can create this filter very simply using npm modules and compiling the script with browserify or webpack.

Remember: display only! Filter in the controller if you're using inputs!

Install lodash:

npm install lodash-node

Create the filter:

var chunk = require('lodash-node/modern/array/chunk');
var memoize = require('lodash-node/modern/function/memoize');

angular.module('myModule', [])
.filter('chunk', function() {
  return memoize(chunk);
});

And here's a sample with this filter:

<div ng-repeat="row in ['a','b','c','d','e','f'] | chunk:3">
  <div class="column" ng-repeat="item in row">
    {{($parent.$index*row.length)+$index+1}}. {{item}}
  </div>
</div>

Order items vertically

1  4
2  5
3  6

Regarding vertical columns (list top to bottom) rather than horizontal (left to right), the exact implementation depends on the desired semantics. Lists that divide up unevenly can be distributed different ways. Here's one way:

<div ng-repeat="row in columns">
  <div class="column" ng-repeat="item in row">
    {{item}}
  </div>
</div>
var data = ['a','b','c','d','e','f','g'];
$scope.columns = columnize(data, 3);
function columnize(input, cols) {
  var arr = [];
  for(i = 0; i < input.length; i++) {
    var colIdx = i % cols;
    arr[colIdx] = arr[colIdx] || [];
    arr[colIdx].push(input[i]);
  }
  return arr;
}

However, the most direct and just plainly simple way to get columns is to use CSS columns:

.columns {
  columns: 3;
}
<div class="columns">
  <div ng-repeat="item in ['a','b','c','d','e','f','g']">
    {{item}}
  </div>
</div>

Find text string using jQuery?

If you just want the node closest to the text you're searching for, you could use this:

$('*:contains("my text"):last');

This will even work if your HTML looks like this:

<p> blah blah <strong>my <em>text</em></strong></p>

Using the above selector will find the <strong> tag, since that's the last tag which contains that entire string.

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

Just adding my suggestion for a resolution, I had a copy of a VM server for developing and testing, I created the database on that with 'sa' having ownership on the db.

I then restored the database onto the live VM server but I was getting the same error mentioned even though the data was still returning correctly. I looked up the 'sa' user mappings and could see it wasn't mapped to the database when I tried to apply the mapping I got a another error "Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405". so I ran this instead

ALTER AUTHORIZATION ON DATABASE::dbname TO sa

I rechecked the user mappings and it was now assigned to my db and it fixed a lot of access issues for me.

Spring Boot JPA - configuring auto reconnect

whoami's answer is the correct one. Using the properties as suggested I was unable to get this to work (using Spring Boot 1.5.3.RELEASE)

I'm adding my answer since it's a complete configuration class so it might help someone using Spring Boot:

@Configuration
@Log4j
public class SwatDataBaseConfig {

    @Value("${swat.decrypt.location}")
    private String fileLocation;

    @Value("${swat.datasource.url}")
    private String dbURL;

    @Value("${swat.datasource.driver-class-name}")
    private String driverName;

    @Value("${swat.datasource.username}")
    private String userName;

    @Value("${swat.datasource.password}")
    private String hashedPassword;

    @Bean
    public DataSource primaryDataSource() {
        PoolProperties poolProperties = new PoolProperties();
        poolProperties.setUrl(dbURL);
        poolProperties.setUsername(userName);
        poolProperties.setPassword(password);
        poolProperties.setDriverClassName(driverName);
        poolProperties.setTestOnBorrow(true);
        poolProperties.setValidationQuery("SELECT 1");
        poolProperties.setValidationInterval(0);
        DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
        return ds;
    }
}

Generate random integers between 0 and 9

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

Question mark and colon in statement. What does it mean?

string requestUri = _apiURL + "?e=" + OperationURL[0] + ((OperationURL[1] == "GET") ? GetRequestSignature() : "");

can be translated to:

string requestUri="";
if ((OperationURL[1] == "GET")
{
    requestUri = _apiURL + "?e=" + GetRequestSignature();
}
else
{
   requestUri = _apiURL + "?e=";
}

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think you are after this:

CONVERT(datetime, date_as_string, 103)

Notice, that datetime hasn't any format. You think about its presentation. To get the data of datetime in an appropriate format you can use

CONVERT(varchar, date_as_datetime, 103)

C++ Vector of pointers

It means something like this:

std::vector<Movie *> movies;

Then you add to the vector as you read lines:

movies.push_back(new Movie(...));

Remember to delete all of the Movie* objects once you are done with the vector.

pandas loc vs. iloc vs. at vs. iat?

df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])

df

                        A   B
                100     a   54
                200     b   67
                300     c   89
In [19]:    
df.loc[100]

Out[19]:
A     a
B    54
Name: 100, dtype: object

In [20]:    
df.iloc[0]

Out[20]:
A     a
B    54
Name: 100, dtype: object

In [24]:    
df2 = df.set_index([df.index,'A'])
df2

Out[24]:
        B
    A   
100 a   54
200 b   67
300 c   89

In [25]:    
df2.ix[100, 'a']

Out[25]:    
B    54
Name: (100, a), dtype: int64

Execute a SQL Stored Procedure and process the results

From MSDN

To execute a stored procedure returning rows programmatically using a command object

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.
' Use Read method (true/false) to see if reader has records and advance to next record
' You can use a While loop for multiple records (While reader.Read() ... End While)
If reader.Read() Then
  someVar = reader(0)
  someVar2 = reader(1)
  someVar3 = reader("NamedField")
End If    

sqlConnection1.Close()

Adding new files to a subversion repository

  • Checkout a working copy of the repository (or at least the subdirectory that you want to add the files to): svn checkout https://example.org/path/to/repo/bleh
  • Copy the files over there.
  • svn add file1 file2...
  • svn commit

I am not aware of a quicker option.

Note: if you are on the same machine as your Subversion repository, the URL can use the file: specifier with a path in place of https: in the svn checkout command. For example svn checkout file:///path/to/repo/bleh.

PS. as pointed out in the comments and other answers, you can use something like svn import . <URL> if you want to recursively import everything in the current directory. With this option, however, you can't skip over some of the files; it's all or nothing.

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

Copy/duplicate database without using mysqldump

I don't really know what you mean by "local access". But for that solution you need to be able to access over ssh the server to copy the files where is database is stored.

I cannot use mysqldump, because my database is big (7Go, mysqldump fail) If the version of the 2 mysql database is too different it might not work, you can check your mysql version using mysql -V.

1) Copy the data from your remote server to your local computer (vps is the alias to your remote server, can be replaced by [email protected])

ssh vps:/etc/init.d/mysql stop
scp -rC vps:/var/lib/mysql/ /tmp/var_lib_mysql
ssh vps:/etc/init.d/apache2 start

2) Import the data copied on your local computer

/etc/init.d/mysql stop
sudo chown -R mysql:mysql /tmp/var_lib_mysql
sudo nano /etc/mysql/my.cnf
-> [mysqld]
-> datadir=/tmp/var_lib_mysql
/etc/init.d/mysql start

If you have a different version, you may need to run

/etc/init.d/mysql stop
mysql_upgrade -u root -pPASSWORD --force #that step took almost 1hrs
/etc/init.d/mysql start

Eclipse error ... cannot be resolved to a type

To solve the error "...cannot be resolved to a type.." do the followings:

  1. Right click on the class and select "Build Path-->Exclude"
  2. Again right click on the class and select "Build Path-->Include"

It works for me.

Generate Row Serial Numbers in SQL Query

I'm not certain, based on your question if you want numbered rows that will remember their numbers even if the underlying data changes (and gives a different ordering), but if you just want numbered rows - that reset on a change in customer ID, then try using the Partition by clause of row_number()

row_number() over(partition by CustomerID order by CustomerID)

How to generate xsd from wsdl

(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :

Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.

This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).

How do I write output in same place on the console?

For Python 3xx:

import time
for i in range(10):
    time.sleep(0.2) 
    print ("\r Loading... {}".format(i)+str(i), end="")

jQuery .val() vs .attr("value")

Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:

var currentValue = $obj.prop("value");

However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.

Pinging an IP address using PHP and echoing the result

This also did not work for me in Wordpress. I also tried -t and -n and other ways, but did not work. I used,

function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c2 -w2 $ip", $outcome, $status);  
    if ($status==0) {
    $status = "alive";
    } else {
    $status = "dead";
    }
    $message .= '<div id="dialog-block-left">';
    $message .= '<div id="ip-status">The IP address, '.$ip.', is  '.$status.'</div><div style="clear:both"></div>';    
    return $message;
}
// Some IP Address
pingAddress("192.168.1.1"); 

This worked perfectly for me, finally. I referred this from http://www.phpscriptsdaily.com/php/php-ping/ Hope this will help

Well I want to modify this as it is working fine on my localhost but not on my live server For live server, I got another thing which now works for both local as well as live.

$fp = fSockOpen($ip,80,$errno,$errstr,1);
if($fp) { $status=0; fclose($fp); } else { $status=1; }

Then I show the Server is up for 0 and down for 1.

This works perfectly for me. I got this from Ping site and return result in PHP Thanks @karim79

Remove leading comma from a string

var s = ",'first string','more','even more'";

var array = s.split(',').slice(1);

That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.

Using BigDecimal to work with currencies

Primitive numeric types are useful for storing single values in memory. But when dealing with calculation using double and float types, there is a problems with the rounding.It happens because memory representation doesn't map exactly to the value. For example, a double value is supposed to take 64 bits but Java doesn't use all 64 bits.It only stores what it thinks the important parts of the number. So you can arrive to the wrong values when you adding values together of the float or double type.

Please see a short clip https://youtu.be/EXxUSz9x7BM

How to redirect to action from JavaScript method?

I wish that I could just comment on yojimbo87's answer to post this, but I don't have enough reputation to comment yet. It was pointed out that this relative path only works from the root:

        window.location.href = "/{controller}/{action}/{params}";

Just wanted to confirm that you can use @Url.Content to provide the absolute path:

function DeleteJob() {
    if (confirm("Do you really want to delete selected job/s?"))
        window.location.href = '@Url.Content("~/{controller}/{action}/{params}")';
    else
        return false;
}

What is the simplest and most robust way to get the user's current location on Android?

EDIT: Updated with the latest Location Service API from Google Play Services library (July 2014)

I would recommend you to use the new Location Service API, available from the Google Play Services library, which provides a more powerful, high-level framework that automates tasks such as location provider choice and power management. According to the official documentation: "... Location API make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology. They also let you minimize power consumption by using all of the capabilities of the device hardware."

For further information visit: Making Your App Location-Aware

To see a full example using the latest Location Service API visit: Android LocationClient class is deprecated but used in documentation

Elegant way to check for missing packages and install them?

 48 lapply_install_and_load <- function (package1, ...)
 49 {
 50     #
 51     # convert arguments to vector
 52     #
 53     packages <- c(package1, ...)
 54     #
 55     # check if loaded and installed
 56     #
 57     loaded        <- packages %in% (.packages())
 58     names(loaded) <- packages
 59     #
 60     installed        <- packages %in% rownames(installed.packages())
 61     names(installed) <- packages
 62     #
 63     # start loop to determine if each package is installed
 64     #
 65     load_it <- function (p, loaded, installed)
 66     {
 67         if (loaded[p])
 68         {
 69             print(paste(p, "loaded"))
 70         }
 71         else
 72         {
 73             print(paste(p, "not loaded"))
 74             if (installed[p])
 75             {
 76                 print(paste(p, "installed"))
 77                 do.call("library", list(p))
 78             }
 79             else
 80             {
 81                 print(paste(p, "not installed"))
 82                 install.packages(p)
 83                 do.call("library", list(p))
 84             }
 85         }
 86     }
 87     #
 88     lapply(packages, load_it, loaded, installed)
 89 }

MySQL: ALTER TABLE if column not exists

SET @dbname = DATABASE();
SET @tablename = "table";
SET @columnname = "fieldname";
SET @preparedStatement = (SELECT IF(
  (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE
      (table_name = @tablename)
      AND (table_schema = @dbname)
      AND (column_name = @columnname)
  ) > 0,
  "SELECT 1",
  CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " DECIMAL(18,4) NULL;")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists; 

Fragment Inside Fragment

I solved this problem. You can use Support library and ViewPager. If you don't need swiping by gesture you can disable swiping. So here is some code to improve my solution:

public class TestFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.frag, container, false);
    final ArrayList<Fragment> list = new ArrayList<Fragment>();

    list.add(new TrFrag());
    list.add(new TrFrag());
    list.add(new TrFrag());

    ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
    pager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
        @Override
        public Fragment getItem(int i) {
            return list.get(i);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    });
    return v;
}
}

P.S.It is ugly code for test, but it improves that it is possible.

P.P.S Inside fragment ChildFragmentManager should be passed to ViewPagerAdapter

How to get the MD5 hash of a file in C++?

Using Crypto++, you could do the following:

#include <sha.h>
#include <iostream> 

SHA256 sha; 
while ( !f.eof() ) { 
   char buff[4096];
   int numchars = f.read(...); 
   sha.Update(buff, numchars); 
}
char hash[size]; 
sha.Final(hash); 
cout << hash <<endl; 

I have a need for something very similar, because I can't read in multi-gigabyte files just to compute a hash. In theory I could memory map them, but I have to support 32bit platforms - that's still problematic for large files.

How to insert a picture into Excel at a specified cell position with VBA

Try this:

With xlApp.ActiveSheet.Pictures.Insert(PicPath)
    With .ShapeRange
        .LockAspectRatio = msoTrue
        .Width = 75
        .Height = 100
    End With
    .Left = xlApp.ActiveSheet.Cells(i, 20).Left
    .Top = xlApp.ActiveSheet.Cells(i, 20).Top
    .Placement = 1
    .PrintObject = True
End With

It's better not to .select anything in Excel, it is usually never necessary and slows down your code.

library not found for -lPods

In this issue,If you have already installed & update pod in your system then your Xcode not being able to find the Pods library.To resolve this issue, please check for following causes that may take place:

  1. You are using the workspace.
  2. The Pods library builds.
  3. The Pods library is referenced in the products group of your project.
  4. Your target includes the Pods library in the link with frameworks build phase.

php: loop through json array

First you have to decode your json :

$array = json_decode($the_json_code);

Then after the json decoded you have to do the foreach

foreach ($array as $key => $jsons) { // This will search in the 2 jsons
     foreach($jsons as $key => $value) {
         echo $value; // This will show jsut the value f each key like "var1" will print 9
                       // And then goes print 16,16,8 ...
    }
}

If you want something specific just ask for a key like this. Put this between the last foreach.

if($key == 'var1'){
 echo $value;
}

Apache: Restrict access to specific source IP inside virtual host

For Apache 2.4, you would use the Require IP directive. So to only allow machines from the 192.168.0.0/24 network (range 192.168.0.0 - 192.168.0.255)

<VirtualHost *:80>
    <Location />
      Require ip 192.168.0.0/24
    </Location>
    ...
</VirtualHost>

And if you just want the localhost machine to have access, then there's a special Require local directive.

The local provider allows access to the server if any of the following conditions is true:

  • the client address matches 127.0.0.0/8
  • the client address is ::1
  • both the client and the server address of the connection are the same

This allows a convenient way to match connections that originate from the local host:

<VirtualHost *:80>
    <Location />
      Require local
    </Location>
    ...
</VirtualHost>

How to represent empty char in Java Character class

Use the \b operator (the backspace escape operator) in the second parameter

String test= "Anna Banana";

System.out.println(test); //returns Anna Banana<br><br>
System.out.println(test.replaceAll(" ","\b")); //returns AnnaBanana removing all the spaces in the string

Disable HttpClient logging

I was also having the same problem. The entire console was filled with [main] DEBUG org.apache.http.wire while running the tests.

The solution which worked for me was creating a logback-test.xml src/test/resources/logback-test.xml as in https://github.com/bonigarcia/webdrivermanager-examples/blob/master/src/test/resources/logback-test.xml (ref - https://github.com/bonigarcia/webdrivermanager/issues/203)

To view my logging infos, I replaced logger name="io.github.bonigarcia" with my package name

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.mypackage" level="DEBUG" />
    <logger name="org" level="INFO" />
    <logger name="com" level="INFO" />

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

Best Practice: Software Versioning

I basically follow this pattern:

  • start from 0.1.0

  • when it's ready I branch the code in the source repo, tag 0.1.0 and create the 0.1.0 branch, the head/trunk becomes 0.2.0-snapshot or something similar

  • I add new features only to the trunk, but backport fixes to the branch and in time I release from it 0.1.1, 0.1.2, ...

  • I declare version 1.0.0 when the product is considered feature complete and doesn't have major shortcomings

  • from then on - everyone can decide when to increment the major version...

Link to download apache http server for 64bit windows.

you can find multiple options listed at http://httpd.apache.org/docs/current/platform/windows.html#down

ApacheHaus Apache Lounge BitNami WAMP Stack WampServer XAMPP

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

There was a relevant answer from Ask Tom published in April 2016.

If you have sufficient server power, you can do

select /*+ parallel */ count(*) from sometable

If you are just after an approximation, you can do :

select 5 * count(*) from sometable sample block (10);

Also, if there is

  1. a column that contains no nulls, but is not defined as NOT NULL, and
  2. there is an index on that column

you could try:

select /*+ index_ffs(t) */ count(*) from sometable  t where indexed_col is not null

How to mark a method as obsolete or deprecated?

Add an annotation to the method using the keyword Obsolete. Message argument is optional but a good idea to communicate why the item is now obsolete and/or what to use instead.
Example:

[System.Obsolete("use myMethodB instead")]
void myMethodA()

Manage toolbar's navigation and back button from fragment in android

(Kotlin) In the activity hosting the fragment(s):

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            onBackPressed()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

I have found that when I add fragments to a project, they show the action bar home button by default, to remove/disable it put this in onViewCreated() (use true to enable it if it is not showing):

val actionBar = this.requireActivity().actionBar
    actionBar?.setDisplayHomeAsUpEnabled(false)

How to create loading dialogs in Android?

Today things have changed a little.

Now we avoid use ProgressDialog to show spinning progress:

enter image description here

If you want to put in your app a spinning progress you should use an Activity indicators:

http://developer.android.com/design/building-blocks/progress.html#activity

Check string length in PHP

Because $xml->xpath always return an array, and strlen expects a string.

Remove an onclick listener

Note that if a view is non-clickable (a TextView for example), setting setOnClickListener(null) will mean the view is clickable. Use mMyView.setClickable(false) if you don't want your view to be clickable. For example, if you use a xml drawable for the background, which shows different colours for different states, if your view is still clickable, users can click on it and the different background colour will show, which may look weird.

Stop fixed position at footer

This worked for me -

HTML -

<div id="sideNote" class="col-sm-3" style="float:right;">

</div> 
<div class="footer-wrap">
        <div id="footer-div">
        </div>      
</div>

CSS -

#sideNote{right:0; margin-top:10px; position:fixed; bottom:0; margin-bottom:5px;}

#footer-div{margin:0 auto; text-align:center; min-height:300px; margin-top:100px; padding:100px 50px;}

JQuery -

function isVisible(elment) {
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elment).offset().top;

    return y <= (vpH + st);
}

function setSideNotePos(){
    $(window).scroll(function() {
        if (isVisible($('.footer-wrap'))) {
            $('#sideNote').css('position','absolute');
            $('#sideNote').css('top',$('.footer-wrap').offset().top - $('#sideNote').outerHeight() - 100);
        } else {
            $('#sideNote').css('position','fixed');
            $('#sideNote').css('top','auto');
        }
    });
}

Now call this function like this -

$(document).ready(function() {
    setSideNotePos();
});

PS - The Jquery functions are copied from an answer to another similar question on stackoverflow, but it wasn't working for me fully. So I modified it to these functions, as they are shown here. I think the position etc attributes to your divs will depend on how the divs are structured, who their parents and siblings are.

The above function works when both sideNote and footer-wraps are direct siblings.

How can I get the domain name of my site within a Django template?

You can use {{ protocol }}://{{ domain }} in your templates to get your domain name.

capture div into image using html2canvas

You should try this (test, works at least in Firefox):

html2canvas(document.body,{
   onrendered:function(canvas){
      document.body.appendChild(canvas);
   }
});

Im running these lines of code to get the full browser screen (only the visible screen, not the hole site):

var w=window, d=document, e=d.documentElement, g=d.getElementsByTagName('body')[0];
var y=w.innerHeight||e.clientHeight||g.clientHeight;

html2canvas(document.body,{
   height:y,
   onrendered:function(canvas){
      var img = canvas.toDataURL();
   }
});

More explanations & options here: http://html2canvas.hertzen.com/#/documentation.html

Exception.Message vs Exception.ToString()

In addition to what's already been said, don't use ToString() on the exception object for displaying to the user. Just the Message property should suffice, or a higher level custom message.

In terms of logging purposes, definitely use ToString() on the Exception, not just the Message property, as in most scenarios, you will be left scratching your head where specifically this exception occurred, and what the call stack was. The stacktrace would have told you all that.

fetch from origin with deleted remote branches?

Regarding git fetch -p, its behavior changed in Git 1.9, and only Git 2.9.x/2.10 reflects that.

See commit 9e70233 (13 Jun 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 1c22105, 06 Jul 2016)

fetch: document that pruning happens before fetching

This was changed in 10a6cc8 (fetch --prune: Run prune before fetching, 2014-01-02), but it seems that nobody in that discussion realized we were advertising the "after" explicitly.

So the documentation now states:

Before fetching, remove any remote-tracking references that no longer exist on the remote

That is because:

When we have a remote-tracking branch named "frotz/nitfol" from a previous fetch, and the upstream now has a branch named "frotz", fetch would fail to remove "frotz/nitfol" with a "git fetch --prune" from the upstream. git would inform the user to use "git remote prune" to fix the problem.

Change the way "fetch --prune" works by moving the pruning operation before the fetching operation. This way, instead of warning the user of a conflict, it automatically fixes it.

Set focus to field in dynamically loaded DIV

The load() function is an asynchronous function. You should set the focus after the load() call finishes, that is in the callback function of load(), because otherwise the element you are referring to by #header, does not yet exist. For example:

$("#display").load("?control=msgs", {}, function() { 
  $('#header').focus();
}); 

I had issues myself even with this solution, so i did a setTimeout in the callback and set the focus in the timeout to make /really/ sure the element exists.

0xC0000005: Access violation reading location 0x00000000

"Access violation reading location 0x00000000" means that you're derefrencing a pointer that hasn't been initialized and therefore has garbage values. Those garbage values could be anything, but usually it happens to be 0 and so you try to read from the memory address 0x0, which the operating system detects and prevents you from doing.

Check and make sure that the array invaders[] is what you think it should be.

Also, you don't seem to be updating i ever - meaning that you keep placing the same Invader object into location 0 of invaders[] at every loop iteration.

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1

E.g.:

   GET /resource HTTP/1.1
   Host: server.example.com
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

How to open the Google Play Store directly from my Android application?

Here is the final code from the answers above that first attempts to open the app using the Google play store app and specifically play store, if it fails, it will start the action view using the web version: Credits to @Eric, @Jonathan Caballero

public void goToPlayStore() {
        String playStoreMarketUrl = "market://details?id=";
        String playStoreWebUrl = "https://play.google.com/store/apps/details?id=";
        String packageName = getActivity().getPackageName();
        try {
            Intent intent =  getActivity()
                            .getPackageManager()
                            .getLaunchIntentForPackage("com.android.vending");
            if (intent != null) {
                ComponentName androidComponent = new ComponentName("com.android.vending",
                        "com.google.android.finsky.activities.LaunchUrlHandlerActivity");
                intent.setComponent(androidComponent);
                intent.setData(Uri.parse(playStoreMarketUrl + packageName));
            } else {
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(playStoreMarketUrl + packageName));
            }
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(playStoreWebUrl + packageName));
            startActivity(intent);
        }
    }

Play sound on button click android

Instead of resetting it as proposed by DeathRs:

if (mp.isPlaying()) {
       mp.stop();
       mp.release();
       mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();

we can just reset the MediaPlayer to it's begin using:

if (mp.isPlaying()) {
       mp.seekTo(0)
}

Download a file from HTTPS using download.file()

Offering the curl package as an alternative that I found to be reliable when extracting large files from an online database. In a recent project, I had to download 120 files from an online database and found it to half the transfer times and to be much more reliable than download.file.

#install.packages("curl")
library(curl)
#install.packages("RCurl")
library(RCurl)

ptm <- proc.time()
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- getURL(URL)
proc.time() - ptm
ptm

ptm1 <- proc.time()
curl_download(url =URL ,destfile="TEST.CSV",quiet=FALSE, mode="wb")
proc.time() - ptm1
ptm1

ptm2 <- proc.time()
y = download.file(URL, destfile = "./data/data.csv", method="curl")
proc.time() - ptm2
ptm2

In this case, rough timing on your URL showed no consistent difference in transfer times. In my application, using curl_download in a script to select and download 120 files from a website decreased my transfer times from 2000 seconds per file to 1000 seconds and increased the reliability from 50% to 2 failures in 120 files. The script is posted in my answer to a question I asked earlier, see .

How do you install Boost on MacOS?

Fink appears to have a full set of Boost packages...

With fink installed and running just do

fink install boost1.35.nopython

at the terminal and accept the dependencies it insists on. Or use

fink list boost

to get a list of different packages that are availible.

Server.Transfer Vs. Response.Redirect

Server.Transfer doesn't change the URL in the client browser, so effectively the browser does not know you changed to another server-side handler. Response.Redirect tells the browser to move to a different page, so the url in the titlebar changes.

Server.Transfer is slightly faster since it avoids one roundtrip to the server, but the non-change of url may be either good or bad for you, depending on what you're trying to do.

Error when creating a new text file with python?

You can use open(name, 'a')

However, when you enter filename, use inverted commas on both sides, otherwise ".txt"cannot be added to filename

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

How to wait for a JavaScript Promise to resolve before resuming function?

If using ES2016 you can use async and await and do something like:

(async () => {
  const data = await fetch(url)
  myFunc(data)
}())

If using ES2015 you can use Generators. If you don't like the syntax you can abstract it away using an async utility function as explained here.

If using ES5 you'll probably want a library like Bluebird to give you more control.

Finally, if your runtime supports ES2015 already execution order may be preserved with parallelism using Fetch Injection.

How to show PIL images on the screen?

I tested this and it works fine for me:

from PIL import Image
im = Image.open('image.jpg')
im.show()

JSONResult to String

json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";            
return new MemoryStream(Encoding.UTF8.GetBytes(json));

How to get exact browser name and version?

Got an awesome function here.

<?php
function getBrowser() { 
  $u_agent = $_SERVER['HTTP_USER_AGENT'];
  $bname = 'Unknown';
  $platform = 'Unknown';
  $version= "";

  //First get the platform?
  if (preg_match('/linux/i', $u_agent)) {
    $platform = 'linux';
  }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
    $platform = 'mac';
  }elseif (preg_match('/windows|win32/i', $u_agent)) {
    $platform = 'windows';
  }

  // Next get the name of the useragent yes seperately and for good reason
  if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)){
    $bname = 'Internet Explorer';
    $ub = "MSIE";
  }elseif(preg_match('/Firefox/i',$u_agent)){
    $bname = 'Mozilla Firefox';
    $ub = "Firefox";
  }elseif(preg_match('/OPR/i',$u_agent)){
    $bname = 'Opera';
    $ub = "Opera";
  }elseif(preg_match('/Chrome/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
    $bname = 'Google Chrome';
    $ub = "Chrome";
  }elseif(preg_match('/Safari/i',$u_agent) && !preg_match('/Edge/i',$u_agent)){
    $bname = 'Apple Safari';
    $ub = "Safari";
  }elseif(preg_match('/Netscape/i',$u_agent)){
    $bname = 'Netscape';
    $ub = "Netscape";
  }elseif(preg_match('/Edge/i',$u_agent)){
    $bname = 'Edge';
    $ub = "Edge";
  }elseif(preg_match('/Trident/i',$u_agent)){
    $bname = 'Internet Explorer';
    $ub = "MSIE";
  }

  // finally get the correct version number
  $known = array('Version', $ub, 'other');
  $pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
  if (!preg_match_all($pattern, $u_agent, $matches)) {
    // we have no matching number just continue
  }
  // see how many we have
  $i = count($matches['browser']);
  if ($i != 1) {
    //we will have two since we are not using 'other' argument yet
    //see if version is before or after the name
    if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
        $version= $matches['version'][0];
    }else {
        $version= $matches['version'][1];
    }
  }else {
    $version= $matches['version'][0];
  }

  // check if we have a number
  if ($version==null || $version=="") {$version="?";}

  return array(
    'userAgent' => $u_agent,
    'name'      => $bname,
    'version'   => $version,
    'platform'  => $platform,
    'pattern'    => $pattern
  );
} 

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

How to clear a data grid view

DataGrid.DataSource = null;
DataGrid.DataBind();

SQL Server principal "dbo" does not exist,

In my case I got this error when trying to impersonate as another user. E.g.

EXEC AS USER = 'dbo';

And as the database was imported from another environment, some of its users did not match the SQL Server logins.

You can check if you have the same problem by running the (deprecated) sp_change_users_login (in "Report" mode), or use the following query:

select p.name,p.sid "sid in DB", (select serp.sid from sys.server_principals serp where serp.name = p.name) "sid in server"
from sys.database_principals p
where p.type in ('G','S','U')
and p.authentication_type = 1
and p.sid not in (select sid from sys.server_principals)

If in that list shows the user you are trying to impersonate, then you probably can fix it by assigning the DB user to the proper login in your server. For instance:

ALTER USER dbo WITH LOGIN = dbo;

Get Application Directory

I got this

String appPath = App.getApp().getApplicationContext().getFilesDir().getAbsolutePath();

from here:

Unit test naming best practices

Class Names. For test fixture names, I find that "Test" is quite common in the ubiquitous language of many domains. For example, in an engineering domain: StressTest, and in a cosmetics domain: SkinTest. Sorry to disagree with Kent, but using "Test" in my test fixtures (StressTestTest?) is confusing.

"Unit" is also used a lot in domains. E.g. MeasurementUnit. Is a class called MeasurementUnitTest a test of "Measurement" or "MeasurementUnit"?

Therefore I like to use the "Qa" prefix for all my test classes. E.g. QaSkinTest and QaMeasurementUnit. It is never confused with domain objects, and using a prefix rather than a suffix means that all the test fixtures live together visually (useful if you have fakes or other support classes in your test project)

Namespaces. I work in C# and I keep my test classes in the same namespace as the class they are testing. It is more convenient than having separate test namespaces. Of course, the test classes are in a different project.

Test method names. I like to name my methods WhenXXX_ExpectYYY. It makes the precondition clear, and helps with automated documentation (a la TestDox). This is similar to the advice on the Google testing blog, but with more separation of preconditions and expectations. For example:

WhenDivisorIsNonZero_ExpectDivisionResult
WhenDivisorIsZero_ExpectError
WhenInventoryIsBelowOrderQty_ExpectBackOrder
WhenInventoryIsAboveOrderQty_ExpectReducedInventory

Error running android: Gradle project sync failed. Please fix your project and try again

Its because the gradle is not synced because of many reasons.

Go to project folder and remove .gradle folder and start sync. It will work

How to Add Stacktrace or debug Option when Building Android Studio Project

my solution is this:

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-v4:27.1.0'
    }
}

How can I run a program from a batch file without leaving the console open after the program starts?

You can use the exit keyword. Here is an example from one of my batch files:

start myProgram.exe param1
exit

Anaconda version with Python 3.5

Anacoda3-4.2.0 Uses python 3.5 You can find the same in the link given below : https://repo.continuum.io/archive/Anaconda3-4.2.0-Windows-x86_64.exe

I faced the same problem and found the correct version by checking the available Anaconda 4.2.0 distributions in installer archive here

How to import a .cer certificate into a java keystore?

Importing .cer certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security worked for me, as opposed to attemps to generate and use my own keystore.

  1. Go to your java_home\jre\lib\security
  2. (Windows) Open admin command line there using cmd and CTRL+SHIFT+ENTER
  3. Run keytool to import certificate:
    • (Replace yourAliasName and path\to\certificate.cer respectively)

 ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer

This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.

WhatsApp API (java/python)

After trying everything, Yowsup library worked for me. The bug that I was facing was recently fixed. Anyone trying to do something with Whatsapp should try it.

Get a filtered list of files in a directory

Filenames with "jpg" and "png" extensions in "path/to/images":

import os
accepted_extensions = ["jpg", "png"]
filenames = [fn for fn in os.listdir("path/to/images") if fn.split(".")[-1] in accepted_extensions]

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, it is asking for the application/executable that is capable of creating Javadoc. There is a javadoc executable inside the jdk's bin folder.

PHP Get Site URL Protocol - http vs https

I've tested the most voted answer and it didn't work for me, I ended up using:

$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

Define a fixed-size list in Java

If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.

If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.

public void fixedAdd(List<Integer> list, int val, int size) {
    list.add(val);
    if(list.size() > size) list.remove(0);
}

LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.

How to do INSERT into a table records extracted from another table

I believe your problem in this instance is the "values" keyword. You use the "values" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it.

Also, you really don't need the parentheses around the select statement.

From msdn:

Multiple-record append query:

INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, …]
FROM tableexpression

Single-record append query:

INSERT INTO target [(field1[, field2[, …]])]     
VALUES (value1[, value2[, …])

Getting Git to work with a proxy server - fails with "Request timed out"

After tirelessly trying every solution on this page, my work around was to use and SSH key instead!

  1. Open Git Bash
  2. $ ssh-keygen.exe -t rsa -C
  3. Open your Git provider (Github, Bitbucket, etc.)
  4. Add copy the id_rsa.pub file contents into Git provider's input page (check your profile)

How to sort an STL vector?

A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

template <typename T, typename U>
struct CompareByMember {
    // This is a pointer-to-member, it represents a member of class T
    // The data member has type U
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

struct Test {
    int a;
    int b;
    std::string c;
    Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};

// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
    return o << t.c;
}

int main() {
    std::vector<Test> vec;
    vec.push_back(Test(1, 10, "y"));
    vec.push_back(Test(2, 9, "x"));

    // sort on the string field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,std::string>(&Test::c));
    std::cout << "sorted by string field, c: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the first integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::a));
    std::cout << "sorted by integer field, a: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the second integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::b));
    std::cout << "sorted by integer field, b: ";
    std::cout << vec[0] << " " << vec[1] << "\n";
}

Output:

sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y

Create dynamic variable name

C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuickTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> names = new Dictionary<string,int>();


            for (int i = 0; i < 10; i++)
            {
                names.Add(String.Format("name{0}", i.ToString()), i);
            }

            var xx1 = names["name1"];
            var xx2 = names["name2"];
            var xx3 = names["name3"];
        }
    }
}

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

how to check for null with a ng-if values in a view with angularjs?

See the correct way with your example:

<div ng-if="!test.view">1</div>
<div ng-if="!!test.view">2</div>

Regards, Nicholls

Eclipse C++: Symbol 'std' could not be resolved

I do not know whether you have solved this problem but I want to post my solution for those might ran into the same problem.

  1. First, make sure that you have the "Includes" folder in your Project Explorer. If you do not have it, go to second step. If you have it, go to third step.

  2. Second, Window -> Preferences-> C/C++- > Build >Environment: Create two environment variables:

    a) Name: C_INCLUDE_PATH Value: /usr/include

    b) Name: CPLUS_INCLUDE_PATH Value: /usr/include/c++

Go to Cygwin/usr/include/, if you cannot find folder "c++", copy it from \cygwin\lib\gcc\i686-pc-cygwin\X.X.X\include and Then restart your Eclipse.

  1. Third, Right Click your project in Project Explorer -> Properties -> C/C++ General -> Paths and Symbols -> Includes -> Languages:GNU C++ If you can find some C++ folders in the "Include directories" then click Apply and OK. Change a bit your codes, and save it.

You will find there will be not symbol could not be resolved problems.

I documented my solution, hoping someone might get benefits.

RESTful call in Java

I see many answers, here's what we are using in 2020 WebClient, and BTW RestTemplate is going to get deprecated. (can check this) RestTemplate going to be deprecated

How to get current html page title with javascript

One option from DOM directly:

$(document).find("title").text();

Tested only on chrome & IE9, but logically should work on all browsers.

Or more generic

var title = document.getElementsByTagName("title")[0].innerHTML;

Parsing JSON Object in Java

Thank you so much to @Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!

I was working with Android reading a JSON from an URL and the only I had to change was the lines

Set<Object> set = jsonObject.keySet(); Iterator<Object> iterator = set.iterator();

for

Iterator<?> iterator = jsonObject.keys();

I share my implementation, to help someone:

public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {

    Iterator<?> iterator = jsonObject.keys();
    while (iterator.hasNext()) {
        String obj = iterator.next().toString();

        if (jsonObject.get(obj) instanceof JSONArray) {
            //Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
            //System.out.println(obj.toString());
            TextView txtView = new TextView(this);
            txtView.setText(obj.toString());
            layoutIzq.addView(txtView);
            getArray(jsonObject.get(obj));
        } else {
            if (jsonObject.get(obj) instanceof JSONObject) {
                //Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
                parseJson((JSONObject) jsonObject.get(obj));
            } else {
                //Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
                //System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
                TextView txtView = new TextView(this);
                txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
                layoutIzq.addView(txtView);
            }
        }
    }
}

Good examples of python-memcache (memcached) being used in Python?

It's fairly simple. You write values using keys and expiry times. You get values using keys. You can expire keys from the system.

Most clients follow the same rules. You can read the generic instructions and best practices on the memcached homepage.

If you really want to dig into it, I'd look at the source. Here's the header comment:

"""
client module for memcached (memory cache daemon)

Overview
========

See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

Usage summary
=============

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1")   # note that the key used for incr/decr must be a string.
    mc.incr("key")
    mc.decr("key")

The standard way to use memcache with a database is like this::

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

Detailed Documentation
======================

More detailed documentation is available in the L{Client} class.
"""

How to switch between python 2.7 to python 3 from command line?

For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3.

To add Python 3 to the environment variables, follow these steps -

  1. Right Click on My Computer and go to Properties.
  2. Go to Advanced System Settings.
  3. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory.

For example,

enter image description here

What is the difference between dict.items() and dict.iteritems() in Python2?

If you have

dict = {key1:value1, key2:value2, key3:value3,...}

In Python 2, dict.items() copies each tuples and returns the list of tuples in dictionary i.e. [(key1,value1), (key2,value2), ...]. Implications are that the whole dictionary is copied to new list containing tuples

dict = {i: i * 2 for i in xrange(10000000)}  
# Slow and memory hungry.
for key, value in dict.items():
    print(key,":",value)

dict.iteritems() returns the dictionary item iterator. The value of the item returned is also the same i.e. (key1,value1), (key2,value2), ..., but this is not a list. This is only dictionary item iterator object. That means less memory usage (50% less).

  • Lists as mutable snapshots: d.items() -> list(d.items())
  • Iterator objects: d.iteritems() -> iter(d.items())

The tuples are the same. You compared tuples in each so you get same.

dict = {i: i * 2 for i in xrange(10000000)}  
# More memory efficient.
for key, value in dict.iteritems():
    print(key,":",value)

In Python 3, dict.items() returns iterator object. dict.iteritems() is removed so there is no more issue.

grabbing first row in a mysql query only

To return only one row use LIMIT 1:

SELECT *
FROM tbl_foo
WHERE name = 'sarmen'
LIMIT 1

It doesn't make sense to say 'first row' or 'last row' unless you have an ORDER BY clause. Assuming you add an ORDER BY clause then you can use LIMIT in the following ways:

  • To get the first row use LIMIT 1.
  • To get the 2nd row you can use limit with an offset: LIMIT 1, 1.
  • To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1.

What does the Java assert keyword do, and when should it be used?

Assertions are a development-phase tool to catch bugs in your code. They're designed to be easily removed, so they won't exist in production code. So assertions are not part of the "solution" that you deliver to the customer. They're internal checks to make sure that the assumptions you're making are correct. The most common example is to test for null. Many methods are written like this:

void doSomething(Widget widget) {
  if (widget != null) {
    widget.someMethod(); // ...
    ... // do more stuff with this widget
  }
}

Very often in a method like this, the widget should simply never be null. So if it's null, there's a bug in your code somewhere that you need to track down. But the code above will never tell you this. So in a well-intentioned effort to write "safe" code, you're also hiding a bug. It's much better to write code like this:

/**
 * @param Widget widget Should never be null
 */
void doSomething(Widget widget) {
  assert widget != null;
  widget.someMethod(); // ...
    ... // do more stuff with this widget
}

This way, you will be sure to catch this bug early. (It's also useful to specify in the contract that this parameter should never be null.) Be sure to turn assertions on when you test your code during development. (And persuading your colleagues to do this, too is often difficult, which I find very annoying.)

Now, some of your colleagues will object to this code, arguing that you should still put in the null check to prevent an exception in production. In that case, the assertion is still useful. You can write it like this:

void doSomething(Widget widget) {
  assert widget != null;
  if (widget != null) {
    widget.someMethod(); // ...
    ... // do more stuff with this widget
  }
}

This way, your colleagues will be happy that the null check is there for production code, but during development, you're no longer hiding the bug when widget is null.

Here's a real-world example: I once wrote a method that compared two arbitrary values for equality, where either value could be null:

/**
 * Compare two values using equals(), after checking for null.
 * @param thisValue (may be null)
 * @param otherValue (may be null)
 * @return True if they are both null or if equals() returns true
 */
public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
  } else {
    result = thisValue.equals(otherValue);
  }
  return result;
}

This code delegates the work of the equals() method in the case where thisValue is not null. But it assumes the equals() method correctly fulfills the contract of equals() by properly handling a null parameter.

A colleague objected to my code, telling me that many of our classes have buggy equals() methods that don't test for null, so I should put that check into this method. It's debatable if this is wise, or if we should force the error, so we can spot it and fix it, but I deferred to my colleague and put in a null check, which I've marked with a comment:

public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
  } else {
    result = otherValue != null && thisValue.equals(otherValue); // questionable null check
  }
  return result;
}

The additional check here, other != null, is only necessary if the equals() method fails to check for null as required by its contract.

Rather than engage in a fruitless debate with my colleague about the wisdom of letting the buggy code stay in our code base, I simply put two assertions in the code. These assertions will let me know, during the development phase, if one of our classes fails to implement equals() properly, so I can fix it:

public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
    assert otherValue == null || otherValue.equals(null) == false;
  } else {
    result = otherValue != null && thisValue.equals(otherValue);
    assert thisValue.equals(null) == false;
  }
  return result;
}

The important points to keep in mind are these:

  1. Assertions are development-phase tools only.

  2. The point of an assertion is to let you know if there's a bug, not just in your code, but in your code base. (The assertions here will actually flag bugs in other classes.)

  3. Even if my colleague was confident that our classes were properly written, the assertions here would still be useful. New classes will be added that might fail to test for null, and this method can flag those bugs for us.

  4. In development, you should always turn assertions on, even if the code you've written doesn't use assertions. My IDE is set to always do this by default for any new executable.

  5. The assertions don't change the behavior of the code in production, so my colleague is happy that the null check is there, and that this method will execute properly even if the equals() method is buggy. I'm happy because I will catch any buggy equals() method in development.

Also, you should test your assertion policy by putting in a temporary assertion that will fail, so you can be certain that you are notified, either through the log file or a stack trace in the output stream.

Service vs IntentService in the Android platform

An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.

IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.

It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.

For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.

PHP post_max_size overrides upload_max_filesize

change in php.ini max_input_vars 1000

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

just to answer your question...btw sry that i'm 9 months late:D...there's a "workaround" 4 this kind of problems. i.e.

new AlertDialog.Builder(some_class.this).setTitle("bla").setMessage("bla bla").show();
wait();

simply add wait();

and them in the OnClickListener start the class again with notify() something like this

@Override
    public void onClick(DialogInterface dialog, int item) {
        Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();
        **notify**();
        dialog.cancel();
    }

the same workaround goes 4 toasts and other async calls in android

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

Java Class.cast() vs. cast operator

I've only ever used Class.cast(Object) to avoid warnings in "generics land". I often see methods doing things like this:

@SuppressWarnings("unchecked")
<T> T doSomething() {
    Object o;
    // snip
    return (T) o;
}

It's often best to replace it by:

<T> T doSomething(Class<T> cls) {
    Object o;
    // snip
    return cls.cast(o);
}

That's the only use case for Class.cast(Object) I've ever come across.

Regarding compiler warnings: I suspect that Class.cast(Object) isn't special to the compiler. It could be optimized when used statically (i.e. Foo.class.cast(o) rather than cls.cast(o)) but I've never seen anybody using it - which makes the effort of building this optimization into the compiler somewhat worthless.

How to get the data-id attribute?

Try

this.dataset.id

_x000D_
_x000D_
$("#list li").on('click', function() {_x000D_
  alert( this.dataset.id );_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>_x000D_
_x000D_
<ul id="list" class="grid">_x000D_
  <li data-id="id-40" class="win">_x000D_
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">_x000D_
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />_x000D_
    </a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I run Redis on Windows?

You can go through the below steps and get setup redis in windows.

  1. Download the Redis zip file. Click here!

  2. Extract the zip file to the prepared directory.

  3. Run redis-server.exe, you can either directly run redis-server.exe by clicking or run via command prompt.

enter image description here

  1. Run redis-cli.exe, after successfully running the redis-server. You can access it and test commands by running redis-cli.exe Test PING command is used to test if a connection is still alive.

enter image description here

Making the iPhone vibrate

From "iPhone Tutorial: Better way to check capabilities of iOS devices":

There are two seemingly similar functions that take a parameter kSystemSoundID_Vibrate:

1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Both of the functions vibrate the iPhone. But, when you use the first function on devices that don’t support vibration, it plays a beep sound. The second function, on the other hand, does nothing on unsupported devices. So if you are going to vibrate the device continuously, as an alert, common sense says, use function 2.

First, add the AudioToolbox framework AudioToolbox.framework to your target in Build Phases.

Then, import this header file:

#import <AudioToolbox/AudioServices.h>

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

How can I pull from remote Git repository and override the changes in my local repository?

Provided that the remote repository is origin, and that you're interested in master:

git fetch origin
git reset --hard origin/master

This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.

All your local commits not common to the remote will be gone.

Replacing a character from a certain index

Strings in Python are immutable meaning you cannot replace parts of them.

You can however create a new string that is modified. Mind that this is not semantically equivalent since other references to the old string will not be updated.

You could for instance write a function:

def replace_str_index(text,index=0,replacement=''):
    return '%s%s%s'%(text[:index],replacement,text[index+1:])

And then for instance call it with:

new_string = replace_str_index(old_string,middle)

If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.

For instance:

replace_str_index('hello?bye',5)

will return 'hellobye'; and:

replace_str_index('hello?bye',5,'good')

will return 'hellogoodbye'.

How to make a JFrame Modal in Swing java

You can create a class that is passed a reference to the parent JFrame and holds it in a JFrame variable. Then you can lock the frame that created your new frame.

parentFrame.disable();

//Some actions

parentFrame.enable();

"Proxy server connection failed" in google chrome

Try following these steps:

  1. Run Chrome as Administrator.
  2. Go to the settings in Chrome.
  3. Go to Advanced Settings (its all the way down).
  4. Scroll to Network Section and click on ''Change proxy settings''.
  5. A window will pop up with the name ''Internet Properties''
  6. Click on ''LAN settings''
  7. Un-check ''Use a proxy server for your LAN''
  8. Check ''Automatically detect settings''
  9. Click everything ''OK'' and you are done!

Suppress command line output

mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"

How to change row color in datagridview?

int counter = gridEstimateSales.Rows.Count;

for (int i = 0; i < counter; i++)
{
    if (i == counter-1)
    {
        //this is where your LAST LINE code goes
        //row.DefaultCellStyle.BackColor = Color.Yellow;
        gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.Red;
    }
    else
    {
        //this is your normal code NOT LAST LINE
        //row.DefaultCellStyle.BackColor = Color.Red;
        gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.White;
    }
}

Convert XML to JSON (and back) using Javascript

I was using xmlToJson just to get a single value of the xml.
I found doing the following is much easier (if the xml only occurs once..)

_x000D_
_x000D_
let xml =_x000D_
'<person>' +_x000D_
  ' <id>762384324</id>' +_x000D_
  ' <firstname>Hank</firstname> ' +_x000D_
  ' <lastname>Stone</lastname>' +_x000D_
'</person>';_x000D_
_x000D_
let getXmlValue = function(str, key) {_x000D_
  return str.substring(_x000D_
    str.lastIndexOf('<' + key + '>') + ('<' + key + '>').length,_x000D_
    str.lastIndexOf('</' + key + '>')_x000D_
  );_x000D_
}_x000D_
_x000D_
_x000D_
alert(getXmlValue(xml, 'firstname')); // gives back Hank
_x000D_
_x000D_
_x000D_

Java Class that implements Map and keeps insertion order?

If an immutable map fits your needs then there is a library by google called guava (see also guava questions)

Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.

ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.

How do I compare version numbers in Python?

There is packaging package available, which will allow you to compare versions as per PEP-440, as well as legacy versions.

>>> from packaging.version import Version, LegacyVersion
>>> Version('1.1') < Version('1.2')
True
>>> Version('1.2.dev4+deadbeef') < Version('1.2')
True
>>> Version('1.2.8.5') <= Version('1.2')
False
>>> Version('1.2.8.5') <= Version('1.2.8.6')
True

Legacy version support:

>>> LegacyVersion('1.2.8.5-5-gdeadbeef')
<LegacyVersion('1.2.8.5-5-gdeadbeef')>

Comparing legacy version with PEP-440 version.

>>> LegacyVersion('1.2.8.5-5-gdeadbeef') < Version('1.2.8.6')
True

document.getElementById(id).focus() is not working for firefox or chrome

Your focus is working before return false; ,After that is not working. You try this solution. Control after return false;

Put code in function:

function  validateNumber(){
    var mnumber = document.getElementById('mobileno').value; 
    if(mnumber.length >=10) {
        alert("Mobile Number Should be in 10 digits only"); 
        document.getElementById('mobileno').value = ""; 
        return false; 
    }else{
        return true;
    }
}

Caller function:

function submitButton(){
        if(!validateNumber()){
            document.getElementById('mobileno').focus();
            return false;
        }
}

HTML:

Input:<input type="text" id="mobileno">
<button onclick="submitButton();" >Submit</button>

Insert an item into sorted list in Python

I'm learning Algorithm right now, so i wonder how bisect module writes. Here is the code from bisect module about inserting an item into sorted list, which uses dichotomy:

def insort_right(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.
    If x is already in a, insert it to the right of the rightmost x.
    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]:
            hi = mid
        else:
            lo = mid+1
    a.insert(lo, x)

How can I use MS Visual Studio for Android Development?

Yes, you can use Visual Studio for Android (native) using "vs-android".

Here are the steps to set it up:

  1. Download the Android SDK here.

  2. Download the Android NDK here.

  3. Download Cygwin here.

  4. Download the JDK here.

  5. Download Visual Studio 2010, 2012 or 2013 here.

  6. Download vs-android here.

  7. Download Apache Ant here.

  8. Set environment variables:

(Control Panel > System > Advanced > Environment Variables)

ANDROID_HOME = <install_path>\android-sdk
ANDROID_NDK_ROOT = <install_path>\android-ndk
ANT_HOME  = <install_path>\apache-ant
JAVA_HOME = <install_path>\jdk
_JAVA_OPTIONS = -Xms256m -Xmx512m  
  1. Download examples from here.

It works like a charm... and best so far to use.

What is the use of the JavaScript 'bind' method?

As mentioned, Function.bind() lets you specify the context that the function will execute in (that is, it lets you pass in what object the this keyword will resolve to in the body of the function.

A couple of analogous toolkit API methods that perform a similar service:

jQuery.proxy()

Dojo.hitch()

Reactjs setState() with a dynamic key name?

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

For example:

_x000D_
_x000D_
inputChangeHandler(event) {_x000D_
  this.setState({ [event.target.name]: event.target.value });_x000D_
}
_x000D_
_x000D_
_x000D_

Curl command line for consuming webServices?

For a SOAP 1.2 Webservice, I normally use

curl --header "content-type: application/soap+xml" --data @filetopost.xml http://domain/path

Appending a line to a file only if it does not already exist

If writing to a protected file, @drAlberT and @rubo77 's answers might not work for you since one can't sudo >>. A similarly simple solution, then, would be to use tee --append (or, on MacOS, tee -a):

LINE='include "/configs/projectname.conf"'
FILE=lighttpd.conf
grep -qF "$LINE" "$FILE"  || echo "$LINE" | sudo tee --append "$FILE"

Excel 2013 VBA Clear All Filters macro

ShowAllData will throw an error if a filter isn't currently applied. This will work:

Sub ResetFilters()
    On Error Resume Next
    ActiveSheet.ShowAllData
End Sub

android - listview get item view by position

You can get only visible View from ListView because row views in ListView are reuseable. If you use mListView.getChildAt(0) you get first visible view. This view is associated with item from adapter at position mListView.getFirstVisiblePosition().

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

Can Mockito stub a method without regard to the argument?

when(
  fooDao.getBar(
    any(Bazoo.class)
  )
).thenReturn(myFoo);

or (to avoid nulls):

when(
  fooDao.getBar(
    (Bazoo)notNull()
  )
).thenReturn(myFoo);

Don't forget to import matchers (many others are available):

For Mockito 2.1.0 and newer:

import static org.mockito.ArgumentMatchers.*;

For older versions:

import static org.mockito.Matchers.*;

How to pass password to scp?

steps to get sshpass For rhel/centos 6 :

# wget http://epel.mirror.net.in/epel/6/i386/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm
# yum install sshpass

source: https://community.mapr.com/thread/9040

Resize HTML5 canvas to fit window

If your div completely filled the webpage then you can fill up that div and so have a canvas that fills up the div.

You may find this interesting, as you may need to use a css to use percentage, but, it depends on which browser you are using, and how much it is in agreement with the spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

You may need to get the offsetWidth and height of the div, or get the window height/width and set that as the pixel value.

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

I ran into this problem as well. The underlying problem is that the ssl library in Python 2.7 versions < 2.7.9 is no longer compatible with the pip mechanism.

If you are running on Windows, and you (like us) can't easily upgrade from an incompatible version of 2.7, FWIW, I found that if you copy the following files from another install of the latest version of Python (e.g. Python 2.7.15) on another machine to your installation:

    Lib\ssl.py
    libs\_ssl.lib
    DLLs\_ssl.dll

it will effectively "upgrade" your SSL layer to one which is supported; we were then be able to use pip again, even to upgrade pip.

How to amend older Git commit?

git rebase -i HEAD^^^

Now mark the ones you want to amend with edit or e (replace pick). Now save and exit.

Now make your changes, then

git add .
git rebase --continue

If you want to add an extra delete remove the options from the commit command. If you want to adjust the message, omit just the --no-edit option.

adding multiple entries to a HashMap at once in one statement

    boolean x;
    for (x = false, 
        map.put("One", new Integer(1)), 
        map.put("Two", new Integer(2)),      
        map.put("Three", new Integer(3)); x;);

Ignoring the declaration of x (which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.

how to execute php code within javascript

If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>

However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
  alert("asdasd");
  $('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>

This runs the php script and loads whatever message it returns into <div id="resultMsg">.

order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:

<?php
// do adding to cart stuff here
echo 'Added to cart';
?>

For this to work you will need to include jQuery on your page, by adding this in your <head> tag:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

How To Make Circle Custom Progress Bar in Android

Rest of code

Code of utils methods:

public static int[] resourcesIDsToColors(Context context, int[] resIDs){
            int[] colors = new int[resIDs.length];
            for(int i=0; i < resIDs.length; i++){
                colors[i] = ActivityCompat.getColor(context, resIDs[i]);
            }
            return colors;
        }
    
    public static void setSubClassFieldIntValue(Object objField, Class<?> superClass, String subName, String fieldName, int fieldValue){
            Class<?> subClass = getSubClass(superClass, subName);
            if(subClass != null) {
                Field field = getClassField(subClass, fieldName);
                if (field != null) {
                    setFieldValue(objField, field, fieldValue);
                }
            }
        }
    
        public static Class<?> getSubClass(Class<?> superClass, String subName){
            Class<?>[] classes = superClass.getDeclaredClasses();
            if(classes != null && classes.length > 0){
                for(Class<?> clss : classes){
                    if(clss.getSimpleName().equals(subName)){
                        return clss;
                    }
                }
            }
            return null;
        }
    
        public static Field getClassField(Class<?> clss, String fieldName){
            try {
                Field field = clss.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field;
            } catch (NoSuchFieldException nsfE) {
                Log.e(TAG, nsfE.getMessage());
            } catch (SecurityException sE){
                Log.e(TAG, sE.getMessage());
            } catch (Exception e){
                Log.e(TAG, e.getMessage());
            }
            return null;
        }
    
    public static int[][] arrayToMatrix(int[] array, int numColumns){
            int numRows = array.length / numColumns;
            int[][] matrix = new int[numRows][numColumns];
            int nElemens = array.length;
            for(int i=0; i < nElemens; i++){
                matrix[i / numColumns][i % numColumns] = array[i];
            }
            return matrix;
        }

public static int[] matrixToArray(int[][] matrix){
        /** [+] Square matrix of order n        ->      A matrix with n rows and n columns, same number of rows and columns.
         *  [+] Matrix rows & columns number annotations:
         *          matrix[rows][columns]           matrix (rows x columns)         matrix rows, columns        rows by columns matrix
         * **/
        int numRows = matrix.length;
        int[] arr = new int[]{};
        for(int i=0; i < numRows; i++){
            int numColumns = matrix[i].length;
            int[] row = new int[numColumns];
            for(int j=0; j < numColumns; j++){
                row[j] = matrix[i][j];
            }
            arr = ArrayUtils.addAll(arr, row);
        }
        return arr;
    }

Code of default layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@color/transparent">
    <LinearLayout
        android:id="@+id/layout_progress_bar_only"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone">
        <android.support.constraint.ConstraintLayout
            android:id="@+id/dpb_constraint_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <me.zhanghai.android.materialprogressbar.MaterialProgressBar
                android:id="@+id/dpb_progress_bar"
                android:layout_width="@dimen/pbd_progressbar_width_2"
                android:layout_height="@dimen/pbd_progressbar_height_2"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"/>
            <LinearLayout
                android:id="@+id/dpb_text_container"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.5"/>
        </android.support.constraint.ConstraintLayout>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/layout_progress_bar_and_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone"
        style="@style/PBDTextualMainLayoutStyle">
        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:cardElevation="@dimen/pbd_textual_card_elevation">
            <TextView
                android:id="@+id/pbd_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                style="@style/PBDTextualTitle"/>
        </android.support.v7.widget.CardView>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/pbd_textual_main_layout_height"
            android:orientation="horizontal">
            <android.support.v7.widget.CardView
                android:layout_width="@dimen/pbd_textual_progressbar_width"
                android:layout_height="@dimen/pbd_textual_progressbar_height">
                <me.zhanghai.android.materialprogressbar.MaterialProgressBar
                    android:id="@+id/dpb_progress_bar_and_msg"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    style="@style/PBDProgressBarStyle"/>
            </android.support.v7.widget.CardView>
            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="@dimen/pbd_textual_msg_container_height">
                <TextView
                    android:id="@+id/dpb_progress_msg"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    style="@style/PBDTextualProgressMsgStyle"/>
            </android.support.v7.widget.CardView>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Progress Bar Rings:

<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:fromDegrees="300"
            android:toDegrees="660">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <gradient
                    android:type="sweep"/>
            </shape>
        </rotate>
    </item>
    <item>
        <rotate
            android:fromDegrees="210"
            android:toDegrees="570">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <gradient
                    android:type="sweep"/>
            </shape>
        </rotate>
    </item>
    <item>
        <rotate
            android:fromDegrees="120"
            android:toDegrees="480">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <gradient
                    android:type="sweep"
                    android:startColor="#00000000"
                    android:centerColor="#00000000"/>
            </shape>
        </rotate>
    </item>
    <item>
        <rotate
            android:fromDegrees="30"
            android:toDegrees="390">
            <shape
                android:shape="ring"
                android:useLevel="false">
                <solid android:color="#000000"/>
                <gradient
                    android:type="sweep"/>
            </shape>
        </rotate>
    </item>
</layer-list>

Dimens Resources:

 <!-- ProgressBarDialog Dimens (Normal & Textual Versions) -->
        <dimen name="pbd_window_width">250dp</dimen>
        <dimen name="pbd_window_height">250dp</dimen>
        <dimen name="pbd_progressbar_width_1">250dp</dimen>
        <dimen name="pbd_progressbar_height_1">250dp</dimen>
        <dimen name="pbd_progressbar_width_2">400dp</dimen>
        <dimen name="pbd_progressbar_height_2">400dp</dimen>
        <dimen name="pbd_textual_window_height">170dp</dimen>
        <dimen name="pbd_textual_main_layout_height">150dp</dimen>
        <dimen name="pbd_textual_progressbar_width">150dp</dimen>
        <dimen name="pbd_textual_progressbar_height">150dp</dimen>
        <dimen name="pbd_textual_msg_container_height">150dp</dimen>
        <dimen name="pbd_textual_main_layout_margin_horizontal">50dp</dimen>
        <dimen name="pbd_textual_main_layout_padding_horizontal">5dp</dimen>
        <dimen name="pbd_textual_main_layout_padding_bottom">15dp</dimen>
        <dimen name="pbd_textual_title_padding">4dp</dimen>
        <dimen name="pbd_textual_msg_container_margin">3dp</dimen>
        <dimen name="pbd_textual_msg_container_padding">3dp</dimen>
        <dimen name="pbd_textual_card_elevation">15dp</dimen>
        <dimen name="pbd_textual_progressmsg_padding_start">10dp</dimen>
        <dimen name="pbd_inner_radius_30dp">30dp</dimen>
        <dimen name="pbd_inner_radius_60dp">60dp</dimen>
        <dimen name="pbd_inner_radius_90dp">90dp</dimen>
        <dimen name="pbd_inner_radius_120dp">120dp</dimen>
        <dimen name="pbd_thickness_40dp">40dp</dimen>
        <dimen name="pbd_thickness_30dp">30dp</dimen>
        <dimen name="pbd_thickness_25dp">25dp</dimen>
        <dimen name="pbd_thickness_20dp">20dp</dimen>
        <dimen name="pbd_thickness_15dp">15dp</dimen>
        <dimen name="pbd_thickness_10dp">10dp</dimen>

Styles Resources:

<!-- PROGRESS BAR DIALOG STYLES -->
    <style name="PBDCenterTextStyleWhite">
        <item name="android:textAlignment">center</item>
        <item name="android:textAppearance">?android:attr/textAppearanceLarge</item>
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">@color/material_white</item>
        <item name="android:layout_gravity">center</item>
        <item name="android:gravity">center</item>
    </style>

    <style name="PBDTextualTitle">
        <item name="android:textAlignment">viewStart</item>
        <item name="android:textAppearance">?android:attr/textAppearanceLargeInverse</item>
        <item name="android:textStyle">bold|italic</item>
        <item name="android:textColor">@color/colorAccent</item>
        <item name="android:padding">@dimen/pbd_textual_title_padding</item>
        <item name="android:layout_gravity">start</item>
        <item name="android:gravity">center_vertical|start</item>
        <item name="android:background">@color/colorPrimaryDark</item>
    </style>

    <style name="PBDTextualProgressMsgStyle">
        <item name="android:textAlignment">viewStart</item>
        <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
        <item name="android:textColor">@color/material_black</item>
        <item name="android:textStyle">normal|italic</item>
        <item name="android:paddingStart">@dimen/pbd_textual_progressmsg_padding_start</item>
        <item name="android:layout_gravity">start</item>
        <item name="android:gravity">center_vertical|start</item>
        <item name="android:background">@color/material_yellow_A100</item>
    </style>

    <style name="PBDTextualMainLayoutStyle">
        <item name="android:paddingLeft">@dimen/pbd_textual_main_layout_padding_horizontal</item>
        <item name="android:paddingRight">@dimen/pbd_textual_main_layout_padding_horizontal</item>
        <item name="android:paddingBottom">@dimen/pbd_textual_main_layout_padding_bottom</item>
        <item name="android:background">@color/colorPrimaryDark</item>
    </style>

    <style name="PBDProgressBarStyle">
        <item name="android:layout_gravity">center</item>
        <item name="android:gravity">center</item>
    </style>

Difference between JOIN and INNER JOIN

INNER JOIN = JOIN

INNER JOIN is the default if you don't specify the type when you use the word JOIN.

You can also use LEFT OUTER JOIN or RIGHT OUTER JOIN, in which case the word OUTER is optional, or you can specify CROSS JOIN.

OR

For an inner join, the syntax is:

SELECT ...
FROM TableA
[INNER] JOIN TableB

(in other words, the "INNER" keyword is optional - results are the same with or without it)

Alternating Row Colors in Bootstrap 3 - No Table

There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type (or :nth-child -- either would work in this case.)

Smallest viewport:

@media (max-width:$smallest-breakpoint) {

  .row div {
     background: #eee;
   }

  .row div:nth-of-type(2n) {
     background: #fff;
   }

}

Medium viewport:

@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
    background: #fff;
  }

}

Largest viewport:

@media (min-width:$mid-breakpoint) and (max-width:9999px) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(6n+4), 
  .row div:nth-of-type(6n+5), 
  .row div:nth-of-type(6n+6) {
      background: #fff;
  }
}

Working fiddle here

Get viewport/window height in ReactJS

Adding this for diversity and clean approach.

This code uses functional style approach. I have used onresize instead of addEventListener as mentioned in other answers.

import { useState, useEffect } from "react";

export default function App() {
  const [size, setSize] = useState({
    x: window.innerWidth,
    y: window.innerHeight
  });
  const updateSize = () =>
    setSize({
      x: window.innerWidth,
      y: window.innerHeight
    });
  useEffect(() => (window.onresize = updateSize), []);
  return (
    <>
      <p>width is : {size.x}</p>
      <p>height is : {size.y}</p>
    </>
  );
}

How to access URL segment(s) in blade in Laravel 5?

BASED ON LARAVEL 5.7 & ABOVE

To get all segments of current URL:

$current_uri = request()->segments();

To get segment posts from http://example.com/users/posts/latest/

NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users and segment(1) will be posts.

//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'

You may have noted that the segment method only works with the current URL ( url()->current() ). So I designed a method to work with previous URL too by cloning the segment() method:

public function index()
{
    $prev_uri_segments = $this->prev_segments(url()->previous());
}

 /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

Compiling with g++ using multiple cores

People have mentioned make but bjam also supports a similar concept. Using bjam -jx instructs bjam to build up to x concurrent commands.

We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.