Programs & Examples On #Visualdesigner

How to send Request payload to REST API in java?

The following code works for me.

//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
                jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        return jsonString.toString();
    } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
    }

}

How to asynchronously call a method in Java

i don't like the idea of using Reflection for that.
Not only dangerous for missing it in some refactoring, but it can also be denied by SecurityManager.

FutureTask is a good option as the other options from the java.util.concurrent package.
My favorite for simple tasks:

    Executors.newSingleThreadExecutor().submit(task);

little bit shorter than creating a Thread (task is a Callable or a Runnable)

How can I make visible an invisible control with jquery? (hide and show not work)

It's been more than 10 years and not sure if anyone still finding this question or answer relevant.

But a quick workaround is just to wrap the asp control within a html container

<div id="myElement" style="display: inline-block">
   <asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>

Whenever the Javascript Event is triggered, if it needs to be an event by the asp control, just wrap the asp control around the div container.

<div id="testG">  
   <asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>

The jQuery Code is below:

$(document).ready(function () {
    $("#testG").click(function () {
                $("#myElement").css("display", "none");
     });
});

How to keep one variable constant with other one changing with row in excel

For future visitors - use this for range: ($A$1:$A$10)

Example
=COUNTIF($G$6:$G$9;J6)>0

Contains case insensitive

if (referrer.toUpperCase().indexOf("RAL") == -1) { ...

Create a new Ruby on Rails application using MySQL instead of SQLite

Just go to rails console and type:

rails new YOURAPPNAME -d mysql

How to handle click event in Button Column in Datagridview?

A bit late to the table here, but in c# (vs2013) you don't need to use column names either, in fact a lot of the extra work that some people propose is completely unnecessary.

The column is actually created as an member of the container (the form, or usercontrol that you've put the DataGridView into). From the designer code (the stuff you're not supposed to edit except when the designer breaks something), you'd see something like:

this.curvesList.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.enablePlot,
        this.desc,
        this.unit,
        this.min,
        this.max,
        this.color});

...

//
// color
// 
this.color.HeaderText = "Colour";
this.color.MinimumWidth = 40;
this.color.Name = "color";
this.color.ReadOnly = true;
this.color.Width = 40;

...

private System.Windows.Forms.DataGridViewButtonColumn color;

So in the CellContentClick handler, apart from ensuring that the row index is not 0, you just need to check whether the clicked column is in fact the one you want by comparing object references:

private void curvesList_CellContentClick(object sender, 
    DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView)sender;
    var column = senderGrid.Columns[e.ColumnIndex];
    if (e.RowIndex >= 0)
    {
        if ((object)column == (object)color)
        {
            colorDialog.Color = Color.Blue;
                colorDialog.ShowDialog();
        }
    }
}

Note that the beauty of this is that any name changes will be caught by the compiler. If you index with a text name that changes, or that you capitalize incorrectly, you're bound for runtime issues. Here you actually use the name of an object, that the designer creates based on the name you supplied. But any mismatch will be brought to your attention by the compiler.

Remove element of a regular array

This is a way to delete an array element, as of .Net 3.5, without copying to another array - using the same array instance with Array.Resize<T>:

public static void RemoveAt<T>(ref T[] arr, int index)
{
    for (int a = index; a < arr.Length - 1; a++)
    {
        // moving elements downwards, to fill the gap at [index]
        arr[a] = arr[a + 1];
    }
    // finally, let's decrement Array's size by one
    Array.Resize(ref arr, arr.Length - 1);
}

Using jQuery to see if a div has a child with a certain class

Simple Way

if ($('#text-field > p.filled-text').length != 0)

How to return a string value from a Bash function

As previously mentioned, the "correct" way to return a string from a function is with command substitution. In the event that the function also needs to output to console (as @Mani mentions above), create a temporary fd in the beginning of the function and redirect to console. Close the temporary fd before returning your string.

#!/bin/bash
# file:  func_return_test.sh
returnString() {
    exec 3>&1 >/dev/tty
    local s=$1
    s=${s:="some default string"}
    echo "writing directly to console"
    exec 3>&-     
    echo "$s"
}

my_string=$(returnString "$*")
echo "my_string:  [$my_string]"

executing script with no params produces...

# ./func_return_test.sh
writing directly to console
my_string:  [some default string]

hope this helps people

-Andy

Set selected item in Android BottomNavigationView

From API 25.3.0 it was introduced the method setSelectedItemId(int id) which lets you mark an item as selected as if it was tapped.

From docs:

Set the selected menu item ID. This behaves the same as tapping on an item.

Code example:

BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);

IMPORTANT

You MUST have already added all items to the menu (in case you do this programmatically) and set the Listener before calling setSelectedItemId(I believe you want the code in your listener to run when you call this method). If you call setSelectedItemId before adding the menu items and setting the listener nothing will happen.

Replace first occurrence of pattern in a string

public string ReplaceFirst(string text, string search, string replace)
{
  int pos = text.IndexOf(search);
  if (pos < 0)
  {
    return text;
  }
  return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}

here is an Extension Method that could also work as well per VoidKing request

public static class StringExtensionMethods
{
    public static string ReplaceFirst(this string text, string search, string replace)
    {
      int pos = text.IndexOf(search);
      if (pos < 0)
      {
        return text;
      }
      return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }
}

Test or check if sheet exists

If you are specifically interested in worksheets only, you can use a simple Evaluate call:

Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

NSOperation vs Grand Central Dispatch

GCD is a low-level C-based API.
NSOperation and NSOperationQueue are Objective-C classes.
NSOperationQueue is objective C wrapper over GCD. If you are using NSOperation, then you are implicitly using Grand Central Dispatch.

GCD advantage over NSOperation:
i. implementation
For GCD implementation is very light-weight
NSOperationQueue is complex and heavy-weight

NSOperation advantages over GCD:

i. Control On Operation
you can Pause, Cancel, Resume an NSOperation

ii. Dependencies
you can set up a dependency between two NSOperations
operation will not started until all of its dependencies return true for finished.

iii. State of Operation
can monitor the state of an operation or operation queue. ready ,executing or finished

iv. Max Number of Operation
you can specify the maximum number of queued operations that can run simultaneously

When to Go for GCD or NSOperation
when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD

ref:
https://cocoacasts.com/choosing-between-nsoperation-and-grand-central-dispatch/ http://iosinfopot.blogspot.in/2015/08/nsthread-vs-gcd-vs-nsoperationqueue.html http://nshipster.com/nsoperation/

How to disable Google Chrome auto update?

Actually, you can shut down the automatic update function through Chrome browser settings. Or you can do it via altering system registry entries. You can view detailed tips here http://blog.doofix.com/how-to-stop-google-chrome-from-automatic-update/ Hope this helps!

Get IP address of an interface on Linux

My 2 cents: the same code works even if iOS:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    showIP();
}



void showIP()
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1)
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }


    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL)
            continue;

        s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

        if( /*(strcmp(ifa->ifa_name,"wlan0")==0)&&( */ ifa->ifa_addr->sa_family==AF_INET) // )
        {
            if (s != 0)
            {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("\tInterface : <%s>\n",ifa->ifa_name );
            printf("\t  Address : <%s>\n", host);
        }
    }

    freeifaddrs(ifaddr);
}


@end

I simply removed the test against wlan0 to see data. ps You can remove "family"

How to match letters only using java regex, matches method?

[A-Za-z ]* to match letters and spaces.

dropping infinite values from dataframes in pandas?

Yet another solution would be to use the isin method. Use it to determine whether each value is infinite or missing and then chain the all method to determine if all the values in the rows are infinite or missing.

Finally, use the negation of that result to select the rows that don't have all infinite or missing values via boolean indexing.

all_inf_or_nan = df.isin([np.inf, -np.inf, np.nan]).all(axis='columns')
df[~all_inf_or_nan]

CSS Grid Layout not working in IE11 even with prefixes

To support IE11 with auto-placement, I converted grid to table layout every time I used the grid layout in 1 dimension only. I also used margin instead of grid-gap.

The result is the same, see how you can do it here https://jsfiddle.net/hp95z6v1/3/

How to recover Git objects damaged by hard disk failure?

Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.

# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD

$ cat .git/HEAD 
ref: refs/heads/master

$ ls .git/refs/heads/

$ cat .git/packed-refs 
# pack-refs with: peeled 
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master

$ git fsck --full 
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc

# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects

# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack

# Check reflogs...
$ git reflog

# ...then clean
$ git reflog expire --expire=0 --all

# Now garbage collect again
$ git gc       
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!

SQL Query - Concatenating Results into One String

If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF trick:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STUFF( (SELECT ',' + CodeName 
                             FROM dbo.AccountCodes 
                             ORDER BY Sort
                             FOR XML PATH('')), 
                            1, 1, '')

The FOR XML PATH('') basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3 etc.) and the STUFF puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.

UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <, > or &, then my current solution will in fact encode those into &lt;, &gt;, and &amp;.

If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb
GO

ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO

In SQL Server 2008:

use mydb
go

exec sp_addrolemember db_datareader, MYUSER 
go
exec sp_addrolemember db_datawriter, MYUSER 
go

To also assign the ability to execute all Stored Procedures for a Database:

GRANT EXECUTE TO MYUSER;

To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

I don't know Sonar, but I suspect it's looking for a private constructor:

private FilePathHelper() {
    // No-op; won't be called
}

Otherwise the Java compiler will provide a public parameterless constructor, which you really don't want.

(You should also make the class final, although other classes wouldn't be able to extend it anyway due to it only having a private constructor.)

How to implement a FSM - Finite State Machine in Java

I design & implemented a simple finite state machine example with java.

IFiniteStateMachine: The public interface to manage the finite state machine
such as add new states to the finite state machine or transit to next states by
specific actions.

interface IFiniteStateMachine {
    void setStartState(IState startState);

    void setEndState(IState endState);

    void addState(IState startState, IState newState, Action action);

    void removeState(String targetStateDesc);

    IState getCurrentState();

    IState getStartState();

    IState getEndState();

    void transit(Action action);
}

IState: The public interface to get state related info
such as state name and mappings to connected states.

interface IState {
    // Returns the mapping for which one action will lead to another state
    Map<String, IState> getAdjacentStates();

    String getStateDesc();

    void addTransit(Action action, IState nextState);

    void removeTransit(String targetStateDesc);
}

Action: the class which will cause the transition of states.

public class Action {
    private String mActionName;

    public Action(String actionName) {
        mActionName = actionName;
    }

    String getActionName() {
        return mActionName;
    }

    @Override
    public String toString() {
        return mActionName;
    }

}

StateImpl: the implementation of IState. I applied data structure such as HashMap to keep Action-State mappings.

public class StateImpl implements IState {
    private HashMap<String, IState> mMapping = new HashMap<>();
    private String mStateName;

    public StateImpl(String stateName) {
        mStateName = stateName;
    }

    @Override
    public Map<String, IState> getAdjacentStates() {
        return mMapping;
    }

    @Override
    public String getStateDesc() {
        return mStateName;
    }

    @Override
    public void addTransit(Action action, IState state) {
        mMapping.put(action.toString(), state);
    }

    @Override
    public void removeTransit(String targetStateDesc) {
        // get action which directs to target state
        String targetAction = null;
        for (Map.Entry<String, IState> entry : mMapping.entrySet()) {
            IState state = entry.getValue();
            if (state.getStateDesc().equals(targetStateDesc)) {
                targetAction = entry.getKey();
            }
        }
        mMapping.remove(targetAction);
    }

}

FiniteStateMachineImpl: Implementation of IFiniteStateMachine. I use ArrayList to keep all the states.

public class FiniteStateMachineImpl implements IFiniteStateMachine {
    private IState mStartState;
    private IState mEndState;
    private IState mCurrentState;
    private ArrayList<IState> mAllStates = new ArrayList<>();
    private HashMap<String, ArrayList<IState>> mMapForAllStates = new HashMap<>();

    public FiniteStateMachineImpl(){}
    @Override
    public void setStartState(IState startState) {
        mStartState = startState;
        mCurrentState = startState;
        mAllStates.add(startState);
        // todo: might have some value
        mMapForAllStates.put(startState.getStateDesc(), new ArrayList<IState>());
    }

    @Override
    public void setEndState(IState endState) {
        mEndState = endState;
        mAllStates.add(endState);
        mMapForAllStates.put(endState.getStateDesc(), new ArrayList<IState>());
    }

    @Override
    public void addState(IState startState, IState newState, Action action) {
        // validate startState, newState and action

        // update mapping in finite state machine
        mAllStates.add(newState);
        final String startStateDesc = startState.getStateDesc();
        final String newStateDesc = newState.getStateDesc();
        mMapForAllStates.put(newStateDesc, new ArrayList<IState>());
        ArrayList<IState> adjacentStateList = null;
        if (mMapForAllStates.containsKey(startStateDesc)) {
            adjacentStateList = mMapForAllStates.get(startStateDesc);
            adjacentStateList.add(newState);
        } else {
            mAllStates.add(startState);
            adjacentStateList = new ArrayList<>();
            adjacentStateList.add(newState);
        }
        mMapForAllStates.put(startStateDesc, adjacentStateList);

        // update mapping in startState
        for (IState state : mAllStates) {
            boolean isStartState = state.getStateDesc().equals(startState.getStateDesc());
            if (isStartState) {
                startState.addTransit(action, newState);
            }
        }
    }

    @Override
    public void removeState(String targetStateDesc) {
        // validate state
        if (!mMapForAllStates.containsKey(targetStateDesc)) {
            throw new RuntimeException("Don't have state: " + targetStateDesc);
        } else {
            // remove from mapping
            mMapForAllStates.remove(targetStateDesc);
        }

        // update all state
        IState targetState = null;
        for (IState state : mAllStates) {
            if (state.getStateDesc().equals(targetStateDesc)) {
                targetState = state;
            } else {
                state.removeTransit(targetStateDesc);
            }
        }

        mAllStates.remove(targetState);

    }

    @Override
    public IState getCurrentState() {
        return mCurrentState;
    }

    @Override
    public void transit(Action action) {
        if (mCurrentState == null) {
            throw new RuntimeException("Please setup start state");
        }
        Map<String, IState> localMapping = mCurrentState.getAdjacentStates();
        if (localMapping.containsKey(action.toString())) {
            mCurrentState = localMapping.get(action.toString());
        } else {
            throw new RuntimeException("No action start from current state");
        }
    }

    @Override
    public IState getStartState() {
        return mStartState;
    }

    @Override
    public IState getEndState() {
        return mEndState;
    }
}

example:

public class example {

    public static void main(String[] args) {
        System.out.println("Finite state machine!!!");
        IState startState = new StateImpl("start");
        IState endState = new StateImpl("end");
        IFiniteStateMachine fsm = new FiniteStateMachineImpl();
        fsm.setStartState(startState);
        fsm.setEndState(endState);
        IState middle1 = new StateImpl("middle1");
        middle1.addTransit(new Action("path1"), endState);
        fsm.addState(startState, middle1, new Action("path1"));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.transit(new Action(("path1")));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.addState(middle1, endState, new Action("path1-end"));
        fsm.transit(new Action(("path1-end")));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.addState(endState, middle1, new Action("path1-end"));
    }

}

Full example on Github

How to create an empty DataFrame with a specified schema?

As of Spark 2.0.0, you can do the following.

Case Class

Let's define a Person case class:

scala> case class Person(id: Int, name: String)
defined class Person

Import spark SparkSession implicit Encoders:

scala> import spark.implicits._
import spark.implicits._

And use SparkSession to create an empty Dataset[Person]:

scala> spark.emptyDataset[Person]
res0: org.apache.spark.sql.Dataset[Person] = [id: int, name: string]

Schema DSL

You could also use a Schema "DSL" (see Support functions for DataFrames in org.apache.spark.sql.ColumnName).

scala> val id = $"id".int
id: org.apache.spark.sql.types.StructField = StructField(id,IntegerType,true)

scala> val name = $"name".string
name: org.apache.spark.sql.types.StructField = StructField(name,StringType,true)

scala> import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StructType

scala> val mySchema = StructType(id :: name :: Nil)
mySchema: org.apache.spark.sql.types.StructType = StructType(StructField(id,IntegerType,true), StructField(name,StringType,true))

scala> import org.apache.spark.sql.Row
import org.apache.spark.sql.Row

scala> val emptyDF = spark.createDataFrame(sc.emptyRDD[Row], mySchema)
emptyDF: org.apache.spark.sql.DataFrame = [id: int, name: string]

scala> emptyDF.printSchema
root
 |-- id: integer (nullable = true)
 |-- name: string (nullable = true)

Two way sync with rsync

I'm now using SparkleShare https://www.sparkleshare.org/

works on mac, linux and windows.

"java.lang.OutOfMemoryError : unable to create new native Thread"

I encountered same issue during the load test, the reason is because of JVM is unable to create a new Java thread further. Below is the JVM source code

if (native_thread->osthread() == NULL) {    
// No one should hold a reference to the 'native_thread'.    
    delete native_thread;   
if (JvmtiExport::should_post_resource_exhausted()) {      
    JvmtiExport::post_resource_exhausted(        
        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 
        JVMTI_RESOURCE_EXHAUSTED_THREADS, 
        "unable to create new native thread");    
    } THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "unable to create new native thread");  
} Thread::start(native_thread);`

Root cause : JVM throws this exception when JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR (resources exhausted (means memory exhausted) ) or JVMTI_RESOURCE_EXHAUSTED_THREADS (Threads exhausted).

In my case Jboss is creating too many threads , to serve the request, but all the threads are blocked . Because of this, JVM is exhausted with threads as well with memory (each thread holds memory , which is not released , because each thread is blocked).

Analyzed the java thread dumps observed nearly 61K threads are blocked by one of our method, which is causing this issue . Below is the portion of Thread dump

"SimpleAsyncTaskExecutor-16562" #38070 prio=5 os_prio=0 tid=0x00007f9985440000 nid=0x2ca6 waiting for monitor entry [0x00007f9d58c2d000]
   java.lang.Thread.State: BLOCKED (on object monitor)

Using two values for one switch case statement

you can do like:

case text1:
case text4: {
            //blah
            break;
}

How to turn off the Eclipse code formatter for certain sections of Java code?

The phantom comments, adding // where you want new lines, are great!

  1. The @formatter: off adds a reference from the code to the editor. The code should, in my opinion, never have such references.

  2. The phantom comments (//) will work regardless of the formatting tool used. Regardless of Eclipse or InteliJ or whatever editor you use. This even works with the very nice Google Java Format

  3. The phantom comments (//) will work all over your application. If you also have Javascript and perhaps use something like JSBeautifier. You can have similar code style also in the Javascript.

  4. Actually, you probably DO want formatting right? You want to remove mixed tab/space and trailing spaces. You want to indent the lines according to the code standard. What you DONT want is a long line. That, and only that, is what the phantom comment gives you!

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

How do I get the total Json record count using JQuery?

Your json isn't an array, it hasn't length property. You must change your data return or the way you get your data count.

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

Check if a JavaScript string is a URL

This function disallows localhost and only allows URLs for web pages (ie, only allows http or https protocol).

It also only allows safe characters as defined here: https://www.urlencoder.io/learn/

function isValidWebUrl(url) {
   let regEx = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
   return regEx.test(url);
}

php - push array into array - key issue

first convert your array too JSON

while($query->fetch()){
   $col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}

then vonvert back it to array

foreach($col as &$array){
   $array = json_decode($array,true);
}

good luck

Disable/Enable button in Excel/VBA

The following works for me (Excel 2010)

Dim b1 As Button

Set b1 = ActiveSheet.Buttons("Button 1")

b1.Font.ColorIndex = 15
b1.Enabled = False
Application.Cursor = xlWait
Call aLongAction
b1.Enabled = True
b1.Font.ColorIndex = 1
Application.Cursor = xlDefault

Be aware that .enabled = False does not gray out a button.

The font color has to be set explicitely to get it grayed.

Disable clipboard prompt in Excel VBA on workbook close

If I may add one more solution: you can simply cancel the clipboard with this command:

Application.CutCopyMode = False

What is getattr() exactly and how do I use it?

It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr

class Person:
    age = 23
    name = "Adam"

person = Person()
print('The age is:', getattr(person, "age"))
print('The age is:', person.age)

The age is: 23

The age is: 23

class Person:
    age = 23
    name = "Adam"

person = Person()

# when default value is provided
print('The sex is:', getattr(person, 'sex', 'Male'))

# when no default value is provided
print('The sex is:', getattr(person, 'sex'))

The sex is: Male

AttributeError: 'Person' object has no attribute 'sex'

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

How to find list intersection?

a = [1,2,3,4,5]
b = [1,3,5,6]
c = list(set(a).intersection(set(b)))

Should work like a dream. And, if you can, use sets instead of lists to avoid all this type changing!

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

Add ArrayList to another ArrayList in java

Then you need a ArrayList of ArrayLists:

ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();
nodes.add(nodeList);

Note that NodeList has been changed to nodeList. In Java Naming Conventions variables start with a lower case. Classes start with an upper case.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

I think you can create a simple SQL query:

$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);

and then you can use it normally.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Until I get a better option, this is the most "bootstrappy" answer I can work out:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/

I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less file:

in _layout.cshtml master page

  • Move footer outside the body-content container
  • Use boostrap's navbar-fixed-bottom on the footer
  • Drop the <hr/> before the footer (as now redundant)

Relevant page HTML:

<div class="container-fluid body-content">
    @RenderBody()
</div>
<footer class="navbar-fixed-bottom">
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>

In Site.less

  • Set HTML and BODY heights to 100%
  • Set BODY overflow to hidden
  • Set body-content div position to absolute
  • Set body-content div top to @navbar-height instead of hard-wiring value
  • Set body-content div bottom to 30px.
  • Set body-content div left and right to 0
  • Set body-content div overflow-y to auto

Site.less

html {
    height: 100%;

    body {
        height: 100%;
        overflow: hidden;

        .container-fluid.body-content {
            position: absolute;
            top: @navbar-height;
            bottom: 30px;
            right: 0;
            left: 0;
            overflow-y: auto;
        }
    }
}

The remaining problem is there seems to be no defining variable for the footer height in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.

In C#, what is the difference between public, private, protected, and having no access modifier?

Hmm.

See here: Access Modifiers.

In a nutshell:

Public gives the method or type complete visibility from other types/classes.

Private allows only the type containing the private method/variable access to the private method/variable (note that nested classes also have access to the containing classes private methods/variables).

Protected is similar to private except derived classes can also access protected methods.

"Nothing" is VB.NET's equivalent to null. Although if you're referring to "nothing" meaning "no access modifier", then it depends, although a very rough rule of thumb (certainly in C#) is that if you don't explicitly specify an access modifier, the method/variable declaration is usually as restricted as it can be. i.e.

public class MyClass
{
    string s = "";
}

is effectively the same as:

public class MyClass
{
    private string s = "";
}

The linked MSDN article will offer a fully description when there's no access modifier explicitly specified.

Custom alert and confirm box in jquery

jQuery UI has it's own elements, but jQuery alone hasn't.

http://jqueryui.com/dialog/

Working example:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


</body>
</html>

Cancel a UIView animation?

The way I do it is to create a new animation to your end point. Set a very short duration and make sure you use the +setAnimationBeginsFromCurrentState: method to start from the current state. When you set it to YES, the current animation is cut short. Looks something like this:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.1];
[UIView setAnimationCurve: UIViewAnimationCurveLinear];
// other animation properties

// set view properties

[UIView commitAnimations];

IsNull function in DB2 SQL?

I'm not familiar with DB2, but have you tried COALESCE?

ie:


SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

How to print_r $_POST array?

$_POST is already an array, so you don't need to wrap array() around it.

Try this instead:

<?php 

 for ($i=0;$i<count($_POST['id']);$i++) {

  echo "<p>".$_POST['id'][$i]."</p>";
  echo "<p>".$_POST['value'][$i]."</p>";
  echo "<hr />";

} 

 ?>

NOTE: This works because your id and value arrays are symmetrical. If they had different numbers of elements then you'd need to take a different approach.

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

How to test if a DataSet is empty?

If I understand correctly, this should work for you

if (ds.Tables[0].Rows.Count == 0)
{
    //
}

Efficiently convert rows to columns in sql server

There are several ways that you can transform data from multiple rows into columns.

Using PIVOT

In SQL Server you can use the PIVOT function to transform the data from rows to columns:

select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;

See Demo.

Pivot with unknown number of columnnames

If you have an unknown number of columnnames that you want to transpose, then you can use dynamic SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) 
                    from yourtable
                    group by ColumnName, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
             (
                select value, ColumnName
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p '

exec sp_executesql @query;

See Demo.

Using an aggregate function

If you do not want to use the PIVOT function, then you can use an aggregate function with a CASE expression:

select
  max(case when columnname = 'FirstName' then value end) Firstname,
  max(case when columnname = 'Amount' then value end) Amount,
  max(case when columnname = 'PostalCode' then value end) PostalCode,
  max(case when columnname = 'LastName' then value end) LastName,
  max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable

See Demo.

Using multiple joins

This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:

select fn.value as FirstName,
  a.value as Amount,
  pc.value as PostalCode,
  ln.value as LastName,
  an.value as AccountNumber
from yourtable fn
left join yourtable a
  on fn.somecol = a.somecol
  and a.columnname = 'Amount'
left join yourtable pc
  on fn.somecol = pc.somecol
  and pc.columnname = 'PostalCode'
left join yourtable ln
  on fn.somecol = ln.somecol
  and ln.columnname = 'LastName'
left join yourtable an
  on fn.somecol = an.somecol
  and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'

Couldn't connect to server 127.0.0.1:27017

Did you run mongod before running mongo?

I followed installation instructions for mongodb from http://docs.mongodb.org/manual/tutorial/install-mongodb-on-os-x/ and I had the same error as you only when I ran mongo before actually running the mongo process with mongod. I thought installing mongodb would also launch it but you need to launch it manually with mongod before you do anything else that needs mongodb.

Cannot find R.layout.activity_main

This is happening due to resources are not loading properly and the similar issue can occur any view also so Below are some technics which you can use to remove this error:-

  • Clean your project, Build -> clean Project
  • Rebuild project, Build -> Rebuild Project
  • Open manifest and check if there's any resource missing
  • Check-in layout to particular id if missing add it
  • If the above steps did not work then restart android studio with invalidating the cache.

Note: In the above-mentioned steps, the last step will work for this issue for sure.

Valid characters of a hostname?

A "name" (Net, Host, Gateway, or Domain name) is a text string up to 24 characters drawn from the alphabet (A-Z), digits (0-9), minus sign (-), and period (.). Note that periods are only allowed when they serve to delimit components of "domain style names". (See RFC-921, "Domain Name System Implementation Schedule", for background). No blank or space characters are permitted as part of a name. No distinction is made between upper and lower case. The first character must be an alpha character. The last character must not be a minus sign or period. A host which serves as a GATEWAY should have "-GATEWAY" or "-GW" as part of its name. Hosts which do not serve as Internet gateways should not use "-GATEWAY" and "-GW" as part of their names. A host which is a TAC should have "-TAC" as the last part of its host name, if it is a DoD host. Single character names or nicknames are not allowed.

This is provided in http://support.microsoft.com/kb/149044

How do I tell if an object is a Promise?

Update: This is no longer the best answer. Please vote up my other answer instead.

obj instanceof Promise

should do it. Note that this may only work reliably with native es6 promises.

If you're using a shim, a promise library or anything else pretending to be promise-like, then it may be more appropriate to test for a "thenable" (anything with a .then method), as shown in other answers here.

How to enable SOAP on CentOS

The yum install php-soap command will install the Soap module for php 5.x

For installing the correct version for your environment I recommend to create a file info.php and put this code: <?php echo phpinfo(); ?>

In the header you'll see the version you're using:

enter image description here

Now that you know the correct version you can run this command: yum search php-soap

This command will return the avaliable versions:

php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol

Now you just need to choose the correct module to your php version.

For this example, you should run this command php72-php-soap.x86_64

Change the default base url for axios

From axios docs you have baseURL and url

baseURL will be prepended to url when making requests. So you can define baseURL as http://127.0.0.1:8000 and make your requests to /url

 // `url` is the server URL that will be used for the request
 url: '/user',

 // `baseURL` will be prepended to `url` unless `url` is absolute.
 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
 // to methods of that instance.
 baseURL: 'https://some-domain.com/api/',

How to change font-color for disabled input?

You can use readonly instead. Following would do the trick for you.

<input type="text" class="details-dialog" style="background-color: #bbbbbb" readonly>

But you need to note the following. Depends on your business requirement, you can use it.

A readonly element is just not editable, but gets sent when the according form submits. A disabled element isn't editable and isn't sent on submit.

What does the 'L' in front a string mean in C++?

It means that it is a wide character, wchar_t.

Similar to 1L being a long value.

How to add a ListView to a Column in Flutter?

I have SingleChildScrollView as a parent, and one Column Widget and then List View Widget as last child.

Adding these properties in List View Worked for me.

  physics: NeverScrollableScrollPhysics(),
  shrinkWrap: true,
  scrollDirection: Axis.vertical,

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

I suffered alot trying to find a solution to it and finally I found the solution by first setting the jre path to system variables by navigating to::

control panel > System and Security > System > Advanced system settings 

Under System variables click on new

Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin

Where Variable value should be the path to your JDK's bin folder.

Then open command prompt and Change directory to the same JDK's bin folder like this

C:\Program Files (x86)\Java\jre1.8.0_171\bin 

then copy and paste the code below in cmd

keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android   

Locate the nginx.conf file my nginx is actually using

Running nginx -t through your commandline will issue out a test and append the output with the filepath to the configuration file (with either an error or success message).

c++ and opencv get and set pixel color to Mat

I would not use .at for performance reasons.

Define a struct:

//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
    uchar blue;
    uchar green;
    uchar red;  };

And then use it like this on your cv::Mat image:

RGB& rgb = image.ptr<RGB>(y)[x];

image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y

Converting a list to a set changes element order

In Python 3.6, set() now should keep the order, but there is another solution for Python 2 and 3:

>>> x = [1, 2, 20, 6, 210]
>>> sorted(set(x), key=x.index)
[1, 2, 20, 6, 210]

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

Adding to what David Whittaker posted, I have created a query that generates the complete table and columns alter statement that will convert each table. It may be a good idea to run

SET SESSION group_concat_max_len = 100000;

first to make sure your group concat doesn't go over the very small limit as seen here.

     SELECT a.table_name, concat('ALTER TABLE ', a.table_schema, '.', a.table_name, ' DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci, ',
        group_concat(distinct(concat(' MODIFY ',  column_name, ' ', column_type, ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ', if (is_nullable = 'NO', ' NOT', ''), ' NULL ',
        if (COLUMN_DEFAULT is not null, CONCAT(' DEFAULT \'', COLUMN_DEFAULT, '\''), ''), if (EXTRA != '', CONCAT(' ', EXTRA), '')))), ';') as alter_statement
    FROM information_schema.columns a
    INNER JOIN INFORMATION_SCHEMA.TABLES b ON a.TABLE_CATALOG = b.TABLE_CATALOG
        AND a.TABLE_SCHEMA = b.TABLE_SCHEMA
        AND a.TABLE_NAME = b.TABLE_NAME
        AND b.table_type != 'view'
    WHERE a.table_schema = ? and (collation_name = 'latin1_swedish_ci' or collation_name = 'utf8mb4_general_ci')
    GROUP BY table_name;

A difference here between the previous answer is it was using utf8 instead of ut8mb4 and using t1.data_type with t1.CHARACTER_MAXIMUM_LENGTH didn't work for enums. Also, my query excludes views since those will have to altered separately.

I simply used a Perl script to return all these alters as an array and iterated over them, fixed the columns that were too long (generally they were varchar(256) when the data generally only had 20 characters in them so that was an easy fix).

I found some data was corrupted when altering from latin1 -> utf8mb4. It appeared to be utf8 encoded latin1 characters in columns would get goofed in the conversion. I simply held data from the columns I knew was going to be an issue in memory from before and after the alter and compared them and generated update statements to fix the data.

BitBucket - download source as ZIP

In Bitbucket Server you can do a download by clicking on ... next to the branch and then Download

Bitbucket Server download

For more info see Download an archive from Bitbucket Server

Android: I lost my android key store, what should I do?

I want to refine this a little bit because down-votes indicate to me that people don't understand that these suggestions are like "last hope" approach for someone who got into the state described in the question.

Check your console input history and/or ant scripts you have been using if you have them. Keep in mind that the console history will not be saved if you were promoted for password but if you entered it within for example signing command you can find it.

You mentioned you have a zip with a password in which your certificate file is stored, you could try just brute force opening that with many tools available. People will say "Yea but what if you used strong password, you should bla,bla,bla..." Unfortunately in that case tough-luck. But people are people and they sometimes use simple passwords. For you any tool that can provide dictionary attacks in which you can enter your own words and set them to some passwords you suspect might help you. Also if password is short enough with today CPUs even regular brute force guessing might work since your zip file does not have any limitation on number of guesses so you will not get blocked as if you tried to brute force some account on a website.

MySQL: selecting rows where a column is null

I had the same issue when converting databases from Access to MySQL (using vb.net to communicate with the database).

I needed to assess if a field (field type varchar(1)) was null.

This statement worked for my scenario:

SELECT * FROM [table name] WHERE [field name] = ''

How to add,set and get Header in request of HttpClient?

On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html

You have something like this:

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.

As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline and Connect-MsolService, you will need to install the following applications (64-bit only):

  1. Applicable Operating Systems: Windows 7 to 10
    Name: "Microsoft Online Services Sign-in Assistant for IT Professionals RTW"
    Version: 7.250.4556.0 (latest)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=41950
    Installer file name: msoidcli_64.msi
  2. Applicable Operating Systems: Windows 7 to 10
    Name: "Windows Azure Active Directory Module for Windows PowerShell"
    Version: Unknown but the latest installer file's SHA-256 hash is D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
    Installer URL: https://technet.microsoft.com/en-us/library/dn975125.aspx
    Installer file name: AdministrationConfig-en.msi
  3. Applicable Operating Systems: Windows 7 only
    Name: "Windows PowerShell 3.0"
    Version: 3.0 (later versions will probably work too)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=34595
    Installer file name: Windows6.1-KB2506143-x64.msu

 

enter image description here enter image description here enter image description here

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

I got this exception because I was trying to make a Toast popup from a background thread.
Toast needs an Activity to push to the user interface and threads don't have that.
So one workaround is to give the thread a link to the parent Activity and Toast to that.

Put this code in the thread where you want to send a Toast message:

parent.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(parent.getBaseContext(), "Hello", Toast.LENGTH_LONG).show();
    }
});

Keep a link to the parent Activity in the background thread that created this thread. Use parent variable in your thread class:

private static YourActivity parent;

When you create the thread, pass the parent Activity as a parameter through the constructor like this:

public YourBackgroundThread(YourActivity parent) {
    this.parent = parent;
}

Now the background thread can push Toast messages to the screen.

Can "git pull --all" update all my local branches?

It can be done using below script... It will first fetch all branches and checkout one by one and update by itself.

#!/bin/bash
git branch -r | grep -v '\->' | while read remote; do git branch --track 
"${remote#origin/}" "$remote"; done

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
branch_name=$(git branch | awk '{print $1" "}' | grep -v '*' | xargs)
for branch in $branch_name; do
   git checkout "$branch" || exit 1
   git rebase "origin/$branch" || exit 1
   git pull origin $branch|| exit 1
done
git checkout "$CURRENT" || exit 1
git pull || exit 1

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

When a assembly' s AssemblyVersion is changed, If it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load! If it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory.

Laravel 5 – Remove Public from URL

BEST Approach: I will not recommend removing public, instead on local computer create a virtual host point to public directory and on remote hosting change public to public_html and point your domain to this directory. Reason, your whole laravel code will be secure because its one level down to your public directory :)

METHOD 1:

I just rename server.php to index.php and it works

METHOD 2:

This work well for all laravel version...

Here is my Directory Structure,

/laravel/
... app
... bootstrap
... public
... etc

Follow these easy steps

  1. move all files from public directory to root /laravel/
  2. now, no need of public directory, so optionally you can remove it now
  3. now open index.php and make following replacements

require DIR.'/../bootstrap/autoload.php';

to

require DIR.'/bootstrap/autoload.php';

and

$app = require_once DIR.'/../bootstrap/start.php';

to

$app = require_once DIR.'/bootstrap/start.php';

  1. now open bootstrap/paths.php and change public directory path:

'public' => DIR.'/../public',

to

'public' => DIR.'/..',

and that's it, now try http:// localhost/laravel/

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

  1. Update Maven Project and check the option "Force update of Snapshots/Releases", it will remove errors.
  2. If not, Maven clean and install the Project.
  3. Still the error isn't removed, repeat step 1.

It worked for me :)

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

Is there a function in python to split a word into a list?

Abuse of the rules, same result: (x for x in 'Word to split')

Actually an iterator, not a list. But it's likely you won't really care.

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

org.postgresql.util.PSQLException: FATAL: sorry, too many clients already

The offending lines are the following:

MaxConnections=90
InitialConnections=80

You can increase the values to allow more connections.

How to style the menu items on an Android action bar

My guess is that you have to also style the views that are generated from the menu information in your onCreateOptionsMenu(). The styling you applied so far is working, but I doubt that the menu items, when rendered with text use a style that is the same as the title part of the ActionBar.

You may want to look at Menu.getActionView() to get the view for the menu action and then adjust it accordingly.

Using a SELECT statement within a WHERE clause

It's not bad practice at all. They are usually referred as SUBQUERY, SUBSELECT or NESTED QUERY.

It's a relatively expensive operation, but it's quite common to encounter a lot of subqueries when dealing with databases since it's the only way to perform certain kind of operations on data.

runOnUiThread in fragment

Try this: getActivity().runOnUiThread(new Runnable...

It's because:

1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.

2) Fragment doesn't have runOnUiThread.

However, Activity does.

Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:

// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());

// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.

EDIT: @rciovati is right, you are in onPostExecute, that's already on the main thread.

Jersey stopped working with InjectionManagerFactory not found

The only way I could solve it was via:

org.glassfish.jersey.core jersey-server ${jersey-2-version}

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-common</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>${jersey-2-version}</version>
</dependency>

So, only if I added jersey-container-servlet and jersey-hk2 would it run without errors

getting the reason why websockets closed with close code 1006

Close Code 1006 is a special code that means the connection was closed abnormally (locally) by the browser implementation.

If your browser client reports close code 1006, then you should be looking at the websocket.onerror(evt) event for details.

However, Chrome will rarely report any close code 1006 reasons to the Javascript side. This is likely due to client security rules in the WebSocket spec to prevent abusing WebSocket. (such as using it to scan for open ports on a destination server, or for generating lots of connections for a denial-of-service attack).

Note that Chrome will often report a close code 1006 if there is an error during the HTTP Upgrade to Websocket (this is the step before a WebSocket is technically "connected"). For reasons such as bad authentication or authorization, or bad protocol use (such as requesting a subprotocol, but the server itself doesn't support that same subprotocol), or even an attempt at talking to a server location that isn't a WebSocket (such as attempting to connect to ws://images.google.com/)

Fundamentally, if you see a close code 1006, you have a very low level error with WebSocket itself (similar to "Unable to Open File" or "Socket Error"), not really meant for the user, as it points to a low level issue with your code and implementation. Fix your low level issues, and then when you are connected, you can then include more reasonable error codes. You can accomplish this in terms of scope or severity in your project. Example: info and warning level are part of your project's specific protocol, and don't cause the connection to terminate. With severe or fatal messages reporting also using your project's protocol to convey as much detail as you want, and then closing the connection using the limited abilities of the WebSocket close flow.

Be aware that WebSocket close codes are very strictly defined, and the close reason phrase/message cannot exceed 123 characters in length (this is an intentional WebSocket limitation).

But not all is lost, if you are just wanting this information for debugging reasons, the detail of the closure, and its underlying reason is often reported with a fair amount of detail in Chrome's Javascript console.

Python requests library how to pass Authorization header with single token

I was looking for something similar and came across this. It looks like in the first option you mentioned

r = requests.get('<MY_URI>', auth=('<MY_TOKEN>'))

"auth" takes two parameters: username and password, so the actual statement should be

r=requests.get('<MY_URI>', auth=('<YOUR_USERNAME>', '<YOUR_PASSWORD>'))

In my case, there was no password, so I left the second parameter in auth field empty as shown below:

r=requests.get('<MY_URI', auth=('MY_USERNAME', ''))

Hope this helps somebody :)

Circle-Rectangle collision detection (intersection)

Here is the modfied code 100% working:

public static bool IsIntersected(PointF circle, float radius, RectangleF rectangle)
{
    var rectangleCenter = new PointF((rectangle.X +  rectangle.Width / 2),
                                     (rectangle.Y + rectangle.Height / 2));

    var w = rectangle.Width  / 2;
    var h = rectangle.Height / 2;

    var dx = Math.Abs(circle.X - rectangleCenter.X);
    var dy = Math.Abs(circle.Y - rectangleCenter.Y);

    if (dx > (radius + w) || dy > (radius + h)) return false;

    var circleDistance = new PointF
                             {
                                 X = Math.Abs(circle.X - rectangle.X - w),
                                 Y = Math.Abs(circle.Y - rectangle.Y - h)
                             };

    if (circleDistance.X <= (w))
    {
        return true;
    }

    if (circleDistance.Y <= (h))
    {
        return true;
    }

    var cornerDistanceSq = Math.Pow(circleDistance.X - w, 2) + 
                                    Math.Pow(circleDistance.Y - h, 2);

    return (cornerDistanceSq <= (Math.Pow(radius, 2)));
}

Bassam Alugili

Check if a string is html or not

zzzzBov's answer above is good, but it does not account for stray closing tags, like for example:

/<[a-z][\s\S]*>/i.test('foo </b> bar'); // false

A version that also catches closing tags could be this:

/<[a-z/][\s\S]*>/i.test('foo </b> bar'); // true

How can I create directory tree in C++/Linux?

Here is my example of code (it works for both Windows and Linux):

#include <iostream>
#include <string>
#include <sys/stat.h> // stat
#include <errno.h>    // errno, ENOENT, EEXIST
#if defined(_WIN32)
#include <direct.h>   // _mkdir
#endif

bool isDirExist(const std::string& path)
{
#if defined(_WIN32)
    struct _stat info;
    if (_stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & _S_IFDIR) != 0;
#else 
    struct stat info;
    if (stat(path.c_str(), &info) != 0)
    {
        return false;
    }
    return (info.st_mode & S_IFDIR) != 0;
#endif
}

bool makePath(const std::string& path)
{
#if defined(_WIN32)
    int ret = _mkdir(path.c_str());
#else
    mode_t mode = 0755;
    int ret = mkdir(path.c_str(), mode);
#endif
    if (ret == 0)
        return true;

    switch (errno)
    {
    case ENOENT:
        // parent didn't exist, try to create it
        {
            int pos = path.find_last_of('/');
            if (pos == std::string::npos)
#if defined(_WIN32)
                pos = path.find_last_of('\\');
            if (pos == std::string::npos)
#endif
                return false;
            if (!makePath( path.substr(0, pos) ))
                return false;
        }
        // now, try to create again
#if defined(_WIN32)
        return 0 == _mkdir(path.c_str());
#else 
        return 0 == mkdir(path.c_str(), mode);
#endif

    case EEXIST:
        // done!
        return isDirExist(path);

    default:
        return false;
    }
}

int main(int argc, char* ARGV[])
{
    for (int i=1; i<argc; i++)
    {
        std::cout << "creating " << ARGV[i] << " ... " << (makePath(ARGV[i]) ? "OK" : "failed") << std::endl;
    }
    return 0;
}

Usage:

$ makePath 1/2 folderA/folderB/folderC
creating 1/2 ... OK
creating folderA/folderB/folderC ... OK

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Just check if the request has a status code 200. So for example:

if status != 200:
    print("An error has occured. [Status code", status, "]")
else:
    data = response.json() #Only convert to Json when status is OK.
    if not data["elements"]:
        print("Empty JSON")
    else:
        "You can extract data here"

How to use MySQL DECIMAL?

There are correct solutions in the comments, but to summarize them into a single answer:

You have to use DECIMAL(6,4).

Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.

How to execute VBA Access module?

If you just want to run a function for testing purposes, you can use the Immediate Window in Access.

Press Ctrl + G in the VBA editor to open it.

Then you can run your functions like this:

  • ?YourFunction("parameter")
    (for functions with a return value - the return value is displayed in the Immediate Window)
  • YourSub "parameter"
    (for subs without a return value, or for functions when you don't care about the return value)
  • ?variable
    (to display the value of a variable)

How to completely uninstall Visual Studio 2010?

If I may give an answer to an old thread; You can use PC Decrapifier to select programs you want to uninstall. PC Decrapifier will uninstall them one by one for you so you don't have to click them all seperately.

This is very useful for removing all the 'junk' - like the SQL Database tools - Visual Studio leaves behind even when uninstalled.

How to insert a value that contains an apostrophe (single quote)?

use double quotation marks around the values.

insert into Person (First, Last) Values("Joe","O'Brien")

Entity Framework Provider type could not be loaded?

In my case I resolved the problem by installing SQL Server 2012 Developer Edition when I had previously installed SQL Server Express 2012 (x64). It seems that provided me with the missing dependency.

How to set a cell to NaN in a pandas dataframe

Most replies here need to import numpy as np

There is a built-in solution into pandas itself: pd.NA, to use like this:

df.replace('N/A', pd.NA)

git commit error: pathspec 'commit' did not match any file(s) known to git

In my case, the problem was I used wrong alias for git commit -m. I used gcalias which dit not meant git commit -m

What does $1 mean in Perl?

The $number variables contain the parts of the string that matched the capture groups ( ... ) in the pattern for your last regex match if the match was successful.

For example, take the following string:

$text = "the quick brown fox jumps over the lazy dog.";

After the statement

$text =~ m/ (b.+?) /;

$1 equals the text "brown".

Show/hide forms using buttons and JavaScript

If you have a container and two sub containers, you can do like this

jQuery

    $("#previousbutton").click(function() {
    $("#form_sub_container1").show();
    $("#form_sub_container2").hide(); })

    $("#nextbutton").click(function() {
    $("#form_container").find(":hidden").show().next();
    $("#form_sub_container1").hide();
})

HTML

     <div id="form_container">
            <div id="form_sub_container1" style="display: block;">
            </div>

            <div id="form_sub_container2" style="display: none;">
            </div>
     </div>

String delimiter in string.split method

Split uses regex, and the pipe char | has special meaning in regex, so you need to escape it. There are a few ways to do this, but here's the simplest:

String[] tokens = line.split("\\|\\|");

Reverse a comparator in Java 8

Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.

In result you get a easy reusable Class File, testable unit step and clear javadoc.

public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass a, MyClass b) throws Exception {
        return super.compare(a, b)*-1;
    }
}

Base64 encoding in SQL Server 2005 T-SQL

I did a script to convert an existing hash encoded in base64 to decimal, it may be useful:

SELECT LOWER(SUBSTRING(CONVERT(NVARCHAR(42), CAST( [COLUMN_NAME] as XML ).value('.','varbinary(max)'), 1), 3, 40)) from TABLE

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

It's not your specific case, but it's worth noting for anybody else that this error can occur if you try to reference some fields in a table that are not the whole primary key of that table. Obviously this is not allowed.

Install dependencies globally and locally using package.json

New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies section of your package.json. Anytime you use something from scripts in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.

For example:

npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally

Then in package.json:

// devDependencies has mocha and babel now

"scripts": {
  "test": "mocha",
  "build": "babel -d lib src",
  "prepublish": "babel -d lib src"
}

Then at your command prompt you can run:

npm run build # finds babel
npm test # finds mocha

npm publish # will run babel first

But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:

"scripts": {
  "preinstall": "npm i -g themodule"
}

So actually my npm install executes npm install again .. which is weird but seems to work.

Note: you might have issues if you are using the most common setup for npm where global Node package installs required sudo. One option is to change your npm configuration so this isn't necessary:

npm config set prefix ~/npm, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH to your ~/.bashrc.

Prevent Caching in ASP.NET MVC for specific actions using an attribute

You can use the built in cache attribute to prevent caching.

For .net Framework: [OutputCache(NoStore = true, Duration = 0)]

For .net Core: [ResponseCache(NoStore = true, Duration = 0)]

Be aware that it is impossible to force the browser to disable caching. The best you can do is provide suggestions that most browsers will honor, usually in the form of headers or meta tags. This decorator attribute will disable server caching and also add this header: Cache-Control: public, no-store, max-age=0. It does not add meta tags. If desired, those can be added manually in the view.

Additionally, JQuery and other client frameworks will attempt to trick the browser into not using it's cached version of a resource by adding stuff to the url, like a timestamp or GUID. This is effective in making the browser ask for the resource again but doesn't really prevent caching.

On a final note. You should be aware that resources can also be cached in between the server and client. ISP's, proxies, and other network devices also cache resources and they often use internal rules without looking at the actual resource. There isn't much you can do about these. The good news is that they typically cache for shorter time frames, like seconds or minutes.

Duplicate AssemblyVersion Attribute

I had the same error and it was underlining the Assembly Vesrion and Assembly File Version so reading Luqi answer I just added them as comments and the error was solved

// AssemblyVersion is the CLR version. Change this only when making breaking    changes
//[assembly: AssemblyVersion("3.1.*")]
// AssemblyFileVersion should ideally be changed with each build, and should help identify the origin of a build
//[assembly: AssemblyFileVersion("3.1.0.0")]

Test if a variable is a list or tuple

Document the argument as needing to be a sequence, and use it as a sequence. Don't check the type.

How do I turn off autocommit for a MySQL client?

You do this in 3 different ways:

  1. Before you do an INSERT, always issue a BEGIN; statement. This will turn off autocommits. You will need to do a COMMIT; once you want your data to be persisted in the database.

  2. Use autocommit=0; every time you instantiate a database connection.

  3. For a global setting, add a autocommit=0 variable in your my.cnf configuration file in MySQL.

store and retrieve a class object in shared preference

Do you need to retrieve the object even after the application shutting donw or just during it's running ?

You can store it into a database.
Or Simply create a custom Application class.

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter
    ...
}

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:name=".MyApplication">
        <activity ... />
        ...
    </application>
    ...
</manifest>

And then from every activities do :

((MyApplication) getApplication).getMyObject();

Not really the best way but it works.

How do I check if PHP is connected to a database already?

Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. He advocates a try/catch pattern with a reconnect in the catch. Here is the pseudo code he recommends:

function query_database(connection, sql, retries=1)
   while true
      try
         result=connection.execute(sql)
         return result
      catch InactiveConnectionException e
         if retries > 0 then
            retries = retries - 1
            connection.reconnect()
         else
            throw e
         end
      end
   end
end

Here is his full blog: https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-harmful/

What is Model in ModelAndView from Spring MVC?

It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.

So ...

   new ModelAndView(view, name, value);

is equivalent to:

   Map model = ...
   model.put(name, value);
   new ModelAndView(view, model);

Does not contain a definition for and no extension method accepting a first argument of type could be found

There are two cases in which this error is raised.

  1. You didn't declare the variable which is used
  2. You didn't create the instances of the class

Where does Git store files?

It will create your repository in the .git folder in the current directory.

Algorithm for Determining Tic Tac Toe Game Over

This is similar to Osama ALASSIRY's answer, but it trades constant-space and linear-time for linear-space and constant-time. That is, there's no looping after initialization.

Initialize a pair (0,0) for each row, each column, and the two diagonals (diagonal & anti-diagonal). These pairs represent the accumulated (sum,sum) of the pieces in the corresponding row, column, or diagonal, where

A piece from player A has value (1,0)
A piece from player B has value (0,1)

When a player places a piece, update the corresponding row pair, column pair, and diagonal pairs (if on the diagonals). If any newly updated row, column, or diagonal pair equals either (n,0) or (0,n) then either A or B won, respectively.

Asymptotic analysis:

O(1) time (per move)
O(n) space (overall)

For the memory use, you use 4*(n+1) integers.

two_elements*n_rows + two_elements*n_columns +
two_elements*two_diagonals = 4*n + 4 integers = 4(n+1) integers

Exercise: Can you see how to test for a draw in O(1) time per-move? If so, you can end the game early on a draw.

how to send a post request with a web browser

You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.

As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox

How do I Sort a Multidimensional Array in PHP

You can use array_multisort()

Try something like this:

foreach ($mdarray as $key => $row) {
    // replace 0 with the field's index/key
    $dates[$key]  = $row[0];
}

array_multisort($dates, SORT_DESC, $mdarray);

For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:

array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);

Where is android studio building my .apk file?

After compiling my code in Android Studio, I found it here:

~\MyApp_Name\app\build\outputs\apk\app-debug.apk

Add an element to an array in Swift

Use += and + operators :

extension Array {

}

func += <V> (inout left: [V], right: V) {
    left.append(right)
}

func + <V>(left: Array<V>, right: V) -> Array<V>
{
    var map = Array<V>()
    for (v) in left {
        map.append(v)
    }

    map.append(right)

    return map
}

then use :

var list = [AnyObject]()
list += "hello" 
list += ["hello", "world!"]
var list2 = list + "anything"

How to check if variable's type matches Type stored in a variable

In order to check if an object is compatible with a given type variable, instead of writing

u is t

you should write

typeof(t).IsInstanceOfType(u)

What is the argument for printf that formats a long?

On most platforms, long and int are the same size (32 bits). Still, it does have its own format specifier:

long n;
unsigned long un;
printf("%ld", n); // signed
printf("%lu", un); // unsigned

For 64 bits, you'd want a long long:

long long n;
unsigned long long un;
printf("%lld", n); // signed
printf("%llu", un); // unsigned

Oh, and of course, it's different in Windows:

printf("%l64d", n); // signed
printf("%l64u", un); // unsigned

Frequently, when I'm printing 64-bit values, I find it helpful to print them in hex (usually with numbers that big, they are pointers or bit fields).

unsigned long long n;
printf("0x%016llX", n); // "0x" followed by "0-padded", "16 char wide", "long long", "HEX with 0-9A-F"

will print:

0x00000000DEADBEEF

Btw, "long" doesn't mean that much anymore (on mainstream x64). "int" is the platform default int size, typically 32 bits. "long" is usually the same size. However, they have different portability semantics on older platforms (and modern embedded platforms!). "long long" is a 64-bit number and usually what people meant to use unless they really really knew what they were doing editing a piece of x-platform portable code. Even then, they probably would have used a macro instead to capture the semantic meaning of the type (eg uint64_t).

char c;       // 8 bits
short s;      // 16 bits
int i;        // 32 bits (on modern platforms)
long l;       // 32 bits
long long ll; // 64 bits 

Back in the day, "int" was 16 bits. You'd think it would now be 64 bits, but no, that would have caused insane portability issues. Of course, even this is a simplification of the arcane and history-rich truth. See wiki:Integer

What does this symbol mean in JavaScript?

See the documentation on MDN about expressions and operators and statements.

Basic keywords and general expressions

this keyword:

var x = function() vs. function x() — Function declaration syntax

(function(){})() — IIFE (Immediately Invoked Function Expression)

someFunction()() — Functions which return other functions

=> — Equal sign, greater than: arrow function expression syntax

|> — Pipe, greater than: Pipeline operator

function*, yield, yield* — Star after function or yield: generator functions

[], Array() — Square brackets: array notation

If the square brackets appear on the left side of an assignment ([a] = ...), or inside a function's parameters, it's a destructuring assignment.

{key: value} — Curly brackets: object literal syntax (not to be confused with blocks)

If the curly brackets appear on the left side of an assignment ({ a } = ...) or inside a function's parameters, it's a destructuring assignment.

`${}` — Backticks, dollar sign with curly brackets: template literals

// — Slashes: regular expression literals

$ — Dollar sign in regex replace patterns: $$, $&, $`, $', $n

() — Parentheses: grouping operator


Property-related expressions

obj.prop, obj[prop], obj["prop"] — Square brackets or dot: property accessors

?., ?.[], ?.() — Question mark, dot: optional chaining operator

:: — Double colon: bind operator

new operator

...iter — Three dots: spread syntax; rest parameters


Increment and decrement

++, -- — Double plus or minus: pre- / post-increment / -decrement operators


Unary and binary (arithmetic, logical, bitwise) operators

delete operator

void operator

+, - — Plus and minus: addition or concatenation, and subtraction operators; unary sign operators

|, &, ^, ~ — Single pipe, ampersand, circumflex, tilde: bitwise OR, AND, XOR, & NOT operators

% — Percent sign: remainder operator

&&, ||, ! — Double ampersand, double pipe, exclamation point: logical operators

?? — Double question mark: nullish-coalescing operator

** — Double star: power operator (exponentiation)


Equality operators

==, === — Equal signs: equality operators

!=, !== — Exclamation point and equal signs: inequality operators


Bit shift operators

<<, >>, >>> — Two or three angle brackets: bit shift operators


Conditional operator

?:… — Question mark and colon: conditional (ternary) operator


Assignment operators

= — Equal sign: assignment operator

%= — Percent equals: remainder assignment

+= — Plus equals: addition assignment operator

&&=, ||=, ??= — Double ampersand, pipe, or question mark, followed by equal sign: logical assignments

Destructuring


Comma operator

, — Comma operator


Control flow

{} — Curly brackets: blocks (not to be confused with object literal syntax)

Declarations

var, let, const — Declaring variables


Label

label: — Colon: labels


# — Hash (number sign): Private methods or private fields

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

The following approach worked for me

  1. Navigate to your android SDK/tools folder in the terminal window (in case you didn't added the path for it)

  2. Make sure the virtual device you're planning to clean is powered off.

  3. Run the command "./emulator -wipe-data -avd YourAvdName" where YourAvdName is the name of your virtual android device

What is move semantics?

Move semantics are based on rvalue references.
An rvalue is a temporary object, which is going to be destroyed at the end of the expression. In current C++, rvalues only bind to const references. C++1x will allow non-const rvalue references, spelled T&&, which are references to an rvalue objects.
Since an rvalue is going to die at the end of an expression, you can steal its data. Instead of copying it into another object, you move its data into it.

class X {
public: 
  X(X&& rhs) // ctor taking an rvalue reference, so-called move-ctor
    : data_()
  {
     // since 'x' is an rvalue object, we can steal its data
     this->swap(std::move(rhs));
     // this will leave rhs with the empty data
  }
  void swap(X&& rhs);
  // ... 
};

// ...

X f();

X x = f(); // f() returns result as rvalue, so this calls move-ctor

In the above code, with old compilers the result of f() is copied into x using X's copy constructor. If your compiler supports move semantics and X has a move-constructor, then that is called instead. Since its rhs argument is an rvalue, we know it's not needed any longer and we can steal its value.
So the value is moved from the unnamed temporary returned from f() to x (while the data of x, initialized to an empty X, is moved into the temporary, which will get destroyed after the assignment).

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate

Invert "if" statement to reduce nesting

It's a matter of opinion.

My normal approach would be to avoid single line ifs, and returns in the middle of a method.

You wouldn't want lines like it suggests everywhere in your method but there is something to be said for checking a bunch of assumptions at the top of your method, and only doing your actual work if they all pass.

Are there inline functions in java?

Java does not provide a way to manually suggest that a method should be inlined. As @notnoop says in the comments, the inlining is typically done by the JVM at execution time.

Find the greatest number in a list of numbers

Use max()

>>> l = [1, 2, 5]
>>> max(l)
5
>>> 

Java: how do I initialize an array size if it's unknown?

If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

import java.util.Scanner;

public class ArrayModify {

    public static void main(String[] args) {
        int[] list;
        String st;
        String[] stNew;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
        st = scan.nextLine();
        stNew = st.split("\\s+");
        list = new int[stNew.length]; // Sets array size to 5

        for (int i = 0; i < stNew.length; i++){
            list[i] =  Integer.parseInt(stNew[i]);
            System.out.println("You Enterred: " + list[i]);
        }
    }
}

Java error - "invalid method declaration; return type required"

Every method (other than a constructor) must have a return type.

public double diameter(){...

Failed to load JavaHL Library

Try this:

  1. Select Window >> Preferences
  2. Expand Team >> SVN
  3. Under SVN interface set Client to SVNKit (Pure Java) SVNKit....

Selenium WebDriver and DropDown Boxes

I have to struggle to find how to achieve especial those who are new to this tool (like me)

C# code:

IWebElement ddl = ffDriver.FindElement(By.Id("ddlGoTo")); 
OpenQA.Selenium.Support.UI.SelectElement clickthis = new OpenQA.Selenium.Support.UI.SelectElement(ddl);
clickthis.SelectByText("Your Text");

hope this help others!

Question mark characters displaying within text, why is this?

Unicode or other character set characters falling through?

I have seen similar "strange" characters show up on sites I have worked on often when the text is copied from an email or some other document format (e.g. word) into a text editor. The editor can display the non ASCII characters but the browser can't. For the website, I would suggest looking up the HTML entity code for the character and inserting that instead ... or switch to more standard ones.

Convert an array into an ArrayList

This will give you a list.

List<Card> cardsList = Arrays.asList(hand);

If you want an arraylist, you can do

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));

Python/Django: log to console under runserver, log to file under Apache

You can configure logging in your settings.py file.

One example:

if DEBUG:
    # will output to your console
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
    )
else:
    # will output to logging file
    logging.basicConfig(
        level = logging.DEBUG,
        format = '%(asctime)s %(levelname)s %(message)s',
        filename = '/my_log_file.log',
        filemode = 'a'
    )

However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.

How to set up ES cluster?

Elastic Search 7 changed the configurations for cluster initialisation. What is important to note is the ES instances communicate internally using the Transport layer(TCP) and not the HTTP protocol which is normally used to perform ops on the indices. Below is sample config for 2 machines cluster.

cluster.name: cluster-new
node.name: node-1
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.211
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

Machine 2 config:-

cluster.name: cluster-new
node.name: node-2
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.212
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes: 
        - "node-1"
        - "node-2”

cluster.name: This has be same across all the machines that are going to be part of a cluster.

node.name : Identifier for the ES instance. Defaults to machine name if not given.

node.master: specifies whether this ES instance is going to be master or not

node.data: specifies whether this ES instance is going to be data node or not(hold data)

bootsrap.memory_lock: disable swapping.You can start the cluster without setting this flag. But its recommended to set the lock.More info: https://www.elastic.co/guide/en/elasticsearch/reference/master/setup-configuration-memory.html

network.host: 0.0.0.0 if you want to expose the ES instance over network. 0.0.0.0 is different from 127.0.0.1( aka localhost or loopback address). It means all IPv4 addresses on the machine. If machine has multiple ip addresses with a server listening on 0.0.0.0, the client can reach the machine from any of the IPv4 addresses.

http.port: port on which this ES instance will listen to for HTTP requests

transport.host: The IPv4 address of the host(this will be used to communicate with other ES instances running on different machines). More info: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-transport.html

transport.tcp.port: 9300 (the port where the machine will accept the tcp connections)

discovery.seed_hosts: This was changed in recent versions. Initialise all the IPv4 addresses with TCP port(important) of ES instances that are going to be part of this cluster. This is going to be same across all ES instances that are part of this cluster.

cluster.initial_master_nodes: node names(node.name) of the ES machines that are going to participate in master election.(Quorum based decision making :- https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-quorums.html#modules-discovery-quorums)

Java 8 forEach with index

There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:

int idx = 0;
for (Param p : params) query.bind(idx++, p);

Or the older style:

for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));

Could not find a part of the path ... bin\roslyn\csc.exe

Upgrading Microsoft.CodeDom.Providers.DotNetCompilerPlatform from 1.0.0 to 1.0.1 fixed this for me.

How to declare a global variable in php?

You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.

$foo = "New";
$closure = (function($bar) use ($foo) {
    echo "$foo $bar";
})("York");

demo | info

Recursively add the entire folder to a repository

I also had the same issue and I do not have .gitignore file. My problem was solved with the following way. This took all sub-directories and files.

git add <directory>/*

AngularJS sorting by property

It's pretty easy, just do it like this

$scope.props = [{order:"1"},{order:"5"},{order:"2"}]

ng-repeat="prop in props | orderBy:'order'"

Count number of 1's in binary representation

There's only one way I can think of to accomplish this task in O(1)... that is to 'cheat' and use a physical device (with linear or even parallel programming I think the limit is O(log(k)) where k represents the number of bytes of the number).

However you could very easily imagine a physical device that connects each bit an to output line with a 0/1 voltage. Then you could just electronically read of the total voltage on a 'summation' line in O(1). It would be quite easy to make this basic idea more elegant with some basic circuit elements to produce the output in whatever form you want (e.g. a binary encoded output), but the essential idea is the same and the electronic circuit would produce the correct output state in fixed time.

I imagine there are also possible quantum computing possibilities, but if we're allowed to do that, I would think a simple electronic circuit is the easier solution.

How can I reorder my divs using only CSS?

Little late to the party, but you can also do this:

<div style="height: 500px; width: 500px;">

<div class="bottom" style="height: 250px; width: 500px; background: red; margin-top: 250px;"></div>

<div class="top" style="height: 250px; width: 500px; background: blue; margin-top: -500px;"></div>

encrypt and decrypt md5

Hashes can not be decrypted check this out.

If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).

But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php

For Blowfish by crypt() function -

crypt('String', '$2a$07$twentytwocharactersalt$');

password_hash will be introduced in PHP 5.5.

$options = [
    'cost' => 7,
    'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);

Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.

How does functools partial do what it does?

In my opinion, it's a way to implement currying in python.

from functools import partial
def add(a,b):
    return a + b

def add2number(x,y,z):
    return x + y + z

if __name__ == "__main__":
    add2 = partial(add,2)
    print("result of add2 ",add2(1))
    add3 = partial(partial(add2number,1),2)
    print("result of add3",add3(1))

The result is 3 and 4.

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Here is the solution: You use Ctrl+Alt+Delete, open task manager and switch to tab services find VMWareHostd and right click to chose StopService. You can start xampp without error

How to declare a constant in Java

Anything that is static is in the class level. You don't have to create instance to access static fields/method. Static variable will be created once when class is loaded.

Instance variables are the variable associated with the object which means that instance variables are created for each object you create. All objects will have separate copy of instance variable for themselves.

In your case, when you declared it as static final, that is only one copy of variable. If you change it from multiple instance, the same variable would be updated (however, you have final variable so it cannot be updated).

In second case, the final int a is also constant , however it is created every time you create an instance of the class where that variable is declared.

Have a look on this Java tutorial for better understanding ,

How to set header and options in axios?

@user2950593 Your axios request is correct. You need to allow your custom headers on server side. If you have your api in php then this code will work for you.

header("Access-Control-Allow-Origin: *");   
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD");
header("Access-Control-Allow-Headers: Content-Type, header1");

Once you will allow your custom headers on server side, your axios requests will start working fine.

Download single files from GitHub

To download a file from a Github repo, use the 'curl' command with the link to the raw file.

curl https://raw.githubusercontent.com/user/repo/filename --output filename

Add the --output option followed by the new filename to download the raw file to the newly created file.

Installing Tomcat 7 as Service on Windows Server 2008

I just had the same issue and could only install tomcat7 as a serivce using the "32-bit/64-bit Windows Service Installer" version of tomcat:

http://tomcat.apache.org/download-70.cgi

Iterating on a file doesn't work the second time

Of course. That is normal and sane behaviour. Instead of closing and re-opening, you could rewind the file.

Error: Cannot find module 'webpack'

Nothing suggested above worked for me (including the NODE_PATH variable). I created a sym link of "node_modules" from my local folder to the global AppData(eg below) and it worked like charm.

C:\Users\mmoinuddin\AppData\Roaming\npm>mklink /D node_modules c:\essportreact\day1\node_modules
symbolic link created for node_modules <<===>> c:\essportreact\day1\node_modules
C:\essportreact\day1>webpack
Hash: 2a82a67f90f9aa05ab4a
Version: webpack 1.15.0

A quick and easy way to join array elements with a separator (the opposite of split) in Java

This options is fast and clear:

  public static String join(String separator, String... values) {
    StringBuilder sb = new StringBuilder(128);
    int end = 0;
    for (String s : values) {
      if (s != null) {
        sb.append(s);
        end = sb.length();
        sb.append(separator);
      }
    }
    return sb.substring(0, end);
  }

php REQUEST_URI

You can simply use $_GET especially if you know the othervar's name. If you want to be on the safe side, use if (isset ($_GET ['varname'])) to test for existence.

How to prevent a background process from being stopped after closing SSH client in Linux

On a Debian-based system (on the remote machine) Install:

sudo apt-get install tmux

Usage:

tmux

run commands you want

To rename session:

Ctrl+B then $

set Name

To exit session:

Ctrl+B then D

(this leaves the tmux session). Then, you can log out of SSH.

When you need to come back/check on it again, start up SSH, and enter

tmux attach session_name

It will take you back to your tmux session.

What is an unhandled promise rejection?

In my case was Promise with no reject neither resolve, because my Promise function threw an exception. This mistake cause UnhandledPromiseRejectionWarning message.

How add class='active' to html menu with php

The solution i'm using is as follows and allows you to set the active class per php page.

Give each of your menu items a unique class, i use .nav-x (nav-about, here).

<li class="nav-item nav-about"> <a class="nav-link" href="about.php">About</a> </li>

At the top of each page (about.php here):

<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>

Elsewhere (header.php / index.php):

<style>
<?php echo $activeClass; ?> {
    color: #fff !important;
}
</style>

Simply change the .nav-about > a per page, .nav-forum > a, for example.

If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.

How do I space out the child elements of a StackPanel?

Another nice approach can be seen here: http://blogs.microsoft.co.il/blogs/eladkatz/archive/2011/05/29/what-is-the-easiest-way-to-set-spacing-between-items-in-stackpanel.aspx Link is broken -> this is webarchive of this link.

It shows how to create an attached behavior, so that syntax like this would work:

<StackPanel local:MarginSetter.Margin="5">
   <TextBox Text="hello" />
   <Button Content="hello" />
   <Button Content="hello" />
</StackPanel>

This is the easiest & fastest way to set Margin to several children of a panel, even if they are not of the same type. (I.e. Buttons, TextBoxes, ComboBoxes, etc.)

Number of regex matches

#An example for counting matched groups
import re

pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"

res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4  
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

In Mac:

Kill process Terminal: kill <pid>

Find pid: Terminal: lsof -i:<port>

From Diego Pino answer

Recording video feed from an IP camera over a network

I haven't used it yet but I would take a look at http://www.zoneminder.com/ The documentation explains you can install it on a modest machine with linux and use IP cameras for remote recording.

Andrew

Any way to break if statement in PHP?

There exist command: goto

if(smth) {
   .....
   .....
   .....
   .....
   .....
   goto Area1;
   .....
   .....


}



Area1:
....your code here....

However, remember goto is not a recommended practice, because it makes the code to be formatted unusually.

How to install pandas from pip on windows cmd?

Since both pip nor python commands are not installed along Python in Windows, you will need to use the Windows alternative py, which is included by default when you installed Python. Then you have the option to specify a general or specific version number after the py command.

C:\> py      -m pip install pandas  %= one of Python on the system =%
C:\> py -2   -m pip install pandas  %= one of Python 2 on the system =%
C:\> py -2.7 -m pip install pandas  %= only for Python 2.7 =%
C:\> py -3   -m pip install pandas  %= one of Python 3 on the system =%
C:\> py -3.6 -m pip install pandas  %= only for Python 3.6 =%

Alternatively, in order to get pip to work without py -m part, you will need to add pip to the PATH environment variable.

C:\> setx PATH "%PATH%;C:\<path\to\python\folder>\Scripts"

Now you can run the following command as expected.

C:\> pip install pandas

Troubleshooting:


Problem:

connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

Solution:

This is caused by your SSL certificate is unable to verify the host server. You can add pypi.python.org to the trusted host or specify an alternative SSL certificate. For more information, please see this post. (Thanks to Anuj Varshney for suggesting this)

C:\> py -m pip install --trusted-host pypi.python.org pip pandas

Problem:

PermissionError: [WinError 5] Access is denied

Solution:

This is a caused by when you don't permission to modify the Python site-package folders. You can avoid this with one of the following methods:

  • Run Windows Command Prompt as administrator (thanks to DataGirl's suggestion) by:

    1. Windows-Key + R to open run
    2. type in cmd.exe in the search box
    3. CTRL + SHIFT + ENTER
    4. An alternative method for step 1-3 would be to manually locate cmd.exe, right click, then click Run as Administrator.
  • Run pip in user mode by adding --user option when installing with pip. Which typically install the package to the local %APPDATA% Python folder.

C:\> py -m pip install --user pandas
C:\> py -m venv c:\path\to\new\venv
C:\> <path\to\the\new\venv>\Scripts\activate.bat

Parse string to DateTime in C#

Try the following code

Month = Date = DateTime.Now.Month.ToString();   
Year = DateTime.Now.Year.ToString(); 
ViewBag.Today = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(Int32.Parse(Month)) + Year;

Access properties file programmatically with Spring?

Please use the below code in your spring configuration file to load the file from class path of your application

 <context:property-placeholder
    ignore-unresolvable="true" ignore-resource-not-found="false" location="classpath:property-file-name" />

moment.js get current time in milliseconds?

var timeArr = moment().format('x');

returns the Unix Millisecond Timestamp as per the format() documentation.

How do I evenly add space between a label and the input field regardless of length of text?

You can always use the 'pre' tag inside the label, and just enter the blank spaces in it, So you can always add the same or different number of spaces you require

<form>
<label>First Name :<pre>Here just enter number of spaces you want to use(I mean using spacebar to enter blank spaces)</pre>
<input type="text"></label>
<label>Last Name :<pre>Now Enter enter number of spaces to match above number of 
spaces</pre>
<input type="text"></label>
</form>

Hope you like my answer, It's a simple and efficient hack

How to remove constraints from my MySQL table?

Also nice, you can temporarily disable all foreign key checks from a mysql database: SET FOREIGN_KEY_CHECKS=0; And to enable it again: SET FOREIGN_KEY_CHECKS=1;

best way to preserve numpy arrays on disk

savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function:

f = file("tmp.bin","wb")
np.save(f,a)
np.save(f,b)
np.save(f,c)
f.close()

f = file("tmp.bin","rb")
aa = np.load(f)
bb = np.load(f)
cc = np.load(f)
f.close()

To save multiple arrays in one file, you just need to open the file first, and then save or load the arrays in sequence.

How do I check if a string is valid JSON in Python?

I would say parsing it is the only way you can really entirely tell. Exception will be raised by python's json.loads() function (almost certainly) if not the correct format. However, the the purposes of your example you can probably just check the first couple of non-whitespace characters...

I'm not familiar with the JSON that facebook sends back, but most JSON strings from web apps will start with a open square [ or curly { bracket. No images formats I know of start with those characters.

Conversely if you know what image formats might show up, you can check the start of the string for their signatures to identify images, and assume you have JSON if it's not an image.

Another simple hack to identify a graphic, rather than a text string, in the case you're looking for a graphic, is just to test for non-ASCII characters in the first couple of dozen characters of the string (assuming the JSON is ASCII).

How to create Haar Cascade (.xml file) to use in OpenCV?

If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.

http://note.sonots.com/SciSoftware/haartraining.html

And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.

http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

How to get the top 10 values in postgresql?

Seems you are looking for ORDER BY in DESCending order with LIMIT clause:

SELECT
 *
FROM
  scores
ORDER BY score DESC
LIMIT 10

Of course SELECT * could seriously affect performance, so use it with caution.

Cron job every three days

I am not a cron specialist, but how about:

0 */72 * * *

It will run every 72 hours non-interrupted.

https://crontab.guru/#0_/72___

Gray out image with CSS?

Considering filter:expression is a Microsoft extension to CSS, so it will only work in Internet Explorer. If you want to grey it out, I would recommend that you set it's opacity to 50% using a bit of javascript.

http://lyxus.net/mv would be a good place to start, because it discusses an opacity script that works with Firefox, Safari, KHTML, Internet Explorer and CSS3 capable browsers.

You might also want to give it a grey border.

How to extract numbers from a string and get an array of ints?

  StringBuffer sBuffer = new StringBuffer();
  Pattern p = Pattern.compile("[0-9]+.[0-9]*|[0-9]*.[0-9]+|[0-9]+");
  Matcher m = p.matcher(str);
  while (m.find()) {
    sBuffer.append(m.group());
  }
  return sBuffer.toString();

This is for extracting numbers retaining the decimal

Centering FontAwesome icons vertically and horizontally

I just managed how to center icons and and making them a container instead of putting them into one.

.fas {
    position: relative;
    color: #EEE;
    font-size: 16px;
}
.fas:before {
    position: absolute;
    left: calc(50% - .5em);
    top: calc(50% - .5em);
}
.fas.fa-icon {
    width: 60px;
    height: 60px;
    color: white;
    background-color: black;
}

How to make an array of arrays in Java

Like this:

String[][] arrays = { array1, array2, array3, array4, array5 };

or

String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };

(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)

How to connect PHP with Microsoft Access database

<?php
    $dbName = $_SERVER["DOCUMENT_ROOT"] . "products\products.mdb";
    if (!file_exists($dbName)) {
       die("Could not find database file.");
    }
    $db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");

A successful connection will allow SQL commands to be executed from PHP to read or write the database. If, however, you get the error message “PDOException Could not find driver” then it’s likely that the PDO ODBC driver is not installed. Use the phpinfo() function to check your installation for references to PDO.

If an entry for PDO ODBC is not present, you will need to ensure your installation includes the PDO extension and ODBC drivers. To do so on Windows, uncomment the line extension=php_pdo_odbc.dll in php.ini, restart Apache, and then try to connect to the database again.

With the driver installed, the output from phpinfo() should include information like this:https://www.diigo.com/item/image/5kc39/hdse

http://i.stack.imgur.com/Zwp2W.png

Assign keyboard shortcut to run procedure

The problem that I had with the above is that I wanted to associate a short cut key with a macro in an xlam which has no visible interface. I found that the folllowing worked

To associate a short cut key with a macro

In Excel (not VBA) on the Developer Tab click Macros - no macros will be shown Type the name of the Sub The Options button should then be enabled Click it Ctrl will be the default Hold down Shift and press the letter you want eg Shift and A will associate Ctrl-Shift-A with the Sub

How do you get the footer to stay at the bottom of a Web page?

The flex solutions worked for me as far as making the footer sticky, but unfortunately changing the body to use flex layout made some of our page layouts change, and not for the better. What finally worked for me was:

    jQuery(document).ready(function() {

    var fht = jQuery('footer').outerHeight(true);
    jQuery('main').css('min-height', "calc(92vh - " + fht + "px)");

});

I got this from ctf0's response at https://css-tricks.com/couple-takes-sticky-footer/

Best practice for localization and globalization of strings and labels

jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.

to know more about this take a look at the How to internationalize your pages using JQuery?

Tkinter: "Python may not be configured for Tk"

Under Arch/Manjaro just install the package tk:

sudo pacman -S tk

How to Store Historical Data

You can create a materialized/indexed views on the table. Based on your requirement you can do full or partial update of the views. Please see this to create mview and log. How to create materialized views in SQL Server?

Creation timestamp and last update timestamp with Hibernate and MySQL

Thanks everyone who helped. After doing some research myself (I'm the guy who asked the question), here is what I found to make sense most:

  • Database column type: the timezone-agnostic number of milliseconds since 1970 represented as decimal(20) because 2^64 has 20 digits and disk space is cheap; let's be straightforward. Also, I will use neither DEFAULT CURRENT_TIMESTAMP, nor triggers. I want no magic in the DB.

  • Java field type: long. The Unix timestamp is well supported across various libs, long has no Y2038 problems, timestamp arithmetic is fast and easy (mainly operator < and operator +, assuming no days/months/years are involved in the calculations). And, most importantly, both primitive longs and java.lang.Longs are immutable—effectively passed by value—unlike java.util.Dates; I'd be really pissed off to find something like foo.getLastUpdate().setTime(System.currentTimeMillis()) when debugging somebody else's code.

  • The ORM framework should be responsible for filling in the data automatically.

  • I haven't tested this yet, but only looking at the docs I assume that @Temporal will do the job; not sure about whether I might use @Version for this purpose. @PrePersist and @PreUpdate are good alternatives to control that manually. Adding that to the layer supertype (common base class) for all entities, is a cute idea provided that you really want timestamping for all of your entities.

Real time data graphing on a line chart with html5

You get the data from server, update your previously available datasetand then probably use one of the freely available libraries to draw the graph (eg: http://www.rgraph.net)

Things you might want to considering : If your chart is represents a state , get only the new data with xhr , update data on client and draw .

AddTransient, AddScoped and AddSingleton Services Differences

  • Singleton is a single instance for the lifetime of the application domain.
  • Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET.
  • Transient is a single instance per code request.

Normally the code request should be made through a constructor parameter, as in

public MyConsumingClass(IDependency dependency)

I wanted to point out in @akazemis's answer that "services" in the context of DI does not imply RESTful services; services are implementations of dependencies that provide functionality.

C++ [Error] no matching function for call to

to add to John's answer:

what you want to pass to the shuffle function is a deck of cards from the class deckOfCards that you've declared in main; however, the deck of cards or vector<Card> deck that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:

class deckOfCards
{
    private:
        vector<Card> deck;

    public:
        deckOfCards();
        static int count;
        static int next;
        void shuffle(vector<Card>& deck);
        Card dealCard();
        bool moreCards();
        vector<Card>& getDeck() {   //GETTER
            return deck;
        }
};

this will in turn allow you to call your shuffle function from main like this:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck

however, you have more problems, specifically when calling cout. first, you're calling the dealCard function wrongly; as dealCard is a memeber function of a class, you should be calling it like this cardDeck.dealCard(); instead of this dealCard(cardDeck);.

now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card by using the following instruction:

cout << cardDeck.dealCard();// deal the cards in the deck

yet, the cout doesn't know how to print it, as it's not a standard type. this means you should overload your << operator to print whatever you want it to print when calling with a Card type.

Why can't I use switch statement on a String?

The following is a complete example based on JeeBee's post, using java enum's instead of using a custom method.

Note that in Java SE 7 and later you can use a String object in the switch statement's expression instead.

public class Main {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

      String current = args[0];
      Days currentDay = Days.valueOf(current.toUpperCase());

      switch (currentDay) {
          case MONDAY:
          case TUESDAY:
          case WEDNESDAY:
              System.out.println("boring");
              break;
          case THURSDAY:
              System.out.println("getting better");
          case FRIDAY:
          case SATURDAY:
          case SUNDAY:
              System.out.println("much better");
              break;

      }
  }

  public enum Days {

    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
  }
}

C++: Where to initialize variables in constructor

In short, always prefer initialization lists when possible. 2 reasons:

  • If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.

  • Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.

Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.

Listing files in a directory matching a pattern in Java

The following code will create a list of files based on the accept method of the FileNameFilter.

List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".exe"); // or something else
        }}));

How to show image using ImageView in Android

Drag image from your hard drive to Drawable folder in your project and in code use it like this:

ImageView image;

image = (ImageView) findViewById(R.id.yourimageviewid);
image.setImageResource(R.drawable.imagename);

GCM with PHP (Google Cloud Messaging)

You can use this PHP library available on packagist:

https://github.com/CoreProc/gcm-php

After installing it you can do this:

$gcmClient = new GcmClient('your-gcm-api-key-here');

$message = new Message($gcmClient);

$message->addRegistrationId('xxxxxxxxxx');
$message->setData([
    'title' => 'Sample Push Notification',
    'message' => 'This is a test push notification using Google Cloud Messaging'
]);

try {

    $response = $message->send();

    // The send() method returns a Response object
    print_r($response);

} catch (Exception $exception) {

    echo 'uh-oh: ' . $exception->getMessage();

}

How do I verify that an Android apk is signed with a release certificate?

Use this command, (go to java < jdk < bin path in cmd prompt)

$ jarsigner -verify -verbose -certs my_application.apk

If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK (means it is unsigned), otherwise you will find something for CN. For more details see: http://developer.android.com/guide/publishing/app-signing.html

Search code inside a Github project

I search the source code inside of Github Repositories with the free Sourcegraph Chrome Extension ... But I Downloaded Chrome First, I knew other browsers support it though, such as - and maybe just only - Firefox.

I skimmed through SourceForge's Chrome Extension Docs and then also I looked at just what I needed for searching for directory names with Github's Search Engine itself, by reading some of Github's Codebase Searching Doc