Programs & Examples On #Command pattern

The Command pattern is a Gang of Four behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. When using this tag on implementation heavy questions - tag the code language the implementation is written in.

How can I remove an element from a list?

Removing Null elements from a list in single line :

x=x[-(which(sapply(x,is.null),arr.ind=TRUE))]

Cheers

C++ error: "Array must be initialized with a brace enclosed initializer"

The syntax to statically initialize an array uses curly braces, like this:

int array[10] = { 0 };

This will zero-initialize the array.

For multi-dimensional arrays, you need nested curly braces, like this:

int cipher[Array_size][Array_size]= { { 0 } };

Note that Array_size must be a compile-time constant for this to work. If Array_size is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector).

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.

i.e:

datetime.Value

but check to see if it has a value first!

if (datetime.HasValue)
{
   // work with datetime.Value
}

How to solve java.lang.NoClassDefFoundError?

For Meteor or Cordova users,

It can be caused by the Java version you use, for meteor and cordova stick with version 8 for now.

1- Check available Java versions /usr/libexec/java_home -V and look for the path name for Java version 8

2- Set the path for Java version 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home

3- Check if it is done echo $JAVA_HOME

Go on and contiune coding.

Get index of array element faster than O(n)

Why not use index or rindex?

array = %w( a b c d e)
# get FIRST index of element searched
puts array.index('a')
# get LAST index of element searched
puts array.rindex('a')

index: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

rindex: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-rindex

SVN- How to commit multiple files in a single shot

You can use an svn changelist to keep track of a set of files that you want to commit together.

The linked page goes into lots of details, but here's an executive summary example:

$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist

How to convert comma-delimited string to list in Python?

>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')

How to simulate a click by using x,y coordinates in JavaScript?

This is just torazaburo's answer, updated to use a MouseEvent object.

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);

    el.dispatchEvent(ev);
}

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

Connection timeouts (assuming a local network and several client machines) typically result from

a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"

b) packet loss due to wrong network configuration or line overload

c) too many requests overloading the server

d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).

Hope this helps.

Writing to an Excel spreadsheet

I surveyed a few Excel modules for Python, and found openpyxl to be the best.

The free book Automate the Boring Stuff with Python has a chapter on openpyxl with more details or you can check the Read the Docs site. You won't need Office or Excel installed in order to use openpyxl.

Your program would look something like this:

import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

stimulusTimes = [1, 2, 3]
reactionTimes = [2.3, 5.1, 7.0]

for i in range(len(stimulusTimes)):
    sheet['A' + str(i + 6)].value = stimulusTimes[i]
    sheet['B' + str(i + 6)].value = reactionTimes[i]

wb.save('example.xlsx')

How can I save multiple documents concurrently in Mongoose/Node.js?

I know this is an old question, but it worries me that there are no properly correct answers here. Most answers just talk about iterating through all the documents and saving each of them individually, which is a BAD idea if you have more than a few documents, and the process gets repeated for even one in many requests.

MongoDB specifically has a batchInsert() call for inserting multiple documents, and this should be used from the native mongodb driver. Mongoose is built on this driver, and it doesn't have support for batch inserts. It probably makes sense as it is supposed to be a Object document modelling tool for MongoDB.

Solution: Mongoose comes with the native MongoDB driver. You can use that driver by requiring it require('mongoose/node_modules/mongodb') (not too sure about this, but you can always install the mongodb npm again if it doesn't work, but I think it should) and then do a proper batchInsert

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This happened to me, and once I removed this: enctype="multipart/form-data" It started working without the warning

How to truncate the time on a DateTime object in Python?

There is a module datetime_truncate which handlers this for you. It just calls datetime.replace.

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

Shift-tab does that in Flex Builder (Based on Eclipse) - SO it hopefully should work in regular eclipse :)

How to connect to a remote Git repository?

Like you said remote_repo_url is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.

There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons. You can refer to the documentation about protocols and how to connect to the server

You can check the rest of chapter 4 for more detailed information, as it's talking about how to set up your own server

How to center a <p> element inside a <div> container?

on the p element, add 3 styling rules.

.myCenteredPElement{
    margin-left:  auto;
    margin-right: auto;
    text-align: center;
}

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

Passing structs to functions

Passing structs to functions by reference: simply :)

#define maxn 1000

struct solotion
{
    int sol[maxn];
    int arry_h[maxn];
    int cat[maxn];
    int scor[maxn];

};

void inser(solotion &come){
    come.sol[0]=2;
}

void initial(solotion &come){
    for(int i=0;i<maxn;i++)
        come.sol[i]=0;
}

int main()
{
    solotion sol1;
    inser(sol1);
    solotion sol2;
    initial(sol2);
}

How do I display a text file content in CMD?

You can do that in some methods:

One is the type command: type filename Another is the more command: more filename With more you can also do that: type filename | more

The last option is using a for for /f "usebackq delims=" %%A in (filename) do (echo.%%A) This will go for each line and display it's content. This is an equivalent of the type command, but it's another method of reading the content.

If you are asking what to use, use the more command as it will make a pause.

CSS: Hover one element, effect for multiple elements?

You'd need to use JavaScript to accomplish this, I think.

jQuery:

$(function(){
   $("#innerContainer").hover(
        function(){
            $("#innerContainer").css('border-color','#FFF');
            $("#outerContainer").css('border-color','#FFF');
        },
        function(){
            $("#innerContainer").css('border-color','#000');
            $("#outerContainer").css('border-color','#000');
        }
    );
});

Adjust the values and element id's accordingly :)

Trust Anchor not found for Android SSL Connection

Update based on latest Android documentation (March 2017):

When you get this type of error:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
        at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
        at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
        at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
        at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
        at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
        at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)

the issue could be one of the following:

  1. The CA that issued the server certificate was unknown
  2. The server certificate wasn't signed by a CA, but was self signed
  3. The server configuration is missing an intermediate CA

The solution is to teach HttpsURLConnection to trust a specific set of CAs. How? Please check https://developer.android.com/training/articles/security-ssl.html#CommonProblems

Others who are using AsyncHTTPClient from com.loopj.android:android-async-http library, please check Setup AsyncHttpClient to use HTTPS.

Insert data into table with result from another select query

INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`;

Check whether variable is number or string in JavaScript

I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.

So if you care about performance, I would, I'd use this:

typeof str === "string" || str instanceof String

for checking if the variable is a string (even if you use var str = new String("foo"), str instanceof String would return true).

As for checking if it's a number I would go for the native: isNaN; function.

How to delete images from a private docker registry?

There are some clients (in Python, Ruby, etc) which do exactly that. For my taste, it isn't sustainable to install a runtime (e.g. Python) on my registry server, just to housekeep my registry!


So deckschrubber is my solution:

go get github.com/fraunhoferfokus/deckschrubber
$GOPATH/bin/deckschrubber

images older than a given age are automatically deleted. Age can be specified using -year, -month, -day, or a combination of them:

$GOPATH/bin/deckschrubber -month 2 -day 13 -registry http://registry:5000

UPDATE: here's a short introduction on deckschrubber.

What is the apply function in Scala?

Mathematicians have their own little funny ways, so instead of saying "then we call function f passing it x as a parameter" as we programmers would say, they talk about "applying function f to its argument x".

In mathematics and computer science, Apply is a function that applies functions to arguments.
Wikipedia

apply serves the purpose of closing the gap between Object-Oriented and Functional paradigms in Scala. Every function in Scala can be represented as an object. Every function also has an OO type: for instance, a function that takes an Int parameter and returns an Int will have OO type of Function1[Int,Int].

 // define a function in scala
 (x:Int) => x + 1

 // assign an object representing the function to a variable
 val f = (x:Int) => x + 1

Since everything is an object in Scala f can now be treated as a reference to Function1[Int,Int] object. For example, we can call toString method inherited from Any, that would have been impossible for a pure function, because functions don't have methods:

  f.toString

Or we could define another Function1[Int,Int] object by calling compose method on f and chaining two different functions together:

 val f2 = f.compose((x:Int) => x - 1)

Now if we want to actually execute the function, or as mathematician say "apply a function to its arguments" we would call the apply method on the Function1[Int,Int] object:

 f2.apply(2)

Writing f.apply(args) every time you want to execute a function represented as an object is the Object-Oriented way, but would add a lot of clutter to the code without adding much additional information and it would be nice to be able to use more standard notation, such as f(args). That's where Scala compiler steps in and whenever we have a reference f to a function object and write f (args) to apply arguments to the represented function the compiler silently expands f (args) to the object method call f.apply (args).

Every function in Scala can be treated as an object and it works the other way too - every object can be treated as a function, provided it has the apply method. Such objects can be used in the function notation:

// we will be able to use this object as a function, as well as an object
object Foo {
  var y = 5
  def apply (x: Int) = x + y
}


Foo (1) // using Foo object in function notation 

There are many usage cases when we would want to treat an object as a function. The most common scenario is a factory pattern. Instead of adding clutter to the code using a factory method we can apply object to a set of arguments to create a new instance of an associated class:

List(1,2,3) // same as List.apply(1,2,3) but less clutter, functional notation

// the way the factory method invocation would have looked
// in other languages with OO notation - needless clutter
List.instanceOf(1,2,3) 

So apply method is just a handy way of closing the gap between functions and objects in Scala.

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

How to get rid of punctuation using NLTK tokenizer?

I think you need some sort of regular expression matching (the following code is in Python 3):

import string
import re
import nltk

s = "I can't do this now, because I'm so tired.  Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)

Output:

['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']

Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize.

Running JAR file on Windows

Making a start.bat was the only thing that worked for me.

open a text document and enter. java -jar whatever yours is called .jar

save as start.bat in the same folder as the .jar file you want to execute. and then run the. bat

Simple mediaplayer play mp3 from file path?

Here is the code to set up a MediaPlayer to play off of the SD card:

String PATH_TO_FILE = "/sdcard/music.mp3";    
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();   
mediaPlayer.start()

You can see the full example here. Let me know if you have any problems.

removing bold styling from part of a header

If you don't want a separate CSS file, you can use inline CSS:

<h1>This text should be bold, <span style="font-weight:normal">but this text should not</span></h1>

However, as Madara's comment suggests, you might want to consider putting the unbolded part in a different header, depending on the use case involved.

What is a plain English explanation of "Big O" notation?

I've more simpler way to understand the time complexity he most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:

statement;

Is constant. The running time of the statement will not change in relation to N

for ( i = 0; i < N; i++ )
  statement;

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

for ( i = 0; i < N; i++ ) 
{
for ( j = 0; j < N; j++ )
  statement;
}

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

while ( low <= high ) 
{
 mid = ( low + high ) / 2;
 if ( target < list[mid] )
 high = mid - 1;
 else if ( target > list[mid] )
  low = mid + 1;
else break;
}

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

void quicksort ( int list[], int left, int right )
{
  int pivot = partition ( list, left, right );
  quicksort ( list, left, pivot - 1 );
  quicksort ( list, pivot + 1, right );
}

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( ) where is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note: None of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course.

How to set default vim colorscheme

You can just use the one-liner

echo colorscheme koehler >> ~/.vimrc

and replace koehler with any other available colorscheme. Imho, all of them are better than default.

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

How to make a Java Generic method static?

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

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

Android and setting alpha for (image) view alpha

There is now an XML alternative:

        <ImageView
        android:id="@+id/example"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/example"
        android:alpha="0.7" />

It is: android:alpha="0.7"

With a value from 0 (transparent) to 1 (opaque).

Check if a Windows service exists and delete in PowerShell

To check if a Windows service named MySuperServiceVersion1 exists, even when you might not be sure of its exact name, you could employ a wildcard, using a substring like so:

 if (Get-Service -Name "*SuperService*" -ErrorAction SilentlyContinue)
{
    # do something
}

Add horizontal scrollbar to html table

Edit: @WickyNilliams has noted that setting display: block on a table body will strip the table of semantics and thus is not a good solution due to accessibility issues.

I had good success with the solution proposed by @Serge Stroobandt, but I encountered the problem @Shevy had with the cells then not filling the full width of the table. I was able to fix this by adding some styles to the tbody.

table {
  display: block;
  overflow-x: auto;
  white-space: nowrap;
}

table tbody {
  display: table;
  width: 100%;
}

This worked for me in Firefox, Chrome, and Safari on Mac.

Jquery Chosen plugin - dynamically populate list by Ajax

This might be helpful. You have to just trigger an event.

$("#DropDownID").trigger("liszt:updated");

Where "DropDownID" is ID of <select>.

More info here: http://harvesthq.github.com/chosen/

How to set and reference a variable in a Jenkinsfile

I can' t comment yet but, just a hint: use try/catch clauses to avoid breaking the pipeline (if you are sure the file exists, disregard)

    pipeline {
        agent any
            stages {
                stage("foo") {
                    steps {
                        script {
                            try {                    
                                env.FILENAME = readFile 'output.txt'
                                echo "${env.FILENAME}"
                            }
                            catch(Exception e) {
                                //do something, e.g. echo 'File not found'
                            }
                        }
                   }
    }

Another hint (this was commented by @hao, and think is worth to share): you may want to trim like this readFile('output.txt').trim()

How to find Control in TemplateField of GridView?

I have done it accessing the controls inside the cell control. Find in all control collections.

 ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;

 Label lbCod = (Label)cc[1];

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

For me

Adding this line

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Before this line.

<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>

worked

How can I make robocopy silent in the command line except for progress?

The > null does not work in the quotes. It sees the > null as the batch filename.

The robocopy no output worked!!!

Here is the new batch file:

robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\EnvBackup c:\offsite_backup\EnvBackup

robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\shares c:\offsite_backup\shares

robocopy /mir /B /r:1 /nfl /ndl /njh /njs /nc /ns /np c:\Quickbooks_Backup c:\offsite_backup\Quickbooks_Backup

Apache server keeps crashing, "caught SIGTERM, shutting down"

from this page:

I found this info:

The mod_fastcgi process manager isn't particularly patient though (there's room for improvement here) and since it has to shutdown too, sends a SIGTERM to all of the FastCGI applications it is responsible for. Apache will restart the process manager and it will restart its managed applications (as if the server was just started). SIGTERM is, well, SIGTERM - your application should exit quickly.

What this implies to me is that if Database I/O, or some other part of the CGI script, fails to respond in a timely fashion (ie getting slower with data-volume growth), that mod_fastcgi is killing the script......is that how other people interpret these docs or what am I missing..

Shorter syntax for casting from a List<X> to a List<Y>?

dynamic data = List<x> val;  
List<y> val2 = ((IEnumerable)data).Cast<y>().ToList();

Setting the focus to a text field

I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.

To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow() on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!

Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.

How can I align YouTube embedded video in the center in bootstrap

make iframe with align="middle" and put it in paragraph with style="text-aling:center":

<p style="text-align:center;">
<iframe width="420" height="315" align="middle" src="https://www.youtube.com/embed/YOURVIDEO">
</iframe>
</p>

Storyboard doesn't contain a view controller with identifier

In Xcode 7 - 13,

when you change storyboard IDs and you get errors like this,

just CLEAN your project (CMD+SHIFT+K)

How do I concatenate strings?

To concatenate multiple strings into a single string, separated by another character, there are a couple of ways.

The nicest I have seen is using the join method on an array:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = [a, b].join("\n");

    print!("{}", result);
}

Depending on your use case you might also prefer more control:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = format!("{}\n{}", a, b);

    print!("{}", result);
}

There are some more manual ways I have seen, some avoiding one or two allocations here and there. For readability purposes I find the above two to be sufficient.

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

Import Google Play Services library in Android Studio

I had similar issue Cannot resolve com.google.android.gms.common.

I followed setup guide http://developer.android.com/google/play-services/setup.html and it works!

Summary:

  1. Installed/Updated Google Play Services, and Google Repository from SDK Manager
  2. Added dependency in build.gradle: compile 'com.google.android.gms:play-services:4.0.30'
  3. Updated AndroidManifest.xml with <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

How to reload or re-render the entire page using AngularJS

If you are using angular ui-router this will be the best solution.

$scope.myLoadingFunction = function() {
    $state.reload();
};

CSS vertical-align: text-bottom;

Sometimes you can play with padding and margin top, add line-height, etc.

See fiddle.

Style and text forked from @aspirinemaga

.parent
{
    width:300px;
    line-height:30px;
    border:1px solid red;
    padding-top:20px;
}

Select mysql query between date?

select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()

or using >= and <= :

select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()

How comment a JSP expression?

your <%= //map.size() %> doesnt simply work because it should have been

<% //= map.size() %>

How do I read image data from a URL in Python?

I use the requests library. It seems to be more robust.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

How to disable RecyclerView scrolling?

You can disable scrolling by freezing your RecyclerView.

To freeze: recyclerView.setLayoutFrozen(true)

To unfreeze: recyclerView.setLayoutFrozen(false)

Android: how to make keyboard enter button say "Search" and handle its click?

In Kotlin

evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        doTheLoginWork()
    }
    true
}

Partial Xml Code

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginUserEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/password"
                android:inputType="textPassword"
                android:imeOptions="actionDone"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>
</LinearLayout>

How SQL query result insert in temp table?

You can use select ... into ... to create and populate a temp table and then query the temp table to return the result.

select *
into #TempTable
from YourTable

select *
from #TempTable

Create Windows service from executable

To create a Windows Service from an executable, you can use sc.exe:

sc.exe create <new_service_name> binPath= "<path_to_the_service_executable>"

You must have quotation marks around the actual exe path, and a space after the binPath=.

More information on the sc command can be found in Microsoft KB251192.

Note that it will not work for just any executable: the executable must be a Windows Service (i.e. implement ServiceMain). When registering a non-service executable as a service, you'll get the following error upon trying to start the service:

Error 1053: The service did not respond to the start or control request in a timely fashion.

There are tools that can create a Windows Service from arbitrary, non-service executables, see the other answers for examples of such tools.

Get single row result with Doctrine NativeQuery

Both getSingleResult() and getOneOrNullResult() will throw an exception if there is more than one result. To fix this problem you could add setMaxResults(1) to your query builder.

 $firstSubscriber = $entity->createQueryBuilder()->select('sub')
        ->from("\Application\Entity\Subscriber", 'sub')
        ->where('sub.subscribe=:isSubscribe')
        ->setParameter('isSubscribe', 1)  
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();

How to roundup a number to the closest ten?

You could also use CEILING which rounds up to an integer or desired multiple of significance

ie
=CEILING(A1,10)
rounds up to a multiple of 10

12340.0001 will become 12350

MySQL - ERROR 1045 - Access denied

  1. Go to mysql console
  2. Enter use mysql;
  3. UPDATE mysql.user SET Password= PASSWORD ('') WHERE User='root' FLUSH PRIVILEGES; exit PASSWORD ('') is must empty
  4. Then go to wamp/apps/phpmyadmin../config.inc.php
  5. Find $cfg ['Servers']['$I']['password']='root';
  6. Replace the ['password'] with ['your old password']
  7. Save the file
  8. Restart the all services and goto localhost/phpmyadmin

REST API error code 500 handling

You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.

Guess what: That's what 5xx is there for.

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

Also beware that "setup" (i.e. localhost/phpmyadmin/setup) has an error in the way it handles the "no password" option. While it creates a line that says:

$cfg['Servers'][$i]['nopassword'] = true;

the actual name of the parameter should be as shown here:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

This "setup" error exists as of today, Oct 20, 2015.

Set initial value in datepicker with jquery?

You can set the value in the HTML and then init datepicker to start/highlight the actual date

<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >


$(".datepicker").each(function() {    
    $(this).datepicker('setDate', $(this).val());
});

The above even works with danish date formats

http://jsfiddle.net/DDsBP/2/

How can I ignore a property when serializing using the DataContractSerializer?

In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.

This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).

How do I convert a float number to a whole number in JavaScript?

_x000D_
_x000D_
//Convert a float to integer_x000D_
_x000D_
Math.floor(5.95)_x000D_
//5_x000D_
_x000D_
Math.ceil(5.95)_x000D_
//6_x000D_
_x000D_
Math.round(5.4)_x000D_
//5_x000D_
_x000D_
Math.round(5.5)_x000D_
//6_x000D_
_x000D_
Math.trunc(5.5)_x000D_
//5_x000D_
_x000D_
//Quick Ways_x000D_
console.log(5.95| 0)_x000D_
console.log(~~5.95) _x000D_
console.log(5.95 >> 0)_x000D_
//5
_x000D_
_x000D_
_x000D_

How to start color picker on Mac OS?

Take a look into NSColorWell class reference.

Trim last character from a string

"Hello! world!".TrimEnd('!');

read more

EDIT:

What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.

Trim - Removes all occurrences of white space characters from the beginning and end of this instance.

MSDN-Trim

Under this definition removing only last character from string is bad solution.

So if we want to "Trim last character from string" we should do something like this

Example as extension method:

public static class MyExtensions
{
  public static string TrimLastCharacter(this String str)
  {
     if(String.IsNullOrEmpty(str)){
        return str;
     } else {
        return str.TrimEnd(str[str.Length - 1]);
     }
  }
}

Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :

else { return str.Remove(str.Length - 1); }

How to display text in pygame?

When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

import pygame

def text_to_screen(screen, text, x, y, size = 50,
            color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
    try:

        text = str(text)
        font = pygame.font.Font(font_type, size)
        text = font.render(text, True, color)
        screen.blit(text, (x, y))

    except Exception, e:
        print 'Font Error, saw it coming'
        raise e

Then when that has been imported when I want to display text taht updates E.G score I do:

Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)

If it is just normal text that isn't being updated:

Funk.text_to_screen(screen, 'Text', xpos, ypos)

You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

Free tool to Create/Edit PNG Images?

Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.

Note--Inkscape is open source and available for free on multiple platforms.

How to get an isoformat datetime string including the default timezone?

You can do it in Python 2.7+ with python-dateutil (which is insalled on Mac by default):

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'

Or you if you want to convert from an existed stored string:

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT) 
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

C# List of objects, how do I get the sum of a property

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

Reading RFID with Android phones

NFC enabled phones can ONLY read NFC and passive high frequency RFID (HF-RFID). These must be read at an extremely close range, typically a few centimeters. For longer range or any other type of RFID/active RFID, you must use an external reader for handling them with mobile devices.

You can get some decent readers from a lot of manufacturers by simply searching on google. There are a lot of plug in ones for all device types.

I deal a lot with HID readers capable of close proximity scans of HID enabled ID cards as well as NFC from smart phones and smart cards. I use SerialIO badge readers that I load a decryption profile onto that allows our secure company cards to be read and utilized by an application I built. They are great for large scale reliable bluetooth scanning. Because they are bluetooth, they work for PC/Android/iOS/Linux. The only problem is, HID readers are very expensive and are meant for enterprise use. Ours cost about $400 each, but again, they read HID, SmartCards, NFC, and RFID.

If this is a personal project, I suggest just using the phone and purchasing some HF-RFID tags. The tag manufacturer should have an SDK for you to use to connect to and manage the tags. You can also just use androids NFC docs to get started https://developer.android.com/guide/topics/connectivity/nfc/. Most android phones from the last 8 years have NFC, only iPhone 6 and newer apple phones have NFC, but only iOS 11 and newer will work for what you want to do.

Convert ArrayList<String> to String[] array

What is happening is that stock_list.toArray() is creating an Object[] rather than a String[] and hence the typecast is failing1.

The correct code would be:

  String [] stockArr = stockList.toArray(new String[stockList.size()]);

or even

  String [] stockArr = stockList.toArray(new String[0]);

For more details, refer to the javadocs for the two overloads of List.toArray.

The latter version uses the zero-length array to determine the type of the result array. (Surprisingly, it is faster to do this than to preallocate ... at least, for recent Java releases. See https://stackoverflow.com/a/4042464/139985 for details.)

From a technical perspective, the reason for this API behavior / design is that an implementation of the List<T>.toArray() method has no information of what the <T> is at runtime. All it knows is that the raw element type is Object. By contrast, in the other case, the array parameter gives the base type of the array. (If the supplied array is big enough to hold the list elements, it is used. Otherwise a new array of the same type and a larger size is allocated and returned as the result.)


1 - In Java, an Object[] is not assignment compatible with a String[]. If it was, then you could do this:

    Object[] objects = new Object[]{new Cat("fluffy")};
    Dog[] dogs = (Dog[]) objects;
    Dog d = dogs[0];     // Huh???

This is clearly nonsense, and that is why array types are not generally assignment compatible.

Toggle input disabled attribute using jQuery

Quite a while later, and thanks to @arne, I created this similar small function to handle where the input should be disabled AND hidden, or enabled AND shown:

function toggleInputState(el, on) {
  // 'on' = true(visible) or false(hidden)
  // If a field is to be shown, enable it; if hidden, disable it.
  // Disabling will prevent the field's value from being submitted
  $(el).prop('disabled', !on).toggle(on);
}

Then a jQuery object (such as $('input[name="something"]') ) is simply switched using:

toggleInputState(myElement, myBoolean)

Display a RecyclerView in Fragment

You should retrieve RecyclerView in a Fragment after inflating core View using that View. Perhaps it can't find your recycler because it's not part of Activity

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();

    return view;
}

Upgrading Node.js to latest version

If you are looking in linux..

npm update will not work mostly am not sure reason but following steps will help you to resolve issue...

Terminal process to upgrade node 4.x to 6.x.

 $ node -v
 v4.x

Check node path

$ which node
/usr/bin/node

Download latest(6.x) node files from [Download][1]

[1]: https://nodejs.org/dist/v6.9.2/node-v6.9.2-linux-x64.tar.xz and unzip files keep in /opt/node-v6.9.2-linux-x64/.

Now unlink current node and link with latest as following

$ unlink /usr/bin/node
$ ln -s /opt/node-v6.9.2-linux-x64/bin/node node
$ node -v
$ v6.9.2

Convert RGBA PNG to RGB with PIL

The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.

Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.

You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:

import Image
import numpy as np

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')

enter image description here


Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.

A better quality result could be made using imagemagick's convert command:

convert logo.png -background white -flatten /tmp/out.jpg

enter image description here


To make a nicer quality blend using numpy, you could use alpha compositing:

import Image
import numpy as np

def alpha_composite(src, dst):
    '''
    Return the alpha composite of src and dst.

    Parameters:
    src -- PIL RGBA Image object
    dst -- PIL RGBA Image object

    The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
    '''
    # http://stackoverflow.com/a/3375291/190597
    # http://stackoverflow.com/a/9166671/190597
    src = np.asarray(src)
    dst = np.asarray(dst)
    out = np.empty(src.shape, dtype = 'float')
    alpha = np.index_exp[:, :, 3:]
    rgb = np.index_exp[:, :, :3]
    src_a = src[alpha]/255.0
    dst_a = dst[alpha]/255.0
    out[alpha] = src_a+dst_a*(1-src_a)
    old_setting = np.seterr(invalid = 'ignore')
    out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
    np.seterr(**old_setting)    
    out[alpha] *= 255
    np.clip(out,0,255)
    # astype('uint8') maps np.nan (and np.inf) to 0
    out = out.astype('uint8')
    out = Image.fromarray(out, 'RGBA')
    return out            

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')

enter image description here

Detect if Android device has Internet connection

You can do this with very simple class.

class CheckInternet {
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
        val activeNetworkInfo = connectivityManager!!.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnected
    }
}

Now you can check this from any class.

if (CheckInternet().isNetworkAvailable(this)) {
  //connected with internet
}else{
  //Not connected with internet
}

Jquery $(this) Child Selector

http://jqapi.com/ Traversing--> Tree Traversal --> Children

Best way to compare dates in Android

Note that the right format is ("dd/MM/yyyy") before the code works. "mm" means minuts !

String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
    strDate = sdf.parse(valid_until);
} catch (ParseException e) {
    e.printStackTrace();
}
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

Difference between style = "position:absolute" and style = "position:relative"

Relative:

  1. An element with position: relative; is positioned relative to its normal position.

  2. If you add no positioning attributes (top, left, bottom or right) on a relative element it will have no effect on it's positioning at all. It will behave exactly as a position: static element.

  3. But if you do add some other positioning attribute, say, top: 10px;, it will shift its position 10 pixels down from where it would normally be.

  4. An element with this type of positioning gets affected by other elements and it itself also affects others.

Absolute:

  1. An element with position: absolute; allows you to place any element exactly where you want it to be. You use the positioning attributes top, left, bottom. and right to set the location.

  2. It is placed relative to the nearest non-static ancestor. If there is no such container, it is placed relative to the page itself.

  3. It gets removed from the normal flow of elements on the page.

  4. An element with this type of positioning is not affected by other elements and also it doesn't affect flow of other elements.

See this self-explanatory example for better clarity. https://codepen.io/nyctophiliac/pen/BJMqjX

Getting full-size profile picture

As noted above, it appears that the cover photo of the profile album is a hi-res profile picture. I would check for the album type of "profile" rather than the name though, as the name may not be consistent across different languages, but the type should be.

To reduce the number of requests / parsing, you can use this fql: "select cover_object_id from album where type='profile' and owner = user_id"

And then you can construct the image url with: "https://graph.facebook.com/" + cover_object_id + "/picture&type=normal&access_token=" + access_token

Looks like there is no "large" type for this image, but the "normal" one is still quite large.

As noted above, this photo may be less accessible than the public profile picture. You need the user_photos or friend_photos permission to access it.

Path.Combine absolute with relative path strings

For windows universal apps Path.GetFullPath() is not available, you can use the System.Uri class instead:

 Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));
 Console.WriteLine(uri.LocalPath);

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

I'd do

for i in `seq 0 2 10`; do echo $i; done

(though of course seq 0 2 10 will produce the same output on its own).

Note that seq allows floating-point numbers (e.g., seq .5 .25 3.5) but bash's brace expansion only allows integers.

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

How to insert an item into an array at a specific index (JavaScript)?

Here's a working function that I uses in one of my application.

This checks if item exit

let ifExist = (item, strings = [ '' ], position = 0) => {
     // output into an array with empty string. Important just in case their is no item. 
    let output = [ '' ];
    // check to see if the item that will be positioned exist.
    if (item) {
        // output should equal to array of strings. 
        output = strings;
       // use splice in order to break the array. 
       // use positition param to state where to put the item
       // and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position. 
        output.splice(position, 0, item);
    }
    //empty string is so we do not concatenate with comma or anything else. 
    return output.join("");
};

And then I call it below.

ifExist("friends", [ ' ( ', ' )' ], 1)}  // output: ( friends )
ifExist("friends", [ ' - '], 1)}  // output:  - friends 
ifExist("friends", [ ':'], 0)}  // output:   friends: 

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

I prefer this solution:

df = spark.table(selected_table).filter(condition)

counter = df.count()

df = df.select([(counter - count(c)).alias(c) for c in df.columns])

Variable declaration in a header file

You can (should) declare it as extern in a header file, and define it in exactly 1 .c file.

Note that that .c file should also use the header and that the standard pattern looks like:

// file.h
extern int x;  // declaration

// file.c
#include "file.h"
int x = 1;    // definition and re-declaration

Match exact string

Use the start and end delimiters: ^abc$

Remove all occurrences of char from string

Try using the overload that takes CharSequence arguments (eg, String) rather than char:

str = str.replace("X", "");

git replacing LF with CRLF

CRLF could cause some problem while using your "code" in two different OS (Linux and Windows). My python script was written in Linux docker container and then pushed using Windows git-bash. It gave me the warning that LF will be replaced by CRLF. I didn't give it much thought but then when I started the script later, it said /usr/bin/env: 'python\r': No such file or directory. Now that an \r for ramification for you. Windows uses "CR" - carriage return - on top of '\n' as new line character - \n\r. That's something you might have to consider.

How does one capture a Mac's command key via JavaScript?

I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ?+x:, you can detect the x key AND check if event.metaKey is set to true. For example:

var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);

When pressing x on it's own, this will output 120, false. When pressing ?+x, it will output 120, true

This only seems to work in Safari - not Chrome

Build android release apk on Phonegap 3.x CLI

This is for Phonegap 3.0.x to 3.3.x. For PhoneGap 3.4.0 and higher see below.

Found part of the answer here, at Phonegap documentation. The full process is the following:

  1. Open a command line window, and go to /path/to/your/project/platforms/android/cordova.

  2. Run build --release. This creates an unsigned release APK at /path/to/your/project/platforms/android/bin folder, called YourAppName-release-unsigned.apk.

  3. Sign and align the APK using the instructions at android developer official docs.

Thanks to @LaurieClark for the link (http://iphonedevlog.wordpress.com/2013/08/16/using-phonegap-3-0-cli-on-mac-osx-10-to-build-ios-and-android-projects/), and the blogger who post it, because it put me on the track.

How to display the string html contents into webbrowser control?

As commented by Thomas W. - I almost missed this comment but I had the same issues so it's worth rewriting as an answer I think.

The main issue being that after the first assignment of webBrowser1.DocumentText to some html, subsequent assignments had no effect.

The solution as linked by Thomas can be found in detail at http://weblogs.asp.net/gunnarpeipman/archive/2009/08/15/displaying-custom-html-in-webbrowser-control.aspx however I will summarize below in case this page becomes unavailable in the future.

In short, due to the way the webBrowser control works, you must navigate to a new page each time you wish to change the content. Therefore the author proposes a method to update the control as:

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    if (webBrowser1.Document != null)
    {
        webBrowser1.Document.Write(string.Empty);
    }
    webBrowser1.DocumentText = html;
}

I have however found that in my current application I get a CastException from the line if(webBrowser1.Document != null). I'm not sure why this is, but I've found that if I wrap the whole if block in a try catch the desired effect still works. See:

private void DisplayHtml(string html)
{
    webBrowser1.Navigate("about:blank");
    try
    {
        if (webBrowser1.Document != null)
        {
            webBrowser1.Document.Write(string.Empty);
        }
    }
    catch (CastException e)
    { } // do nothing with this
    webBrowser1.DocumentText = html;
}

So every time the function to DisplayHtml is executed I receive a CastException from the if statement, so the contents of the if statement are never reached. However if I comment out the if statement so as not to receive the CastException, then the browser control doesn't get updated. I suspect there is another side effect of the code behind the Document property which causes this effect despite the fact that it also throws an exception.

Anyway I hope this helps people.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4


typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;

...

# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

__init__ and arguments in Python

In python you must always pass in at least one argument to class methods, the argument is self and it is not meaningless its a reference to the instance itself

How do I list loaded plugins in Vim?

The problem with :scriptnames, :commands, :functions, and similar Vim commands, is that they display information in a large slab of text, which is very hard to visually parse.

To get around this, I wrote Headlights, a plugin that adds a menu to Vim showing all loaded plugins, TextMate style. The added benefit is that it shows plugin commands, mappings, files, and other bits and pieces.

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

/usr/bin/ld: cannot find

@Alwin Doss You should provide the -L option before -l. You would have done the other way round probably. Try this :)

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

<style name="AppTheme" parent="android:Theme.Holo" />

Setting size for icon in CSS

The better way is using 'background-size'.

.pnx-msg-icon .pnx-icon-msg-warning{
background-image: url("../pics/edit.png");
background-repeat: no-repeat;
background-size: 10px;
width: 10px;
height: 10px;
cursor: pointer;
}

even if your icon dimensions is bigger than 10px it will be 10px.

What is the purpose of Android's <merge> tag in XML layouts?

To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/content_profile" />

</LinearLayout>

content_profile.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</LinearLayout>

In here, the entire layout file when inflated looks like this.

<LinearLayout>
    <LinearLayout>
        <TextView />
        <TextView />
    </LinearLayout>
</LinearLayout>

See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.

enter image description here

content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.

<merge xmlns:android="http://schemas.android.com/apk/res/android">

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</merge>

Now our layout looks like this

<LinearLayout>
    <TextView />
    <TextView />
</LinearLayout>

Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.

enter image description here

So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.

What is the difference between String and StringBuffer in Java?

A StringBuffer is used to create a single string from many strings, e.g. when you want to append parts of a String in a loop.

You should use a StringBuilder instead of a StringBuffer when you have only a single Thread accessing the StringBuffer, since the StringBuilder is not synchronized and thus faster.

AFAIK there is no upper limit for String size in Java as a language, but the JVMs probably have an upper limit.

How to save and extract session data in codeigniter

CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.

Initializing a Session

To initialize the Session class manually in our controller constructor use following code.

Adding Custom Session Data

We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.

$this->session->set_userdata($newarray);

Where $newarray is an associative array containing our new data.

$newarray = array( 'name' => 'manish', 'email' => '[email protected]'); $this->session->set_userdata($newarray); 

Retrieving Session

$session_id = $this->session->userdata('session_id');

Above function returns FALSE (boolean) if the session array does not exist.

Retrieving All Session Data

$this->session->all_userdata()

I have taken reference from http://www.tutsway.com/codeigniter-session.php.

Database, Table and Column Naming Conventions?

My opinions on these are:

1) No, table names should be singular.

While it appears to make sense for the simple selection (select * from Orders) it makes less sense for the OO equivalent (Orders x = new Orders).

A table in a DB is really the set of that entity, it makes more sense once you're using set-logic:

select Orders.*
from Orders inner join Products
    on Orders.Key = Products.Key

That last line, the actual logic of the join, looks confusing with plural table names.

I'm not sure about always using an alias (as Matt suggests) clears that up.

2) They should be singular as they only hold 1 property

3) Never, if the column name is ambiguous (as above where they both have a column called [Key]) the name of the table (or its alias) can distinguish them well enough. You want queries to be quick to type and simple - prefixes add unnecessary complexity.

4) Whatever you want, I'd suggest CapitalCase

I don't think there's one set of absolute guidelines on any of these.

As long as whatever you pick is consistent across the application or DB I don't think it really matters.

How to affect other elements when one element is hovered

In this particular example, you can use:

#container:hover #cube {
    background-color: yellow;   
}

This example only works since cube is a child of container. For more complicated scenarios, you'd need to use different CSS, or use JavaScript.

How to host material icons offline?

Method 2. Self hosting Developer Guide

Download the latest release from github (assets: zip file), unzip, and copy the font folder, containing the material design icons files, into your local project -- https://github.com/google/material-design-icons/releases

You only need to use the font folder from the archive: it contains the icons fonts in the different formats (for multiple browser support) and boilerplate css.

  • Replace the source in the url attribute of @font-face, with the relative path to the iconfont folder in your local project, (where the font files are located) eg. url("iconfont/MaterialIcons-Regular.ttf")
@font-face {
   font-family: 'Material Icons';
   font-style: normal;
   font-weight: 400;
   src: url(iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
   src: local('Material Icons'),
        local('MaterialIcons-Regular'),
        url(iconfont/MaterialIcons-Regular.woff2) format('woff2'),
        url(iconfont/MaterialIcons-Regular.woff) format('woff'),
        url(iconfont/MaterialIcons-Regular.ttf) format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

<i class="material-icons">face</i>

NPM / Bower Packages

Google officially has a Bower and NPM dependency option -- follow Material Icons Guide 1

Using bower : bower install material-design-icons --save

Using NPM : npm install material-design-icons --save

Material Icons : Alternatively look into Material design icon font and CSS framework for self hosting the icons, from @marella's https://marella.me/material-icons/


Note

It seems google has the project on low maintenance mode. The last release was, at time of writing, 3 years ago!

There are several issues on GitHub regarding this, but I'd like to refer to @cyberalien comment on the issue Is this project actively maintained? #951 where it refers several community projects that forked and continue maintaining material icons.


Add / remove input field dynamically with jQuery

In your click function, you can write:

function addMoreRows(frm) {
   rowCount ++;
   var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" size="17%"  maxlength="120" /></td><td><input name="" type="text"  maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> <a href="javascript:void(0);" onclick="removeRow('+rowCount+');">Delete</a></p>';
   jQuery('#addedRows').append(recRow);
}

Or follow this link: http://www.discussdesk.com/add-remove-more-rows-dynamically-using-jquery.htm

How to delete the top 1000 rows from a table using Sql Server 2008?

The code you tried is in fact two statements. A DELETE followed by a SELECT.

You don't define TOP as ordered by what.

For a specific ordering criteria deleting from a CTE or similar table expression is the most efficient way.

;WITH CTE AS
(
SELECT TOP 1000 *
FROM [mytab]
ORDER BY a1
)
DELETE FROM CTE

How to convert JSON to XML or XML to JSON?

You can do these conversions also with the .NET Framework:

JSON to XML: by using System.Runtime.Serialization.Json

var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));

XML to JSON: by using System.Web.Script.Serialization

var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));

private static Dictionary<string, object> GetXmlData(XElement xml)
{
    var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
    if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
    else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

    return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}

jQuery Form Validation before Ajax submit

This specific example will just check for inputs but you could tweak it however, Add something like this to your .ajax function:

beforeSend: function() {                    
    $empty = $('form#yourForm').find("input").filter(function() {
        return this.value === "";
    });
    if($empty.length) {
        alert('You must fill out all fields in order to submit a change');
        return false;
    }else{
        return true;
    };
},

Unix ls command: show full path when using options

I wrote a shell script called fullpath that contains this code, use it everyday:

    #!/bin/sh
    for i in $* ; do
        echo $(pwd)/$i
    done

Put it somewhere in your PATH, and make it executable(chmod 755 fullpath) then just use
fullpath file_or_directory

I can't install intel HAXM

After some trials, knowing that I had all the factors stated in this thread and other threads properly configured, I still got this error in Android Studio.

Even after installing externally, it seems Android Studio could not discover that HAXM is already installed, unless it gets to install it itself.

As a solution that worked for me, under User\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager which android has downloaded when attempting to install HAXM, click the installer and uninstall the software, then re-try from Android Studio to install it, it should work now.

How do I read input character-by-character in Java?

You have several options if you use BufferedReader. This buffered reader is faster than Reader so you can wrap it.

BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);

this reads line into char array. You have similar options. Look at documentation.

Alter table to modify default value of column

ALTER TABLE <table_name> MODIFY <column_name> DEFAULT <defult_value>

EX: ALTER TABLE AAA MODIFY ID DEFAULT AAA_SEQUENCE.nextval

Tested on Oracle Database 12c Enterprise Edition Release 12.2.0.1.0

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

Getting the first character of a string with $str[0]

It'll vary depending on resources, but you could run the script bellow and see for yourself ;)

<?php
$tests = 100000;

for ($i = 0; $i < $tests; $i++)
{
    $string = md5(rand());
    $position = rand(0, 31);

    $start1 = microtime(true);
    $char1 = $string[$position];
    $end1 = microtime(true);
    $time1[$i] = $end1 - $start1;

    $start2 = microtime(true);
    $char2 = substr($string, $position, 1);
    $end2 = microtime(true);
    $time2[$i] = $end2 - $start2;

    $start3 = microtime(true);
    $char3 = $string{$position};
    $end3 = microtime(true);
    $time3[$i] = $end3 - $start3;
}

$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;

$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;

$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>

Some reference numbers (on an old CoreDuo machine)

$ php 1.php 
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6

$ php 1.php 
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6

It seems that using the [] or {} operators is more or less the same.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

What do two question marks together mean in C#?

It's short hand for the ternary operator.

FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();

Or for those who don't do ternary:

if (formsAuth != null)
{
  FormsAuth = formsAuth;
}
else
{
  FormsAuth = new FormsAuthenticationWrapper();
}

Is iterating ConcurrentHashMap values thread safe?

It means that you should not share an iterator object among multiple threads. Creating multiple iterators and using them concurrently in separate threads is fine.

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

How To: Execute command line in C#, get STD OUT results

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

Code is from MSDN.

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

How to sort a Ruby Hash by number value?

That's not the behavior I'm seeing:

irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
 10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]

Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

brew services start mysql defualt set --bind-address=127.0.0.1 with /usr/local/Cellar/mysql/5.6.27/homebrew.mxcl.mysql.plist,so replace --bind-address=127.0.0.1 with --bind-address=* or --bind-address=0.0.0.0

jQuery see if any or no checkboxes are selected

This is what I used for checking if any checkboxes in a list of checkboxes had changed:

$('input[type="checkbox"]').change(function(){ 

        var itemName = $('select option:selected').text();  

         //Do something.

});     

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

Android - Share on Facebook, Twitter, Mail, ecc

This will help

1- First Define This Constants

 public static final String FACEBOOK_PACKAGE_NAME = "com.facebook.katana";
    public static final String TWITTER_PACKAGE_NAME = "com.twitter.android";
    public static final String INSTAGRAM_PACKAGE_NAME = "com.instagram.android";
    public static final String PINTEREST_PACKAGE_NAME = "com.pinterest";
    public static final String WHATS_PACKAGE_NAME =  "com.whatsapp";

2- Second Use This method

 public static void shareAppWithSocial(Context context, String application, String title, 
 String description) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setPackage(application);

        intent.putExtra(android.content.Intent.EXTRA_TITLE, title);
        intent.putExtra(Intent.EXTRA_TEXT, description);
        intent.setType("text/plain");

        try {
            // Start the specific social application
            context.startActivity(intent);
        } catch (android.content.ActivityNotFoundException ex) {
            // The application does not exist
            Toast.makeText(context, "app have not been installed.", Toast.LENGTH_SHORT).show();
        }


    }

How to convert the background to transparent?

For Photoshop you need to download Photoshop portable.... Load image e press "w" click in image e suave as png or gif....

How to switch a user per task or set of tasks?

With Ansible 1.9 or later

Ansible uses the become, become_user, and become_method directives to achieve privilege escalation. You can apply them to an entire play or playbook, set them in an included playbook, or set them for a particular task.

- name: checkout repo
  git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
  become: yes
  become_user: some_user

You can use become_with to specify how the privilege escalation is achieved, the default being sudo.

The directive is in effect for the scope of the block in which it is used (examples).

See Hosts and Users for some additional examples and Become (Privilege Escalation) for more detailed documentation.

In addition to the task-scoped become and become_user directives, Ansible 1.9 added some new variables and command line options to set these values for the duration of a play in the absence of explicit directives:

As of Ansible 2.0.2.0, the older sudo/sudo_user syntax described below still works, but the deprecation notice states, "This feature will be removed in a future release."


Previous syntax, deprecated as of Ansible 1.9 and scheduled for removal:

- name: checkout repo
  git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
  sudo: yes
  sudo_user: some_user

Can I add background color only for padding?

You can't set colour of the padding.

You will have to create a wrapper element with the desired background colour. Add border to this element and set it's padding.

Look here for an example: http://jsbin.com/abanek/1/edit

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

How does one target IE7 and IE8 with valid CSS?

For a more complete list as of 2015:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading

Changing Underline color

In practice, it is possible, if you use span element instead of font:

<style>
u { color: black; }
.red { color: red }
</style>
<u><span class='red'><br>$username</span></u>

See jsfiddle. Appears to work on Chrome, Safari, Firefox, IE, Opera (tested on Win 7 with newest versions).

The code in the question should work, too, but it does not work for some reason on WebKit browsers (Chrome, Safari).

By the CSS spec: “The color(s) required for the text decoration must be derived from the 'color' property value of the element on which 'text-decoration' is set. The color of decorations must remain the same even if descendant elements have different 'color' values.”

What is the argument for printf that formats a long?

It depends, if you are referring to unsigned long the formatting character is "%lu". If you're referring to signed long the formatting character is "%ld".

Google Play Services Library update and missing symbol @integer/google_play_services_version

For everyone using Eclipse, this is how you should do it.

Eclipse -> import -> existing android code -> browse -> navigate to google-play-services_lib FOLDER (android-sdk/extras/google/google_play_services/libproject).

Then, on your project

control click -> properties -> android -> libraries, add -> select the project you just imported -> ok

Oracle SQL: Update a table with data from another table

Update table set column = (select...)

never worked for me since set only expects 1 value - SQL Error: ORA-01427: single-row subquery returns more than one row.

here's the solution:

BEGIN
For i in (select id, name, desc from table1) 
LOOP
Update table2 set name = i.name, desc = i.desc where id = i.id;
END LOOP;
END;

That's how exactly you run it on SQLDeveloper worksheet. They say it's slow but that's the only solution that worked for me on this case.

How to access local files of the filesystem in the Android emulator?

You can use the adb command which comes in the tools dir of the SDK:

adb shell

It will give you a command line prompt where you can browse and access the filesystem. Or you can extract the files you want:

adb pull /sdcard/the_file_you_want.txt

Also, if you use eclipse with the ADT, there's a view to browse the file system (Window->Show View->Other... and choose Android->File Explorer)

How to search multiple columns in MySQL?

Here is a query which you can use to search for anything in from your database as a search result ,

SELECT * FROM tbl_customer 
    WHERE CustomerName LIKE '%".$search."%'
    OR Address LIKE '%".$search."%' 
    OR City LIKE '%".$search."%' 
    OR PostalCode LIKE '%".$search."%' 
    OR Country LIKE '%".$search."%'

Using this code will help you search in for multiple columns easily

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

As of Android Studio version 0.8.14

You should add:

 android {
     packagingOptions { 
         exclude 'META-INF/LICENSE.txt'
         exclude 'META-INF/NOTICE.txt'
         exclude '...'
     }
 }  

to your build.gradle file.

History:

According to comment 14 in this bug: https://issuetracker.google.com/issues/36982149#comment14 this is a bug in v0.7.0 of the Android Gradle plugin, and is due to be fixed soon in 0.7.1.

Here are the notes from that bug about the addition for 0.7.1:

0.7.1 is out with the fix for this.

The DSL to exclude files is:

android {
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
    }
}

You can add as many exclude statement as you want. The value is the archive path. No wildcard or glob support yet.

Filenames "LICENSE.txt" and "NOTICE.txt" are case sensitive. Please try out with "license.txt" and "notice.txt" as well.

Foreach loop, determine which is the last iteration of the loop

How about a good old fashioned for loop?

for (int i = 0; i < Model.Results.Count; i++) {

     if (i == Model.Results.Count - 1) {
           // this is the last item
     }
}

Or using Linq and the foreach:

foreach (Item result in Model.Results)   
{   
     if (Model.Results.IndexOf(result) == Model.Results.Count - 1) {
             // this is the last item
     }
}

How do I watch a file for changes?

ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001

class myThread (threading.Thread):
    def __init__(self, threadID, fileName, directory, origin):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.fileName = fileName
        self.daemon = True
        self.dir = directory
        self.originalFile = origin
    def run(self):
        startMonitor(self.fileName, self.dir, self.originalFile)

def startMonitor(fileMonitoring,dirPath,originalFile):
    hDir = win32file.CreateFile (
        dirPath,
        FILE_LIST_DIRECTORY,
        win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
        None,
        win32con.OPEN_EXISTING,
        win32con.FILE_FLAG_BACKUP_SEMANTICS,
        None
    )
    # Wait for new data and call ProcessNewData for each new chunk that's
    # written
    while 1:
        # Wait for a change to occur
        results = win32file.ReadDirectoryChangesW (
            hDir,
            1024,
            False,
            win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
            None,
            None
        )
        # For each change, check to see if it's updating the file we're
        # interested in
        for action, file_M in results:
            full_filename = os.path.join (dirPath, file_M)
            #print file, ACTIONS.get (action, "Unknown")
            if len(full_filename) == len(fileMonitoring) and action == 3:
                #copy to main file
                ...

How to copy text from a div to clipboard

Both examples work like a charm :)

  1. JAVASCRIPT:

    _x000D_
    _x000D_
    function CopyToClipboard(containerid) {_x000D_
      if (document.selection) {_x000D_
        var range = document.body.createTextRange();_x000D_
        range.moveToElementText(document.getElementById(containerid));_x000D_
        range.select().createTextRange();_x000D_
        document.execCommand("copy");_x000D_
      } else if (window.getSelection) {_x000D_
        var range = document.createRange();_x000D_
        range.selectNode(document.getElementById(containerid));_x000D_
        window.getSelection().addRange(range);_x000D_
        document.execCommand("copy");_x000D_
        alert("Text has been copied, now paste in the text-area")_x000D_
      }_x000D_
    }
    _x000D_
    <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>_x000D_
    <br /><br />_x000D_
    <div id="div1">Text To Copy </div>_x000D_
    <br />_x000D_
    <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
    _x000D_
    _x000D_
    _x000D_

  2. JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard

extract date only from given timestamp in oracle sql

Use the function cast() to convert from timestamp to date

select to_char(cast(sysdate as date),'DD-MM-YYYY') from dual;

For more info of function cast oracle11g http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions016.htm#SQLRF51256

The character encoding of the plain text document was not declared - mootool script

If you are using ASP.NET Core MVC project. This error message can be shown then you have the correct cshtml file in your Views folder but the action is missing in your controller.

Adding the missing action to the controller will fix it.

How to force the input date format to dd/mm/yyyy?

DEMO : http://jsfiddle.net/shfj70qp/

//dd/mm/yyyy 

var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();

console.log(month+"/"+day+"/"+year);

Break or return from Java 8 stream forEach?

Update with Java 9+ with takeWhile:

MutableBoolean ongoing = MutableBoolean.of(true);
someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
    // doing something.
    if (...) { // want to break;
        ongoing.setFalse();
    }
});

How to change css property using javascript

Consider the following example: If you want to change a single CSS property(say, color to 'blue'), then the below statement works fine.

document.getElementById("ele_id").style.color="blue";

But, for changing multiple properies the more robust way is using Object.assign() or, object spread operator {...};

See below:

const ele=document.getElementById("ele_id");
const custom_style={
    display: "block",
    color: "red"
}

//Object.assign():
Object.assign(ele.style,custum_style);

Spread operator works similarly, just the syntax is a little different.

when exactly are we supposed to use "public static final String"?

You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.

Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.

An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).

Here's why:

  1. Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
  2. What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.

What are the consequences?

Imagine you have this:

class Foo {
  public static final String VERSION = "1.0";
}

class Bar {
  public static void main(String[] args) {
    System.out.println("I am using version " + Foo.VERSION);
  }
}

After compiling and running Bar, you'll get:

I am using version 1.0

Now, you improve Foo and change the version to "1.1". After recompiling Foo, you run Bar and get this wrong output:

I am using version 1.0

This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.

I've seen this a couple of times and it is really hard to debug.

If by final you mean a constant that might change in later versions of your program, a better solution would be this:

class Foo {
  private static String version = "1.0";
  public static final String getVersion() {
    return version;
  }
}

The performance penalty of this is negligible, since JIT code generator will inline it at run-time.

how to resolve DTS_E_OLEDBERROR. in ssis

I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.

Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008

http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx

http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx

http://blogs.msdn.com/b/psssql/archive/2008/10/01/windows-scalable-networking-pack-possible-performance-and-concurrency-impacts-to-sql-server-workloads.aspx

What is the difference between function and procedure in PL/SQL?

The following are the major differences between procedure and function,

  1. Procedure is named PL/SQL block which performs one or more tasks. where function is named PL/SQL block which performs a specific action.
  2. Procedure may or may not return value where as function should return one value.
  3. we can call functions in select statement where as procedure we cant.

Ignoring NaNs with str.contains

I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.

import pandas as pd
import numpy as np

df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])

newdf = df.loc[df['a'].str.contains('foo') == True]

Works with or without .loc.

I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True or False. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.

call javascript function on hyperlink click

I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

attachEvent / addEventListening allow multiple event handlers to be created.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

using mailto to send email with an attachment

this is not possible in "mailto" function.

please go with server side coding(C#).make sure open vs in administrative permission.

Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

oMsg.Subject = "emailSubject";
oMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
oMsg.BCC = "emailBcc";
oMsg.To = "emailRecipient";

string body = "emailMessage";

oMsg.HTMLBody = "body";              
oMsg.Attachments.Add(Convert.ToString(@"/my_location_virtual_path/myfile.txt"), Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);

oMsg.Display(false); //In order to displ

Efficiently counting the number of lines of a text file. (200mb+)

private static function lineCount($file) {
    $linecount = 0;
    $handle = fopen($file, "r");
    while(!feof($handle)){
        if (fgets($handle) !== false) {
                $linecount++;
        }
    }
    fclose($handle);
    return  $linecount;     
}

I wanted to add a little fix to the function above...

in a specific example where i had a file containing the word 'testing' the function returned 2 as a result. so i needed to add a check if fgets returned false or not :)

have fun :)

How to monitor SQL Server table changes by using c#?

You can use the SqlDependency Class. Its intended use is mostly for ASP.NET pages (low number of client notifications).

ALTER DATABASE UrDb SET ENABLE_BROKER

Implement the OnChange event to get notified:

void OnChange(object sender, SqlNotificationEventArgs e)

And in code:

SqlCommand cmd = ...
cmd.Notification = null;

SqlDependency dependency = new SqlDependency(cmd);

dependency.OnChange += OnChange;

It uses the Service Broker (a message-based communication platform) to receive messages from the database engine.

String comparison technique used by Python

Python string comparison is lexicographic:

From Python Docs: http://docs.python.org/reference/expressions.html

Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.

Hence in your example, 'abc' < 'bac', 'a' comes before (less-than) 'b' numerically (in ASCII and Unicode representations), so the comparison ends right there.

Why does JPA have a @Transient annotation?

For Kotlin developers, remember the Java transient keyword becomes the built-in Kotlin @Transient annotation. Therefore, make sure you have the JPA import if you're using JPA @Transient in your entity:

import javax.persistence.Transient

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I was missing several DLLs. Even if I manually copied them to the directory the next time I published they would disappear. Each one was already set to Copy Locally in VS. The fix for me was to set each one to Copy Locally false, save, build then set each one to copy locally true. This time when I published all of the DLLs published correctly. Strange

Make an existing Git branch track a remote branch?

Here, using github and git version 2.1.4, just do:

$ git clone [email protected]:user/repo.git

And remotes come by itelsef, even if not linked locally:

$ git remote show origin

* remote origin
  Fetch URL: [email protected]:user/repo.git
  Push  URL: [email protected]:user/repo.git
  HEAD branch: master
  Remote branches:
    develop tracked         <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    master  tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (up to date)

But of course, still no local branch:

$ git branch
* master                  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

See? Now if you just checkout develp, it will do the magic automatically:

$ git checkout develop
Branch develop set up to track remote branch develop from origin.
Switched to a new branch 'develop'

So easy!


Summary. Just run this 2 commands:

$ git clone [email protected]:user/repo.git
$ git checkout develop

read string from .resx file in C#

Assuming the .resx file was added using Visual Studio under the project properties, there is an easier and less error prone way to access the string.

  1. Expanding the .resx file in the Solution Explorer should show a .Designer.cs file.
  2. When opened, the .Designer.cs file has a Properties namespace and an internal class. For this example assume the class is named Resources.
  3. Accessing the string is then as easy as:

    var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
    var exampleXmlString = resourceManager.GetString("exampleXml");
    
  4. Replace JoshCodes.Core.Testing.Unit with the project's default namespace.

  5. Replace "exampleXml" with the name of your string resource.

How to play .wav files with java

A class that will play a WAV file, blocking until the sound has finished playing:

class Sound implements Playable {

    private final Path wavPath;
    private final CyclicBarrier barrier = new CyclicBarrier(2);

    Sound(final Path wavPath) {

        this.wavPath = wavPath;
    }

    @Override
    public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {

        try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
             final Clip clip = AudioSystem.getClip()) {

            listenForEndOf(clip);
            clip.open(audioIn);
            clip.start();
            waitForSoundEnd();
        }
    }

    private void listenForEndOf(final Clip clip) {

        clip.addLineListener(event -> {
            if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
        });
    }

    private void waitOnBarrier() {

        try {

            barrier.await();
        } catch (final InterruptedException ignored) {
        } catch (final BrokenBarrierException e) {

            throw new RuntimeException(e);
        }
    }

    private void waitForSoundEnd() {

        waitOnBarrier();
    }
}

Transitions on the CSS display property

I suspect that the reason that transitions are disabled if display is changed is because of what display actually does. It does not change anything that could conceivably be smoothly animated.

display: none; and visibility: hidden; are two entirely different things.
Both do have the effect of making the element invisible, but with visibility: hidden; it’s still rendered in the layout, but just not visibly so.
The hidden element still takes up space, and is still rendered inline or as a block or block-inline or table or whatever the display element tells it to render as, and takes up space accordingly.
Other elements do not automatically move to occupy that space. The hidden element just doesn’t render its actual pixels to the output.

display: none on the other hand actually prevents the element from rendering entirely.
It does not take up any layout space.
Other elements that would’ve occupied some or all of the space taken up by this element now adjust to occupy that space, as if the element simply did not exist at all.

display is not just another visual attribute.
It establishes the entire rendering mode of the element, such as whether it’s a block, inline, inline-block, table, table-row, table-cell, list-item, or whatever!
Each of those have very different layout ramifications, and there would be no reasonable way to animate or smoothly transition them (try to imagine a smooth transition from block to inline or vice-versa, for instance!).

This is why transitions are disabled if display changes (even if the change is to or from nonenone isn’t merely invisibility, it’s its own element rendering mode that means no rendering at all!).

is python capable of running on multiple cores?

Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.

How to parse JSON Array (Not Json Object) in Android

public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Output:

name1
url1
name2
url2

Python/Json:Expecting property name enclosed in double quotes

JSON strings must use double quotes. The JSON python library enforces this so you are unable to load your string. Your data needs to look like this:

{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}

If that's not something you can do, you could use ast.literal_eval() instead of json.loads()

Check if a time is between two times (time DataType)

I had a very similar problem and want to share my solution

Given this table (all MySQL 5.6):

create table DailySchedule
(
  id         int auto_increment primary key,
  start_time time not null,
  stop_time  time not null
);

Select all rows where a given time x (hh:mm:ss) is between start and stop time. Including the next day.

Note: replace NOW() with the any time x you like

SELECT id
FROM DailySchedule
WHERE
  (start_time < stop_time AND NOW() BETWEEN start_time AND stop_time)
  OR
  (stop_time < start_time AND NOW() < start_time AND NOW() < stop_time)
  OR
  (stop_time < start_time AND NOW() > start_time)

Results

Given

  id: 1, start_time: 10:00:00, stop_time: 15:00:00
  id: 2, start_time: 22:00:00, stop_time: 12:00:00
  • Selected rows with NOW = 09:00:00: 2
  • Selected rows with NOW = 14:00:00: 1
  • Selected rows with NOW = 11:00:00: 1,2
  • Selected rows with NOW = 20:00:00: nothing

Finding the position of the max element

std::max_element takes two iterators delimiting a sequence and returns an iterator pointing to the maximal element in that sequence. You can additionally pass a predicate to the function that defines the ordering of elements.

Cannot connect to Database server (mysql workbench)

I had a similar issue on Mac OS and I was able to fix it this way:

From the terminal, run:

mysql -u root -p -h 127.0.0.1 -P 3306

Then, I was asked to enter the password. I just pressed enter since no password was setup.

I got a message as follows:

Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 181. Server version: 8.0.11 Homebrew.

If you succeeded to log into mysql>, run the following command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

You should get a message like this:

Query OK, 0 rows affected (0.19 sec)

Now, your password is "password" and your username is "root".

Happy coding :)

Is there a float input type in HTML5?

Using React on my IPad, type="number" does not work perfectly for me. For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$). The first group (...) is true for all positive two digit numbers without the floating point (e.g. 23), | or e.g. .12345 for the second group (...). You can adopt it for any positive floating point number by simply changing the range {0,2} or {0,5} respectively.

<input
  className="center-align"
  type="text"
  pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
  step="any"
  maxlength="7"
  validate="true"
/>

jQuery UI themes and HTML tables

dochoffiday's answer is a great starting point, but for me it did not cut it (the CSS part needed a buff) so I made a modified version with several improvements.

See it in action, then come back for the description.

JavaScript

(function ($) {
    $.fn.styleTable = function (options) {
        var defaults = {
            css: 'ui-styled-table'
        };
        options = $.extend(defaults, options);

        return this.each(function () {
            $this = $(this);
            $this.addClass(options.css);

            $this.on('mouseover mouseout', 'tbody tr', function (event) {
                $(this).children().toggleClass("ui-state-hover",
                                               event.type == 'mouseover');
            });

            $this.find("th").addClass("ui-state-default");
            $this.find("td").addClass("ui-widget-content");
            $this.find("tr:last-child").addClass("last-child");
        });
    };
})(jQuery);

Differences with the original version:

  • the default CSS class has been changed to ui-styled-table (it sounds more consistent)
  • the .live call was replaced with the recommended .on for jQuery 1.7 upwards
  • the explicit conditional has been replaced by .toggleClass (a terser equivalent)
  • code that sets the misleadingly-named CSS class first on table cells has been removed
  • the code that dynamically adds .last-child to the last table row is necessary to fix a visual glitch on Internet Explorer 7 and Internet Explorer 8; for browsers that support :last-child it is not necessary

CSS

/* Internet Explorer 7: setting "separate" results in bad visuals; all other browsers work fine with either value. */
/* If set to "separate", then this rule is also needed to prevent double vertical borders on hover:
table.ui-styled-table tr * + th, table.ui-styled-table tr * + td  { border-left-width: 0px !important; } */
table.ui-styled-table { border-collapse: collapse; }

/* Undo the "bolding" that jQuery UI theme may cause on hovered elements
/* Internet Explorer 7: does not support "inherit", so use a MS proprietary expression along with an Internet Explorer <= 7 targeting hack
        to make the visuals consistent across all supported browsers */
table.ui-styled-table td.ui-state-hover {
    font-weight: inherit;
    *font-weight: expression(this.parentNode.currentStyle['fontWeight']);
}

/* Initally remove bottom border for all cells. */
table.ui-styled-table th, table.ui-styled-table td { border-bottom-width: 0px !important; }

/* Hovered-row cells should show bottom border (will be highlighted) */
table.ui-styled-table tbody tr:hover th,
table.ui-styled-table tbody tr:hover td
{ border-bottom-width: 1px !important; }

/* Remove top border if the above row is being hovered to prevent double horizontal borders. */
table.ui-styled-table tbody tr:hover + tr th,
table.ui-styled-table tbody tr:hover + tr td
{ border-top-width: 0px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 7, Internet Explorer 8: selector dependent on CSS classes because of no support for :last-child */
table.ui-styled-table tbody tr.last-child th,
table.ui-styled-table tbody tr.last-child td
{ border-bottom-width: 1px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 8 BUG: if these (unsupported) selectors are added to a rule, other selectors for that rule will stop working as well! */
/* Internet Explorer 9 and later, Firefox, Chrome: make sure the visuals are working even without the CSS classes crutch. */
table.ui-styled-table tbody tr:last-child th,
table.ui-styled-table tbody tr:last-child td
{ border-bottom-width: 1px !important; }

Notes

I have tested this on Internet Explorer 7 and upwards, Firefox 11 and Google Chrome 18 and confirmed that it works perfectly. I have not tested reasonably earlier versions of Firefox and Chrome or any version of Opera; however, those browsers are well-known for good CSS support and since we are not using any bleeding-edge functionality here I assume it will work just fine there as well.

If you are not interested in Internet Explorer 7 support there is one CSS attribute (introduced with the star hack) that can go.

If you are not interested in Internet Explorer 8 support either, the CSS and JavaScript related to adding and targeting the last-child CSS class can go as well.

How do I get the base URL with PHP?

You can do it like this, but sorry my english is not good enough.

First, get home base url with this simple code..

I've tested this code on my local server and public and the result is good.

<?php

function home_base_url(){   

// first get http protocol if http or https

$base_url = (isset($_SERVER['HTTPS']) &&

$_SERVER['HTTPS']!='off') ? 'https://' : 'http://';

// get default website root directory

$tmpURL = dirname(__FILE__);

// when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website",

//convert value to http url use string replace, 

// replace any backslashes to slash in this case use chr value "92"

$tmpURL = str_replace(chr(92),'/',$tmpURL);

// now replace any same string in $tmpURL value to null or ''

// and will return value like /localhost/my_website/ or just /my_website/

$tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL);

// delete any slash character in first and last of value

$tmpURL = ltrim($tmpURL,'/');

$tmpURL = rtrim($tmpURL, '/');


// check again if we find any slash string in value then we can assume its local machine

    if (strpos($tmpURL,'/')){

// explode that value and take only first value

       $tmpURL = explode('/',$tmpURL);

       $tmpURL = $tmpURL[0];

      }

// now last steps

// assign protocol in first value

   if ($tmpURL !== $_SERVER['HTTP_HOST'])

// if protocol its http then like this

      $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/';

    else

// else if protocol is https

      $base_url .= $tmpURL.'/';

// give return value

return $base_url; 

}

?>

// and test it

echo home_base_url();

output will like this :

local machine : http://localhost/my_website/ or https://myhost/my_website 

public : http://www.my_website.com/ or https://www.my_website.com/

use home_base_url function at index.php of your website and define it

and then you can use this function to load scripts, css and content via url like

<?php

echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";

?>

will create output like this :

<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>

and if this script works fine,,!

Import SQL file into mysql

Try:

mysql -u username -p database_name < file.sql

Check MySQL Options.

Note: It is better to use the full path of the SQL file file.sql.

How does Access-Control-Allow-Origin header work?

The Access-Control-Allow-Origin response header indicates whether the response can be shared with requesting code from the given origin.

Header type Response       header
Forbidden header name      no

A response that tells the browser to allow code from any origin to access a resource will include the following:

Access-Control-Allow-Origin: *

For more info, visit here....

How to make a Python script run like a service or daemon in Linux

Use whatever service manager your system offers - for example under Ubuntu use upstart. This will handle all the details for you such as start on boot, restart on crash, etc.

Remove rows not .isin('X')

You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]

Note: for option 4 for you'll need to import numpy as np

Update: You can also use the .query method for this too. This allows for method chaining:
5. df.query("column not in @values").
where values is a list of the values that you don't want to include.

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Setting locales in terminal resolved the issue for me. Open the terminal and

  1. Check if locale settings are missing

    > locale
    LANG=
    LC_COLLATE="C"
    LC_CTYPE="UTF-8"
    LC_MESSAGES="C"
    LC_MONETARY="C"
    LC_NUMERIC="C"
    LC_TIME="C"
    LC_ALL=
    
  2. Edit ~/.profile or ~/.bashrc

    export LANG=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    
  3. Run . ~/.profile or . ~/.bashrc to read from the file.

  4. Open a new terminal window and check that the locales are properly set

    > locale
    LANG="en_US.UTF-8"
    LC_COLLATE="en_US.UTF-8"
    LC_CTYPE="en_US.UTF-8"
    LC_MESSAGES="en_US.UTF-8"
    LC_MONETARY="en_US.UTF-8"
    LC_NUMERIC="en_US.UTF-8"
    LC_TIME="en_US.UTF-8"
    LC_ALL="en_US.UTF-8"
    

ERROR 2006 (HY000): MySQL server has gone away

For Drupal 8 users looking for solution for DB import failure:

At end of sql dump file there can commands inserting data to "webprofiler" table. That's I guess some debug log file and is not really important for site to work so all this can be removed. I deleted all those inserts including LOCK TABLES and UNLOCK TABLES (and everything between). It's at very bottom of the sql file. Issue is described here:

https://www.drupal.org/project/devel/issues/2723437

But there is no solution for it beside truncating that table.

BTW I tried all solutions from answers above and nothing else helped.

OpenCV error: the function is not implemented

Don't waste your time trying to resolve this issue, this was made clear by the makers themselves. Instead of cv2.imshow() use this:

img = cv2.imread('path_to_image')
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

How to create a css rule for all elements except one class?

The negation pseudo-class seems to be what you are looking for.

table:not(.dojoxGrid) {color:red;}

It's not supported by = IE8 though.

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

If you are not using Laravel but using Eloquent package then:

use \Illuminate\Database\Capsule\Manager as Capsule;
use \Illuminate\Events\Dispatcher;
use \Illuminate\Container\Container;

$capsule = new Capsule;

$capsule->addConnection([
    // connection details
]);
// Set the event dispatcher used by Eloquent models... (optional)
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();

// Setup the Eloquent ORM...(optional unless you've used setEventDispatcher())
$capsule->bootEloquent();

// Listen for Query Events for Debug
$events = new Dispatcher;
$events->listen('illuminate.query', function($query, $bindings, $time, $name)
{
    // Format binding data for sql insertion
    foreach ($bindings as $i => $binding) {
        if ($binding instanceof \DateTime) {
            $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
        } else if (is_string($binding)) {
            $bindings[$i] = "'$binding'";`enter code here`
        }
    }

    // Insert bindings into query
    $query = str_replace(array('%', '?'), array('%%', '%s'), $query);
    $query = vsprintf($query, $bindings);

    // Debug SQL queries
    echo 'SQL: [' . $query . ']';
});

$capsule->setEventDispatcher($events);

Add table row in jQuery

If you want to add row before the <tr> first child.

$("#myTable > tbody").prepend("<tr><td>my data</td><td>more data</td></tr>");

If you want to add row after the <tr> last child.

$("#myTable > tbody").append("<tr><td>my data</td><td>more data</td></tr>");

! [rejected] master -> master (fetch first)

Please try this command to solve it -

git push origin master --force

Or

 git push origin master -f

How to determine if one array contains all elements of another array

If there are are no duplicate elements or you don't care about them, then you can use the Set class:

a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false

Behind the scenes this uses

all? { |o| set.include?(o) }

How to display data from database into textbox, and update it

Wrap your all statements in !IsPostBack condition on page load.

protected void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
      // all statements
   }
}

This will fix your issue.

Reordering arrays

Here is an immutable version for those who are interested:

function immutableMove(arr, from, to) {
  return arr.reduce((prev, current, idx, self) => {
    if (from === to) {
      prev.push(current);
    }
    if (idx === from) {
      return prev;
    }
    if (from < to) {
      prev.push(current);
    }
    if (idx === to) {
      prev.push(self[from]);
    }
    if (from > to) {
      prev.push(current);
    }
    return prev;
  }, []);
}

How to post JSON to PHP with curl

Normally the parameter -d is interpreted as form-encoded. You need the -H parameter:

curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json

Using SimpleXML to create an XML object from scratch

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.