Programs & Examples On #Jazelle

How can you program if you're blind?

What in the world would a braille keyboard even be??

There are such things as braille writers but you would never use one as an input device for a computer.

If you're simply talking about a keyboard with the braille symbols on it this would also be a very bad idea. You're going to have a lot more keys to reach while typing and it would still be slower.

Touch typing is NOT a visual skill, a blind person can do it just as well as a sighted person.

What does axis in pandas mean?

Say for example, if you use df.shape then you will get a tuple containing the number of rows & columns in the data frame as the output.

In [10]: movies_df.shape
Out[10]: (1000, 11)

In the example above, there are 1000 rows & 11 columns in the movies data frame where 'row' is mentioned in the index 0 position & 'column' in the index 1 position of the tuple. Hence 'axis=1' denotes column & 'axis=0' denotes row.

Credits: Github

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.

The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).

Numeric Type Attributes.

Which Protocols are used for PING?

Netscantools Pro Ping can do ICMP, UDP, and TCP.

class << self idiom in Ruby

I found a super simple explanation about class << self , Eigenclass and different type of methods.

In Ruby, there are three types of methods that can be applied to a class:

  1. Instance methods
  2. Singleton methods
  3. Class methods

Instance methods and class methods are almost similar to their homonymous in other programming languages.

class Foo  
  def an_instance_method  
    puts "I am an instance method"  
  end  
  def self.a_class_method  
    puts "I am a class method"  
  end  
end

foo = Foo.new

def foo.a_singleton_method
  puts "I am a singletone method"
end

Another way of accessing an Eigenclass(which includes singleton methods) is with the following syntax (class <<):

foo = Foo.new

class << foo
  def a_singleton_method
    puts "I am a singleton method"
  end
end

now you can define a singleton method for self which is the class Foo itself in this context:

class Foo
  class << self
    def a_singleton_and_class_method
      puts "I am a singleton method for self and a class method for Foo"
    end
  end
end

Retrofit and GET using parameters

Complete working example in Kotlin, I have replaced my API keys with 1111...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

Android Image View Pinch Zooming

@Override
public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

    ImageView view = (ImageView) v;
    dumpEvent(event);

    // Handle touch events here...
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
    case MotionEvent.ACTION_DOWN:
        savedMatrix.set(matrix);
        start.set(event.getX(), event.getY());
        Log.d(TAG, "mode=DRAG");
        mode = DRAG;
        break;
    case MotionEvent.ACTION_POINTER_DOWN:
        oldDist = spacing(event);
        Log.d(TAG, "oldDist=" + oldDist);
        if (oldDist > 10f) {
            savedMatrix.set(matrix);
            midPoint(mid, event);
            mode = ZOOM;
            Log.d(TAG, "mode=ZOOM");
        }
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_POINTER_UP:
        mode = NONE;
        Log.d(TAG, "mode=NONE");
        break;
    case MotionEvent.ACTION_MOVE:
        if (mode == DRAG) {
            // ...
            matrix.set(savedMatrix);
            matrix.postTranslate(event.getX() - start.x, event.getY()
                    - start.y);
        } else if (mode == ZOOM) {
            float newDist = spacing(event);
            Log.d(TAG, "newDist=" + newDist);
            if (newDist > 10f) {
                matrix.set(savedMatrix);
                float scale = newDist / oldDist;
                matrix.postScale(scale, scale, mid.x, mid.y);
            }
        }
        break;
    }

    view.setImageMatrix(matrix);
    return true;
}

private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);
    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }
    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }
    sb.append("]");
    Log.d(TAG, sb.toString());
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return FloatMath.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}

and dont forget to set scaleType property to matrix of ImageView tag like:

<ImageView
    android:id="@+id/imageEnhance"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="15dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:background="@drawable/enhanceimageframe"
    android:scaleType="matrix" >
</ImageView>

and the variables used are:

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;

Passing multiple values for a single parameter in Reporting Services

Modification of great John solution, solve:

  • "2 quotes" error
  • space after one of piece in parameter

    
    ALTER FUNCTION [dbo].[fn_MVParam]
    (@RepParam nvarchar(4000), @Delim char(1)= ',')
    RETURNS @Values TABLE (Param nvarchar(4000))AS
    BEGIN
    //2 quotes error
    set @RepParam = replace(@RepParam,char(39)+char(39),CHAR(39))
    DECLARE @chrind INT
    DECLARE @Piece nvarchar(100)
    SELECT @chrind = 1 
    WHILE @chrind > 0
    BEGIN
      SELECT @chrind = CHARINDEX(@Delim,@RepParam)
      IF @chrind  > 0
        SELECT @Piece = LEFT(@RepParam,@chrind - 1)
      ELSE
        SELECT @Piece = @RepParam
      INSERT  @Values(Param) VALUES(CAST(@Piece AS VARCHAR(300)))
      //space after one of piece in parameter: LEN(@RepParam + '1')-1
      SELECT @RepParam = RIGHT(@RepParam,LEN(@RepParam + '1')-1 - @chrind)
      IF LEN(@RepParam) = 0 BREAK
    END
    RETURN
    END
    
    

Use of Java's Collections.singletonList()?

From the javadoc

@param  the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.

example

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create an array of string objs
        String initList[] = { "One", "Two", "Four", "One",};

        // create one list
        List list = new ArrayList(Arrays.asList(initList));

        System.out.println("List value before: "+list);

        // create singleton list
        list = Collections.singletonList("OnlyOneElement");
        list.add("five"); //throws UnsupportedOperationException
        System.out.println("List value after: "+list);
    }
}

Use it when code expects a read-only list, but you only want to pass one element in it. singletonList is (thread-)safe and fast.

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

When I had this problem, I had included the mail-api.jar in my maven pom file. That's the API specification only. The fix is to replace this:

<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>

with the reference implementation of that api:

<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>

I know it has sun in the package name, but that's the latest version. I learned this from https://stackoverflow.com/a/28935760/1128668

openpyxl - adjust column width size

A slight improvement of the above accepted answer, that I think is more pythonic (asking for forgiveness is better than asking for permission)

column_widths = []
for row in workSheet.iter_rows():
    for i, cell in enumerate(row):
        try:
            column_widths[i] = max(column_widths[i], len(str(cell.value)))
        except IndexError:
            column_widths.append(len(str(cell.value)))

for i, column_width in enumerate(column_widths):
    workSheet.column_dimensions[get_column_letter(i + 1)].width = column_width

Find and replace strings in vim on multiple lines

We don't need to bother entering the current line number.

If you would like to change each foo to bar for current line (.) and the two next lines (+2), simply do:

:.,+2s/foo/bar/g

If you want to confirm before changes are made, replace g with gc:

:.,+2s/foo/bar/gc

How to auto-scroll to end of div when data is added?

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

How to printf long long

  • Your scanf() statement needs to use %lld too.
  • Your loop does not have a terminating condition.
  • There are far too many parentheses and far too few spaces in the expression

    pi += pow(-1.0, e) / (2.0*e + 1.0);
    
  • You add one on the first iteration of the loop, and thereafter zero to the value of 'pi'; this does not change the value much.
  • You should use an explicit return type of int for main().
  • On the whole, it is best to specify int main(void) when it ignores its arguments, though that is less of a categorical statement than the rest.
  • I dislike the explicit licence granted in C99 to omit the return from the end of main() and don't use it myself; I write return 0; to be explicit.

I think the whole algorithm is dubious when written using long long; the data type probably should be more like long double (with %Lf for the scanf() format, and maybe %19.16Lf for the printf() formats.

What is the difference between JSF, Servlet and JSP?

JSPs are the View component of MVC (Model View Controller). The Controller takes the incoming request and passes it to the Model, which might be a bean that does some database access. The JSP then formats the output using HTML, CSS and JavaScript, and the output then gets sent back to the requester.

What does "use strict" do in JavaScript, and what is the reasoning behind it?

This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More

To quote some interesting parts:

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

And:

Strict mode helps out in a couple ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):

// Non-strict code...

(function(){
  "use strict";

  // Define your library strictly...
})();

// Non-strict code...

Which might be helpful if you have to mix old and new code ;-)

So, I suppose it's a bit like the "use strict" you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.

Strict mode is now supported by all major browsers.

Inside native ECMAScript modules (with import and export statements) and ES6 classes, strict mode is always enabled and cannot be disabled.

What should main() return in C and C++?

The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. There were also some changes made between ISO/IEC 9899:1989 (C90) and ISO/IEC 9899:1999 (C99).

main() should be declared as either:

int main(void)
int main(int argc, char **argv)

Or equivalent. For example, int main(int argc, char *argv[]) is equivalent to the second one. In C90, the int return type can be omitted as it is a default, but in C99 and newer, the int return type may not be omitted.

If an implementation permits it, main() can be declared in other ways (e.g., int main(int argc, char *argv[], char *envp[])), but this makes the program implementation defined, and no longer strictly conforming.

The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): 0 and EXIT_SUCCESS for a successful termination, and EXIT_FAILURE for an unsuccessful termination. Any other values are non-standard and implementation defined. In C90, main() must have an explicit return statement at the end to avoid undefined behaviour. In C99 and newer, you may omit the return statement from main(). If you do, and main() finished, there is an implicit return 0.

Finally, there is nothing wrong from a standards point of view with calling main() recursively from a C program.

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

I got this error this morning, I just did a fresh install of Fedora 14 and was trying to get my local projects back online. I was missing php-mysql, I installed it via yum and the error is now gone.

How to show disable HTML select option in by default?

I know you ask how to disable the option, but I figure the end users visual outcome is the same with this solution, although it is probably marginally less resource demanding.

Use the optgroup tag, like so :

<select name="tagging">
    <optgroup label="Choose Tagging">
        <option value="Option A">Option A</option>
        <option value="Option B">Option B</option>
        <option value="Option C">Option C</option>
    </optgroup>
</select>

Understanding INADDR_ANY for socket programming

INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.

How do I read a date in Excel format in Python?

For quick and dirty:

year, month, day, hour, minute, second = xlrd.xldate_as_tuple(excelDate, wb.datemode)
whatYouWant = str(month)+'/'+str(day)+'/'+str(year)

Trying to add adb to PATH variable OSX

I added export PATH=${PATH}:/Users/mishrapranjal/android-sdks/platform-tools/ into both places .bash_profile and .profile to make sure it works. Still it wasn't working and then I looked at sarnold's tip about restarting terminal and it worked like a charm. It saved my time of adding every time this into the PATH whenever I had to run adb. Thank you guys.

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

Can I load a UIImage from a URL?

The Best and easy way to load Image via Url is by this Code:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];

    dispatch_async(dispatch_get_main_queue(), ^{
        imgView.image= [UIImage imageWithData:data];
    });
});

Replace imgUrl by your ImageURL
Replace imgView by your UIImageView.

It will load the Image in another Thread, so It will not slow down your App load.

How can I check whether a radio button is selected with JavaScript?

This would be valid for radio buttons sharing the same name, no JQuery needed.

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];

If we are talking about checkboxes and we want a list with the checkboxes checked sharing a name:

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });

How do you make a LinearLayout scrollable?

Wrap the linear layout with a <ScrollView>

See here for an example:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       xmlns:android="http://schemas.android.com/apk/res/android">
       <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <LinearLayout 
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:orientation="vertical">
                  <!-- Content here -->
            </LinearLayout>
      </ScrollView>
 </LinearLayout>

Note: fill_parent is deprecated and renamed to match_parent in API Level 8 and higher.

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Corresponding to INSERT (Transact-SQL) (SQL Server 2005) you can't omit INSERT INTO dbo.Blah and have to specify it every time or use another syntax/approach,

Adding backslashes without escaping [Python]

printing a list can also cause this problem (im new in python, so it confused me a bit too):

>>>myList = ['\\']
>>>print myList
['\\']
>>>print ''.join(myList)
\ 

similarly:

>>>myList = ['\&']
>>>print myList
['\\&']
>>>print ''.join(myList)
\&

What are named pipes?

Unix and Windows both have things called "Named pipes", but they behave differently. On Unix, a named pipe is a one-way street which typically has just one reader and one writer - the writer writes, and the reader reads, you get it?

On Windows, the thing called a "Named pipe" is an IPC object more like a TCP socket - things can flow both ways and there is some metadata (You can obtain the credentials of the thing on the other end etc).

Unix named pipes appear as a special file in the filesystem and can be accessed with normal file IO commands including the shell. Windows ones don't, and need to be opened with a special system call (after which they behave mostly like a normal win32 handle).

Even more confusing, Unix has something called a "Unix socket" or AF_UNIX socket, which works more like (but not completely like) a win32 "named pipe", being bidirectional.

How would I create a UIAlertView in Swift?

Simply do not provide otherButtonTitles in the constructor.

let alertView = UIAlertView(title: "Oops!", message: "Something
happened...", delegate: nil, cancelButtonTitle: "OK")

alertView.show()

But I do agree with Oscar, this class is deprecated in iOS 8, so there won't be no use of UIAlertView if you're doing an iOS 8 only app. Otherwise the code above will work.

Does Python have a package/module management system?

In 2019 poetry is the package and dependency manager you are looking for.

https://github.com/sdispater/poetry#why

It's modern, simple and reliable.

How to get a list of all files in Cloud Storage in a Firebase app?

You can use the following code. Here I am uploading the image to firebase storage and then I am storing the image download url to firebase database.

//getting the storage reference
            StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + getFileExtension(filePath));

            //adding the file to reference 
            sRef.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            //dismissing the progress dialog
                            progressDialog.dismiss();

                            //displaying success toast 
                            Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();

                            //creating the upload object to store uploaded image details 
                            Upload upload = new Upload(editTextName.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());

                            //adding an upload to firebase database 
                            String uploadId = mDatabase.push().getKey();
                            mDatabase.child(uploadId).setValue(upload);
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            //displaying the upload progress 
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });

Now to fetch all the images stored in firebase database you can use

//adding an event listener to fetch values
        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                //dismissing the progress dialog 
                progressDialog.dismiss();

                //iterating through all the values in database
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Upload upload = postSnapshot.getValue(Upload.class);
                    uploads.add(upload);
                }
                //creating adapter
                adapter = new MyAdapter(getApplicationContext(), uploads);

                //adding adapter to recyclerview
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                progressDialog.dismiss();
            }
        });

Fore more details you can see my post Firebase Storage Example.

GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

Remove characters before character "."

string input = "America.USA"
string output = input.Substring(input.IndexOf('.') + 1);

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

Adding a reference to System.Net.Http.Formatting.dll may cause DLL mismatch issues. Right now, System.Net.Http.Formatting.dll appears to reference version 4.5.0.0 of Newtonsoft.Json.DLL, whereas the latest version is 6.0.0.0. That means you'll need to also add a binding redirect to avoid a .NET Assembly exception if you reference the latest Newtonsoft NuGet package or DLL:

<dependentAssembly>
   <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
 </dependentAssembly> 

So an alternative solution to adding a reference to System.Net.Http.Formatting.dll is to read the response as a string and then desearalize yourself with JsonConvert.DeserializeObject(responseAsString). The full method would be:

public async Task<T> GetHttpResponseContentAsType(string baseUrl, string subUrl)
{
     using (var client = new HttpClient())
     {
         client.BaseAddress = new Uri(baseUrl);
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

         HttpResponseMessage response = await client.GetAsync(subUrl);
         response.EnsureSuccessStatusCode();
         var responseAsString = await response.Content.ReadAsStringAsync();
         var responseAsConcreteType = JsonConvert.DeserializeObject<T>(responseAsString);
         return responseAsConcreteType;
      }
}

How to parse dates in multiple formats using SimpleDateFormat

In Apache commons lang, DateUtils class we have a method called parseDate. We can use this for parsing the date.

Also another library Joda-time also have the method to parse the date.

How to use foreach with a hash reference?

foreach my $key (keys %$ad_grp_ref) {
    ...
}

Perl::Critic and daxim recommend the style

foreach my $key (keys %{ $ad_grp_ref }) {
    ...
}

out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })

Set cookie and get cookie with JavaScript

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

Adding an item to an associative array

I know this is an old question but you can use:

array_push($data, array($category => $question));

This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

array_push($data,$question);

Connection Java-MySql : Public Key Retrieval is not allowed

If you are getting the following error while connecting the mysql (either local or mysql container running the mysql):

java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed

Solution: Add the following line in your database service:

command: --default-authentication-plugin=mysql_native_password

Print to standard printer from Python?

Unfortunately, there is no standard way to print using Python on all platforms. So you'll need to write your own wrapper function to print.

You need to detect the OS your program is running on, then:

For Linux -

import subprocess
lpr =  subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)

For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html

More resources:

Print PDF document with python's win32print module?

How do I print to the OS's default printer in Python 3 (cross platform)?

Is it possible to decompile an Android .apk file?

I may also add, that nowadays it is possible to decompile Android application online, no software needed!

Here are 2 options for you:

How to combine results of two queries into a single dataset

The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2

If you had, for example, the following data:

col1  col2
a     1
b     2

col3  col4
y     98
z     99

You would end up with the following:

col1  col2  col3  col4
a     1     y     98
a     1     z     99
b     2     y     98
b     2     z     99

Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField

That would pull things together for you into however the data is related, giving you your result.

scroll up and down a div on button click using jquery

Scrolling div on click of button.

Html Code:-

 <div id="textBody" style="height:200px; width:600px; overflow:auto;">
    <!------Your content---->
 </div>

JQuery code for scrolling div:-

$(function() {
   $( "#upBtn" ).click(function(){
      $('#textBody').scrollTop($('#textBody').scrollTop()-20);
 }); 

 $( "#downBtn" ).click(function(){
     $('#textBody').scrollTop($('#textBody').scrollTop()+20);;
 }); 

});

Postman addon's like in firefox

The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).

Now I'm settled with Fiddler (Inspectors > WebView)

One line if in VB .NET

You can use the IIf function too:

CheckIt = IIf(TestMe > 1000, "Large", "Small")

Calculating the angle between the line defined by two points

in android i did this using kotlin:

private fun angleBetweenPoints(a: PointF, b: PointF): Double {
        val deltaY = abs(b.y - a.y)
        val deltaX = abs(b.x - a.x)
        return Math.toDegrees(atan2(deltaY.toDouble(), deltaX.toDouble()))
    }

Constants in Objective-C

I myself have a header dedicated to declaring constant NSStrings used for preferences like so:

extern NSString * const PPRememberMusicList;
extern NSString * const PPLoadMusicAtListLoad;
extern NSString * const PPAfterPlayingMusic;
extern NSString * const PPGotoStartupAfterPlaying;

Then declaring them in the accompanying .m file:

NSString * const PPRememberMusicList = @"Remember Music List";
NSString * const PPLoadMusicAtListLoad = @"Load music when loading list";
NSString * const PPAfterPlayingMusic = @"After playing music";
NSString * const PPGotoStartupAfterPlaying = @"Go to startup pos. after playing";

This approach has served me well.

Edit: Note that this works best if the strings are used in multiple files. If only one file uses it, you can just do #define kNSStringConstant @"Constant NSString" in the .m file that uses the string.

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

Java Error: "Your security settings have blocked a local application from running"

I faced the same issue today, and I was able to fix the issue by changing the security settings on the Java Control Panel from HIGH to MEDIUM.

Well, setting the Java Security Setting to MEDIUM permanently is not really recommended as this will allow potentialy malicious software to run on your system and not be blocked. So I suggest after running your applet you may want to change back the setting to HIGH.

Location of the Java Control Panel

Change the setting of the Control Panel

How to set dialog to show in full screen?

try

Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen)

List the queries running on SQL Server

SELECT 
    p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, t.text
FROM
    sys.dm_exec_requests as r,
    master.dbo.sysprocesses as p
    CROSS APPLY sys.dm_exec_sql_text(p.sql_handle) t
WHERE
    p.status NOT IN ('sleeping', 'background')
AND r.session_id = p.spid

And

KILL @spid

Reading images in python

From documentation:

Matplotlib can only read PNGs natively. Further image formats are supported via the optional dependency on Pillow.

So in case of PNG we may use plt.imread(). In other cases it's probably better to use Pillow directly.

How can I use jQuery to move a div across the screen

You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

To read up on this, check out this thread (from my very first Stackoverflow post no less)!

Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

jQuery.post( ) .done( ) and success:

From the doc:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

The point it is just an alternative for success callback option, and jqXHR.success() is deprecated.

Scripting SQL Server permissions

Yes, you can use a script like this to generate another script

SET NOCOUNT ON;
DECLARE @NewRole varchar(100), @SourceRole varchar(100);

-- Change as needed
SELECT @SourceRole = 'Giver', @NewRole = 'Taker';

SELECT
    state_desc + ' ' + permission_name + ' ON ' + OBJECT_NAME(major_id) + ' TO ' + @NewRole
FROM
    sys.database_permissions
WHERE
    grantee_principal_id = DATABASE_PRINCIPAL_ID(@SourceRole) AND
    -- 0 = DB,  1 = object/column, 3 = schema. 1 is normally enough
    class <= 3

This is taken from my answer here

How do I install SciPy on 64 bit Windows?

I found this solution after days.

Firstly, which Python version you want to install?

If you want for Python 2.7 version:

STEP 1:

scipy-0.19.0-cp27-cp27m-win32.whl

scipy-0.19.0-cp27-cp27m-win_amd64.whl

numpy-1.11.3+mkl-cp27-cp27m-win32.whl

numpy-1.11.3+mkl-cp27-cp27m-win_amd64.whl

If you want for Python 3.4 version:

scipy-0.19.0-cp34-cp34m-win32.whl

scipy-0.19.0-cp34-cp34m-win_amd64.whl

numpy-1.11.3+mkl-cp34-cp34m-win32.whl

numpy-1.11.3+mkl-cp34-cp34m-win_amd64.whl

If you want for Python 3.5 version:

scipy-0.19.0-cp35-cp35m-win32.whl

scipy-0.19.0-cp35-cp35m-win_amd64.whl

numpy-1.11.3+mkl-cp35-cp35m-win32.whl

numpy-1.11.3+mkl-cp35-cp35m-win_amd64.whl

If you want for Python 3.6 version:

scipy-0.19.0-cp36-cp36m-win32.whl

scipy-0.19.0-cp36-cp36m-win_amd64.whl

numpy-1.11.3+mkl-cp36-cp36m-win32.whl

numpy-1.11.3+mkl-cp36-cp36m-win_amd64.whl

Link: click

Once finishing installation, go to your directory.

For example, my directory:

cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>
pip install [where/is/your/downloaded/scipy_whl.]

STEP 2:

NumPy + MKL

From same web site based on the Python version again:

After that use same thing again in the script folder:

cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>

pip3 install [where/is/your/downloaded/numpy_whl.]

And test it in the Python folder.

Python35>python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import scipy

convert string to specific datetime format?

  <%= string_to_datetime("2011-05-19 10:30:14") %>

  def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S")
    DateTime.strptime(string, format).to_time unless string.blank?
  end

Illegal Character when trying to compile java code

I solved this by right clicking in my textEdit program file and selecting [substitutions] and un-checking smart quotes.

What's the scope of a variable initialized in an if statement?

Yes, they're in the same "local scope", and actually code like this is common in Python:

if condition:
  x = 'something'
else:
  x = 'something else'

use(x)

Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.

In other words, Python does not have block-level scopes. Be careful, though, with examples such as

if False:
    x = 3
print(x)

which would clearly raise a NameError exception.

How to create a number picker dialog?

A Simple Example:

layout/billing_day_dialog.xml

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

    <NumberPicker
        android:id="@+id/number_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/apply_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/number_picker"
        android:text="Apply" />

</RelativeLayout>

NumberPickerActivity.java

import android.app.Activity;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.NumberPicker;

public class NumberPickerActivity extends Activity 
{

  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.billing_day_dialog);
    NumberPicker np = (NumberPicker)findViewById(R.id.number_picker);
    np.setMinValue(1);// restricted number to minimum value i.e 1
    np.setMaxValue(31);// restricked number to maximum value i.e. 31
    np.setWrapSelectorWheel(true); 

    np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() 
    {

      @Override
      public void onValueChange(NumberPicker picker, int oldVal, int newVal) 
      {

       // TODO Auto-generated method stub

       String Old = "Old Value : ";

       String New = "New Value : ";

      }
    });

     Log.d("NumberPicker", "NumberPicker");

   }

}/* NumberPickerActivity */

AndroidManifest.xml : Specify theme for the activity as dialogue theme.

<activity
  android:name="org.npn.analytics.call.NumberPickerActivity"
  android:theme="@android:style/Theme.Holo.Dialog"
  android:label="@string/title_activity_number_picker" >
</activity>

Hope it will help.

How do I find out what version of WordPress is running?

From experience with WordPress 3.8.3:

(1) Login as admin (2) Click on the W menu in the upper left corner (3) Click on menu item "About WordPress".

This will take you to .../wp-admin/about.php

There it will say "Welcome to WordPress 3.8.3"

jQuery val is undefined?

You should call the events after the document is ready, like this:

$(document).ready(function () {
  // Your code
});

This is because you are trying to manipulate elements before they are rendered by the browser.

So, in the case you posted it should look something like this

$(document).ready(function () {
  var editorTitle = $('#editorTitle').val();
  var editorText = $('#editorText').html();
});

Hope it helps.

Tips: always save your jQuery object in a variable for later use and only code that really need to run after the document have loaded should go inside the ready() function.

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

How to return a html page from a restful controller in spring boot?

Replace @Restcontroller with @controller. @Restcontroller returns only content not html and jsp pages.

What is the meaning of the term "thread-safe"?

Yes and yes. It implies that data is not modified by more than one thread simultaneously. However, your program might work as expected, and appear thread-safe, even if it is fundamentally not.

Note that the unpredictablility of results is a consequence of 'race-conditions' that probably result in data being modified in an order other than the expected one.

Prevent Android activity dialog from closing on outside touch

Setting the dialog cancelable to be false is enough, and either you touch outside of the alert dialog or click the back button will make the alert dialog disappear. So use this one:

setCancelable(false)

And the other function is not necessary anymore: dialog.setCanceledOnTouchOutside(false);

If you are creating a temporary dialog and wondering there to put this line of code, here is an example:

new AlertDialog.Builder(this)
                        .setTitle("Trial Version")
                        .setCancelable(false)
                        .setMessage("You are using trial version!")
                        .setIcon(R.drawable.time_left)
                        .setPositiveButton(android.R.string.yes, null).show();

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I found the problem that was causing the HTTP error.

In the setFalse() function that is triggered by the Save button my code was trying to submit the form that contained the button.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

when I remove the document.submitForm.submit(); it works:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!

Incrementing in C++ - When to use x++ or ++x?

You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.

An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.

Edit: fixed the mixup of prefix and suffix notation

Difference between RUN and CMD in a Dockerfile

The existing answers cover most of what anyone looking at this question would need. So I'll just cover some niche areas for CMD and RUN.

CMD: Duplicates are Allowed but Wasteful

GingerBeer makes an important point: you won't get any errors if you put in more than one CMD - but it's wasteful to do so. I'd like to elaborate with an example:

FROM busybox
CMD echo "Executing CMD"
CMD echo "Executing CMD 2"

If you build this into an image and run a container in this image, then as GingerBeer states, only the last CMD will be heeded. So the output of that container will be:

Executing CMD 2

The way I think of it is that "CMD" is setting a single global variable for the entire image that is being built, so successive "CMD" statements simply overwrite any previous writes to that global variable, and in the final image that's built the last one to write wins. Since a Dockerfile executes in order from top to bottom, we know that the bottom-most CMD is the one gets this final "write" (metaphorically speaking).

RUN: Commands May not Execute if Images are Cached

A subtle point to notice about RUN is that it's treated as a pure function even if there are side-effects, and is thus cached. What this means is that if RUN had some side effects that don't change the resultant image, and that image has already been cached, the RUN won't be executed again and so the side effects won't happen on subsequent builds. For example, take this Dockerfile:

FROM busybox
RUN echo "Just echo while you work"

First time you run it, you'll get output such as this, with different alphanumeric IDs:

docker build -t example/run-echo .
Sending build context to Docker daemon  9.216kB
Step 1/2 : FROM busybox
 ---> be5888e67be6
Step 2/2 : RUN echo "Just echo while you work"
 ---> Running in ed37d558c505
Just echo while you work
Removing intermediate container ed37d558c505
 ---> 6f46f7a393d8
Successfully built 6f46f7a393d8
Successfully tagged example/run-echo:latest

Notice that the echo statement was executed in the above. Second time you run it, it uses the cache, and you won't see any echo in the output of the build:

docker build -t example/run-echo .
Sending build context to Docker daemon  9.216kB
Step 1/2 : FROM busybox
 ---> be5888e67be6
Step 2/2 : RUN echo "Just echo while you work"
 ---> Using cache
 ---> 6f46f7a393d8
Successfully built 6f46f7a393d8
Successfully tagged example/run-echo:latest

Sharing url link does not show thumbnail image on facebook

My site faces same issue too.

Using Facebook debug tool is no help at all. Fetch new data but not IMAGE CACHE.

I forced facebook to clear IMAGE CACHE by add www. into image url. In your case is remove www. and config web server redirect.

 add/remove www. in image url should solve the problem

How to check for registry value using VbScript

Try something like this:

Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

Here you have a very good tutorial, that explains, how to use the new grid classes in Bootstrap 3.

It also covers mixins etc.

How to force Chrome's script debugger to reload javascript?

Here's a shortcut to DevTools:

  1. F12 to open Chrome DevTools
  2. F1 to open DevTools Settings
  3. Check Disable cache (while DevTools is open) as shown below:

enter image description here

Note: Updated per Dimi's comment. They tend to move it so let me know or update the post if you notice that it's changed.

iOS 7 status bar overlapping UI

Place this code snippet in your MainViewController.m file in the phonegap project.

- (void)viewDidLayoutSubviews{

    if ([self respondsToSelector:@selector(topLayoutGuide)]) // iOS 7 or above
    {
        CGFloat top = self.topLayoutGuide.length;
        if(self.webView.frame.origin.y == 0){
            // We only want to do this once, or 
            // if the view has somehow been "restored" by other    code.
            self.webView.frame = CGRectMake(self.webView.frame.origin.x,
                                           self.webView.frame.origin.y + top,
                                           self.webView.frame.size.width,
                                           self.webView.frame.size.height-top);
        } 
    } 
}

How do I update all my CPAN modules to their latest versions?

An easy way to upgrade all Perl packages (CPAN modules) is the following way:

cpan upgrade /(.*)/

cpan will recognize the regular expression like this and will update/upgrade all packages installed.

A regex for version number parsing

Use regex and now you have two problems. I would split the thing on dots ("."), then make sure that each part is either a wildcard or set of digits (regex is perfect now). If the thing is valid, you just return correct chunk of the split.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also had the same problem. I used next way:

1.Added settings.xml file (~/.m2/settings.xml) with next content

<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>qq-proxya</host>
      <port>8080</port>
      <username>user</username>
      <password>passw</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>

3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !

  1. After that updated project in the Eclipse(Alt + F5) or right click on project -> Maven -> Update project

P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.

AngularJS : Custom filters and ng-repeat

One of the easiest ways to fix this is to use the $ which is the search all.

Here is a plunker that shows it working. I have changed the checkboxes to radio ( because I thought they should be complementary )..

http://plnkr.co/edit/dHzvm6hR5P8G4wPuTxoi?p=preview

If you want a very specific way of doing this ( instead of doing a generic search ) you need work with functions in the search.

The documentation is here

http://docs.angularjs.org/api/ng.filter:filter

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

Open a webpage in the default browser

or sometimes it's very easy just type Process.Start("http://www.example.com/")

then change the http://www.example.com/")

The requested operation cannot be performed on a file with a user-mapped section open

Close visual studio, delete bin , debug release folder, and start visual studio project again. that fixed my problem

How to get distinct values from an array of objects in JavaScript?

I picked up random samples and tested it against the 100,000 items as below:

let array=[]
for (var i=1;i<100000;i++){

 let j= Math.floor(Math.random() * i) + 1
  array.push({"name":"Joe"+j, "age":j})
}

And here the performance result for each:

  Vlad Bezden Time:         === > 15ms
  Travis J Time: 25ms       === > 25ms 
  Niet the Dark Absol Time: === > 30ms
  Arun Saini Time:          === > 31ms
  Mrchief Time:             === > 54ms
  Ivan Nosov Time:          === > 14374ms

Also, I want to mention, since the items are generated randomly, the second place was iterating between Travis and Niet.

How to read pdf file and write it to outputStream

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more here) :

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:\\Invoice.pdf");  // The PDF file from where you would like to extract
         File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created

Regular expression to match non-ASCII characters?

This should do it:

[^\x00-\x7F]+

It matches any character which is not contained in the ASCII character set (0-127, i.e. 0x0 to 0x7F).

You can do the same thing with Unicode:

[^\u0000-\u007F]+

For unicode you can look at this 2 resources:

Check whether a value exists in JSON object

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};

 var Duplicate= JSONObject .find(s => s.name== "cat");
        if (typeof (Duplicate) === "undefined") {
           alert("Not Exist");
           return;
        } else {
            if (JSON.stringify(Duplicate).length > 0) {
                alert("Value Exist");
                return;
            }
        }

Reset C int array to zero : the fastest way?

Here's the function I use:

template<typename T>
static void setValue(T arr[], size_t length, const T& val)
{
    std::fill(arr, arr + length, val);
}

template<typename T, size_t N>
static void setValue(T (&arr)[N], const T& val)
{
    std::fill(arr, arr + N, val);
}

You can call it like this:

//fixed arrays
int a[10];
setValue(a, 0);

//dynamic arrays
int *d = new int[length];
setValue(d, length, 0);

Above is more C++11 way than using memset. Also you get compile time error if you use dynamic array with specifying the size.

How to set the default value of an attribute on a Laravel model

You should set default values in migrations:

$table->tinyInteger('role')->default(1);

Is there a way to make Firefox ignore invalid ssl-certificates?

Try Add Exception: FireFox -> Tools -> Advanced -> View Certificates -> Servers -> Add Exception.

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Can I get image from canvas element and use it in img src tag?

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

And right click can be saved as a .PNG

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

Cheers Si

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

How to quickly and conveniently disable all console.log statements in my code?

I found a little more advanced piece of code in this url JavaScript Tip: Bust and Disable console.log:

var DEBUG_MODE = true; // Set this value to false for production

if(typeof(console) === 'undefined') {
   console = {}
}

if(!DEBUG_MODE || typeof(console.log) === 'undefined') {
   // FYI: Firebug might get cranky...
   console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time =    console.timeEnd = console.assert = console.profile = function() {};
}

Difference between if () { } and if () : endif;

I think that it really depends on your personal coding style. If you're used to C++, Javascript, etc., you might feel more comfortable using the {} syntax. If you're used to Visual Basic, you might want to use the if : endif; syntax.

I'm not sure one can definitively say one is easier to read than the other - it's personal preference. I usually do something like this:

<?php
if ($foo) { ?>
   <p>Foo!</p><?php
} else { ?>
   <p>Bar!</p><?php
}  // if-else ($foo) ?>

Whether that's easier to read than:

<?php
if ($foo): ?>
   <p>Foo!</p><?php
else: ?>
   <p>Bar!</p><?php
endif; ?>

is a matter of opinion. I can see why some would feel the 2nd way is easier - but only if you haven't been programming in Javascript and C++ all your life. :)

Is it a good practice to place C++ definitions in header files?

I think your co-worker is right as long as he does not enter in the process to write executable code in the header. The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.

By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.

CSS3 transform not working

This is merely an educated guess without seeing the rest of your HTML/CSS:

Have you applied display: block or display: inline-block to li a? If not, try it.

Otherwise, try applying the CSS3 transform rules to li instead.

What does the 'b' character do in front of a string literal?

Here's an example where the absence of b would throw a TypeError exception in Python 3.x

>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Adding a b prefix would fix the problem.

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

As people already mentioned, it could be internet problems or proxy configuration.
I found this question when I was searching about the same problem. In my case, it was proxy configuration.
Answers posted here didn't solve my issue, because every link suggest a configuration that shows the username and passoword and I can't use it.
I was searching about it elsewere and I found a configuration to be made on settings.xml, I needed to make some changes. Here is the final code:

<profiles>
    <profile>
       <id>MavenRepository</id>
           <repositories>
            <repository>
                <id>central</id>
                <url>https://repo1.maven.org/maven2</url>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
                <releases>
                    <enabled>true</enabled>
                </releases>
            </repository>
        </repositories>
    </profile>
</profiles>

<activeProfiles>
    <activeProfile>MavenRepository</activeProfile>
</activeProfiles>

I hope be useful.

The PowerShell -and conditional operator

Try like this:

if($user_sam -ne $NULL -and $user_case -ne $NULL)

Empty variables are $null and then different from "" ([string]::empty).

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

Placing border inside of div and not on its edge

A more modern solution might be to use css variables and calc. calc is widely supported but variables is not yet in IE11 (polyfills available).

:root {
  box-width: 100px;
  border-width: 1px;
}

#box {
  width: calc(var(--box-width) - var(--border-width));
}

Although this does use some calculations, which the original questions was looking to avoid. I think this is an ok time to use calculations as they are controlled by the css itself. It also has no need for additional markup or misappropriating other css properties that may be needed later on.

This solution is only really useful if a fixed height isn't needed.

Importing CSV with line breaks in Excel 2007

What just worked for me, importing into Excel directly provided that the import is done as a text format instead as csv format. M/

nodemon not working: -bash: nodemon: command not found

For nodemon: not found command I tried with many links but was not working then i tried with the below steps it worked fine.

Follow this step it worked for me.

step1 : sudo su

step2 : npm install -g nodemon --save-dev

It is working fine.

"The operation is not valid for the state of the transaction" error and transaction scope

I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?

How to compare arrays in C#?

Array.Equals() appears to only test for the same instance.

There doesn't appear to be a method that compares the values but it would be very easy to write.

Just compare the lengths, if not equal, return false. Otherwise, loop through each value in the array and determine if they match.

Disable scrolling when touch moving certain element

The ultimate solution would be setting overflow: hidden; on document.documentElement like so:

/* element is an HTML element You want catch the touch */
element.addEventListener('touchstart', function(e) {
    document.documentElement.style.overflow = 'hidden';
});

document.addEventListener('touchend', function(e) {
    document.documentElement.style.overflow = 'auto';
});

By setting overflow: hidden on start of touch it makes everything exceeding window hidden thus removing availability to scroll anything (no content to scroll).

After touchend the lock can be freed by setting overflow to auto (the default value).

It is better to append this to <html> because <body> may be used to do some styling, plus it can make children behave unexpectedly.

EDIT: About touch-action: none; - Safari doesn't support it according to MDN.

What is the order of precedence for CSS?

First of all, based on your @extend directive, it seems you're not using pure CSS, but a preprocessor such as SASS os Stylus.

Now, when we talk about "order of precedence" in CSS, there is a general rule involved: whatever rules set after other rules (in a top-down fashion) are applied. In your case, just by specifying .smallbox after .smallbox-paysummary you would be able to change the precedence of your rules.

However, if you wanna go a bit further, I suggest this reading: CSS cascade W3C specification. You will find that the precedence of a rule is based on:

  1. The current media type;
  2. Importance;
  3. Origin;
  4. Specificity of the selector, and finally our well-known rule:
  5. Which one is latter specified.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How to get the filename without the extension in Java?

Use FilenameUtils.removeExtension from Apache Commons IO

Example:

You can provide full path name or only the file name.

String myString1 = FilenameUtils.removeExtension("helloworld.exe"); // returns "helloworld"
String myString2 = FilenameUtils.removeExtension("/home/abc/yey.xls"); // returns "yey"

Hope this helps ..

Maven: Failed to read artifact descriptor

I had the same issue with eclipse where the maven build command line worked just fine BUT try this

  • go into .m2/repository and wipe the directory associated
  • run update maven dependencies in eclipse

The error goes away....why my mvn command line worked with those directories and eclipse .m2eclipse could not, I have no idea and it kinda sucks. My project is now working in eclipse again.

PHPExcel - creating multiple sheets by iteration

Complementing the coment of @Mark Baker.
Do as follow:

$titles = array('title 1', 'title 2');
$sheet = 0;
foreach($array as $value){
    if($sheet > 0){
        $objPHPExcel->createSheet();
        $sheet = $objPHPExcel->setActiveSheetIndex($sheet);
        $sheet->setTitle("$value");
        //Do you want something more here
    }else{
        $objPHPExcel->setActiveSheetIndex(0)->setTitle("$value");
    }
    $sheet++;
}  

This worked for me. And hope it works for those who need! :)

C++ unordered_map using a custom class type as the key

Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map (basic implementation of a sparse matrix):

// UnorderedMapObjectAsKey.cpp

#include <iostream>
#include <vector>
#include <unordered_map>

struct Pos
{
  int row;
  int col;

  Pos() { }
  Pos(int row, int col)
  {
    this->row = row;
    this->col = col;
  }

  bool operator==(const Pos& otherPos) const
  {
    if (this->row == otherPos.row && this->col == otherPos.col) return true;
    else return false;
  }

  struct HashFunction
  {
    size_t operator()(const Pos& pos) const
    {
      size_t rowHash = std::hash<int>()(pos.row);
      size_t colHash = std::hash<int>()(pos.col) << 1;
      return rowHash ^ colHash;
    }
  };
};

int main(void)
{
  std::unordered_map<Pos, int, Pos::HashFunction> umap;

  // at row 1, col 2, set value to 5
  umap[Pos(1, 2)] = 5;

  // at row 3, col 4, set value to 10
  umap[Pos(3, 4)] = 10;

  // print the umap
  std::cout << "\n";
  for (auto& element : umap)
  {
    std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
  }
  std::cout << "\n";

  return 0;
}

What size should TabBar images be?

According to the Apple Human Interface Guidelines:

@1x : about 25 x 25 (max: 48 x 32)

@2x : about 50 x 50 (max: 96 x 64)

@3x : about 75 x 75 (max: 144 x 96)

How to read connection string in .NET Core?

In 3.1 there is a section already defined for "ConnectionStrings"

System.Configuration.ConnnectionStringSettings

Define:

  "ConnectionStrings": {
    "ConnectionString": "..."
  }

Register:

public void ConfigureServices(IServiceCollection services)
{
     services.Configure<ConnectionStringSettings>(Configuration.GetSection("ConnectionStrings"));
}

Inject:

public class ObjectModelContext : DbContext, IObjectModelContext
{

     private readonly ConnectionStringSettings ConnectionStringSettings;

    ...

     public ObjectModelContext(DbContextOptions<ObjectModelContext> options, IOptions<ConnectionStringSettings> setting) : base(options)
    {
          ConnectionStringSettings = setting.Value;
    }

    ...
}

Use:

   public static void ConfigureContext(DbContextOptionsBuilder optionsBuilder, ConnectionStringSettings connectionStringSettings)
    {
        if (optionsBuilder.IsConfigured == false)
        {
            optionsBuilder.UseLazyLoadingProxies()
                          .UseSqlServer(connectionStringSettings.ConnectionString);
        }
    }

How to install sshpass on mac?

For the simple reason:

Andy-B-MacBook:~ l.admin$ brew install sshpass
Error: No available formula with the name "sshpass"
We won't add sshpass because it makes it too easy for novice SSH users to
ruin SSH's security.

Thus, the answer to do the curl / configure / install worked great for me on Mac.

css label width not taking effect

Do display: inline-block:

#report-upload-form label {
    padding-left:26px;
    width:125px;
    text-transform: uppercase;
    display:inline-block
}

http://jsfiddle.net/aqMN4/

HTML5 Canvas: Zooming

One option is to use css zoom feature:

$("#canvas_id").css("zoom","x%"); 

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

How to update /etc/hosts file in Docker image during "docker build"

You can not modify the host file in the image using echo in RUN step because docker daemon will maintain the file(/etc/hosts) and its content(hosts entry) when you start a container from the image.

However following can be used to achieve the same:

ENTRYPOINT ["/bin/sh", "-c" , "echo 192.168.254.10   database-server >> /etc/hosts && echo 192.168.239.62   redis-ms-server >> /etc/hosts && exec java -jar ./botblocker.jar " ]

Key to notice here is the use of exec command as docker documentation suggests. Use of exec will make the java command as PID 1 for the container. Docker interrupts will only respond to that.

See https://docs.docker.com/engine/reference/builder/#entrypoint

Changing route doesn't scroll to top in the new page

All of the answers above break expected browser behavior. What most people want is something that will scroll to the top if it's a "new" page, but return to the previous position if you're getting there through the Back (or Forward) button.

If you assume HTML5 mode, this turns out to be easy (although I'm sure some bright folks out there can figure out how to make this more elegant!):

// Called when browser back/forward used
window.onpopstate = function() { 
    $timeout.cancel(doc_scrolling); 
};

// Called after ui-router changes state (but sadly before onpopstate)
$scope.$on('$stateChangeSuccess', function() {
    doc_scrolling = $timeout( scroll_top, 50 );

// Moves entire browser window to top
scroll_top = function() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}

The way it works is that the router assumes it is going to scroll to the top, but delays a bit to give the browser a chance to finish up. If the browser then notifies us that the change was due to a Back/Forward navigation, it cancels the timeout, and the scroll never occurs.

I used raw document commands to scroll because I want to move to the entire top of the window. If you just want your ui-view to scroll, then set autoscroll="my_var" where you control my_var using the techniques above. But I think most people will want to scroll the entire page if you are going to the page as "new".

The above uses ui-router, though you could use ng-route instead by swapping $routeChangeSuccess for$stateChangeSuccess.

How can I add a variable to console.log?

Then use + to combine strings:

console.log("story " + name + " story");

How can I exclude one word with grep?

I've a directory with a bunch of files. I want to find all the files that DO NOT contain the string "speedup" so I successfully used the following command:

grep -iL speedup *

What is char ** in C?

well, char * means a pointer point to char, it is different from char array.

char amessage[] = "this is an array";  /* define an array*/
char *pmessage = "this is a pointer"; /* define a pointer*/

And, char ** means a pointer point to a char pointer.

You can look some books about details about pointer and array.

Java - How to create new Entry (key, value)

There's public static class AbstractMap.SimpleEntry<K,V>. Don't let the Abstract part of the name mislead you: it is in fact NOT an abstract class (but its top-level AbstractMap is).

The fact that it's a static nested class means that you DON'T need an enclosing AbstractMap instance to instantiate it, so something like this compiles fine:

Map.Entry<String,Integer> entry =
    new AbstractMap.SimpleEntry<String, Integer>("exmpleString", 42);

As noted in another answer, Guava also has a convenient static factory method Maps.immutableEntry that you can use.


You said:

I can't use Map.Entry itself because apparently it's a read-only object that I can't instantiate new instanceof

That's not entirely accurate. The reason why you can't instantiate it directly (i.e. with new) is because it's an interface Map.Entry.


Caveat and tip

As noted in the documentation, AbstractMap.SimpleEntry is @since 1.6, so if you're stuck to 5.0, then it's not available to you.

To look for another known class that implements Map.Entry, you can in fact go directly to the javadoc. From the Java 6 version

Interface Map.Entry

All Known Implementing Classes:

Unfortunately the 1.5 version does not list any known implementing class that you can use, so you may have be stuck with implementing your own.

How do you make a deep copy of an object?

Using Jackson to serialize and deserialize the object. This implementation does not require the object to implement the Serializable class.

  <T> T clone(T object, Class<T> clazzType) throws IOException {

    final ObjectMapper objMapper = new ObjectMapper();
    String jsonStr= objMapper.writeValueAsString(object);

    return objMapper.readValue(jsonStr, clazzType);

  }

Mercurial undo last commit

Since you can't rollback you should merge that commit into the new head you got when you pulled. If you don't want any of the work you did in it you can easily do that using this tip.

So if you've pulled and updated to their head you can do this:

hg --config ui.merge=internal:local merge

keeps all the changes in the currently checked out revision, and none of the changes in the not-checked-out revision (the one you wrote that you no longer want).

This is a great way to do it because it keeps your history accurate and complete. If 2 years from now someone finds a bug in what you pulled down you can look in your (unused but saved) implementation of the same thing and go, "oh, I did it right". :)

Get a JSON object from a HTTP response

This is not the exact answer for your question, but this may help you

public class JsonParser {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<Club> getNearestClubs(double lat, double lon) {
        // YOUR URL GOES HERE
        String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);

        List<Club> ret = new ArrayList<Club>();

        HttpResponse response = null;
        HttpGet getMethod = new HttpGet(getUrl);
        try {
            response = httpClient.execute(getMethod);

            // CONVERT RESPONSE TO STRING
            String result = EntityUtils.toString(response.getEntity());

            // CONVERT RESPONSE STRING TO JSON ARRAY
            JSONArray ja = new JSONArray(result);

            // ITERATE THROUGH AND RETRIEVE CLUB FIELDS
            int n = ja.length();
            for (int i = 0; i < n; i++) {
                // GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
                JSONObject jo = ja.getJSONObject(i);

                // RETRIEVE EACH JSON OBJECT'S FIELDS
                long id = jo.getLong("id");
                String name = jo.getString("name");
                String address = jo.getString("address");
                String country = jo.getString("country");
                String zip = jo.getString("zip");
                double clat = jo.getDouble("lat");
                double clon = jo.getDouble("lon");
                String url = jo.getString("url");
                String number = jo.getString("number");

                // CONVERT DATA FIELDS TO CLUB OBJECT
                Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
                ret.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // RETURN LIST OF CLUBS
        return ret;
    }

}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:

JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

How to pass optional arguments to a method in C++?

An important rule with respect to default parameter usage:
Default parameters should be specified at right most end, once you specify a default value parameter you cannot specify non default parameter again. ex:

int DoSomething(int x, int y = 10, int z) -----------> Not Allowed

int DoSomething(int x, int z, int y = 10) -----------> Allowed 

regex string replace

Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:

str = str.replace(/[^-a-z0-9]+/g, "");

Also, if you need to match upper-case letters along with lower case, you should use:

str = str.replace(/[^-a-zA-Z0-9]+/g, "");

How do I set session timeout of greater than 30 minutes

Setting the timeout in the web.xml is the correct way to set the timeout.

DateDiff to output hours and minutes

Since any DateTime can be cast to a float, and the decimal part of the number represent the time itself:

DECLARE @date DATETIME = GETDATE()

SELECT CAST(CAST(@date AS FLOAT) - FLOOR(CAST(@date AS FLOAT)) AS DATETIME

This will result a datetime like '1900-01-01 hour of the day' you can cast it as time, timestamp or even use convert to get the formatted time.

I guess this works in any version of SQL since cast a datetime to float is compatible since version 2005.

Hope it helps.

How to SELECT by MAX(date)?

Workaround but working solution

Only if ID is autoincrement, you can search for the maximum id instead of the max date. So, by the ID you can find all others fields.

select *
from table
where id IN ( 
              select max(id)
              from table
              group by #MY_FIELD#
              )

MySQL convert date string to Unix timestamp

You will certainly have to use both STR_TO_DATE to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP to get the timestamp from it.

Given the format of your date, something like

UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))

Will gives you a valid timestamp. Look the STR_TO_DATE documentation to have more information on the format string.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

If your problem is like the following while using Google Chrome:

[XMLHttpRequest cannot load file. Received an invalid response. Origin 'null' is therefore not allowed access.]

Then create a batch file by following these steps:

Open notepad in Desktop.

  1. Just copy and paste the followings in your currently opened notepad file:

start "chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files exit

  1. Note: In the previous line, Replace the full absolute address with your location of chrome installation. [To find it...Right click your short cut of chrome.exe link or icon and Click on Properties and copy-paste the target link][Remember : start to files in one line, & exit in another line by pressing enter]
  2. Save the file as fileName.bat [Very important: .bat]
  3. If you want to change the file later then right-click on the .bat file and click on edit. After modifying, save the file.

This will do what? It will open Chrome.exe with file access. Now, from any location in your computer, browse your html files with Google Chrome. I hope this will solve the XMLHttpRequest problem.

Keep in mind : Just use the shortcut bat file to open Chrome when you require it. Tell me if it solves your problem. I had a similar problem and I solved it in this way. Thanks.

How open PowerShell as administrator from the run window

Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd for the search term.

image of win 10 start menu
(source: winaero.com)

Running a cron job at 2:30 AM everyday

As an addition to the all above mentioned great answers, check the https://crontab.guru/ - a useful online resource for checking your crontab syntax.

What you get is human readable representation of what you have specified.

See the examples below:

Print DIV content by JQuery

I prefer this one, I have tested it and its working

https://github.com/jasonday/printThis

$("#mySelector").printThis();

or

$("#mySelector").printThis({
*      debug: false,              * show the iframe for debugging
*      importCSS: true,           * import page CSS
*      printContainer: true,      * grab outer container as well as the contents of the selector
*      loadCSS: "path/to/my.css", * path to additional css file
*      pageTitle: "",             * add title to print page
*      removeInline: false        * remove all inline styles from print elements
*  });

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

If you want to fill NaN for a specific column you can use loc:

d1 = {"Col1" : ['A', 'B', 'C'],
     "fruits": ['Avocado', 'Banana', 'NaN']}
d1= pd.DataFrame(d1)

output:

Col1    fruits
0   A   Avocado
1   B   Banana
2   C   NaN


d1.loc[ d1.Col1=='C', 'fruits' ] =  'Carrot'


output:

Col1    fruits
0   A   Avocado
1   B   Banana
2   C   Carrot

Java command not found on Linux

I use the following script to update the default alternative after install jdk.

#!/bin/bash
export JAVA_BIN_DIR=/usr/java/default/bin # replace with your installed directory
cd ${JAVA_BIN_DIR}
a=(java javac javadoc javah javap javaws)
for exe in ${a[@]}; do
    sudo update-alternatives --install "/usr/bin/${exe}" "${exe}" "${JAVA_BIN_DIR}/${exe}" 1
    sudo update-alternatives --set ${exe} ${JAVA_BIN_DIR}/${exe}
done

Better way to set distance between flexbox items

Use the css display: inline-flex; value.

html

<div id='box'>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
</div>

css

.box {
    display: inline-flex;
    gap: 10px; // gap between items
}

Incrementing a variable inside a Bash loop

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

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

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

my erroring sample code:

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

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

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

Find character position and update file name

If you use Excel, then the command would be Find and MID. Here is what it would look like in Powershell.

 $text = "asdfNAME=PC123456<>Diweursejsfdjiwr"

asdfNAME=PC123456<>Diweursejsfdjiwr - Randon line of text, we want PC123456

 $text.IndexOf("E=")

7 - this is the "FIND" command for Powershell

 $text.substring(10,5)

C1234 - this is the "MID" command for Powershell

 $text.substring($text.IndexOf("E=")+2,8)

PC123456 - tada it has found and cut our text

-RavonTUS

Why my regexp for hyphenated words doesn't work?

You can use this:

r'[a-z]+(?:-[a-z]+)*' 

What is the best way to call a script from another script?

This is possible in Python 2 using

execfile("test2.py")

See the documentation for the handling of namespaces, if important in your case.

In Python 3, this is possible using (thanks to @fantastory)

exec(open("test2.py").read())

However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.

c# search string in txt file

If you whant only one first string, you can use simple for-loop.

var lines = File.ReadAllLines(pathToTextFile);

var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
   if(!firstFound && lines[index].Contains("CustomerEN"))
   {
      firstFound = true;
   }
   if(firstFound && lines[index].Contains("CustomerCh"))
   {
      //do, what you want, and exit the loop
      // return lines[index];
   }
}

What is the unix command to see how much disk space there is and how much is remaining?

If you want to see how much space each folder ocuppes:

du -sh *

  • s – summarize
  • h – human readable
  • * – list of folders

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

".addEventListener is not a function" why does this error occur?

_x000D_
_x000D_
var comment = document.getElementsByClassName("button");_x000D_
_x000D_
function showComment() {_x000D_
  var place = document.getElementById('textfield');_x000D_
  var commentBox = document.createElement('textarea');_x000D_
  place.appendChild(commentBox);_x000D_
}_x000D_
_x000D_
for (var i in comment) {_x000D_
  comment[i].onclick = function() {_x000D_
    showComment();_x000D_
  };_x000D_
}
_x000D_
<input type="button" class="button" value="1">_x000D_
<input type="button" class="button" value="2">_x000D_
<div id="textfield"></div>
_x000D_
_x000D_
_x000D_

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

Rotate and translate

There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.

.item {
  writing-mode: vertical-rl;
}

CSS:writing-mode

Outline effect to text

I had this issue as well, and the text-shadow wasn't an option because the corners would look bad (unless I had many many shadows), and I didn't want any blur, therefore my only other option was to do the following: Have 2 divs, and for the background div, put a -webkit-text-stroke on it, which then allows for as big of an outline as you like.

_x000D_
_x000D_
div {_x000D_
  font-size: 200px;_x000D_
  position: absolute;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
_x000D_
.front {_x000D_
 color: blue;_x000D_
}_x000D_
_x000D_
.outline {_x000D_
  -webkit-text-stroke: 30px red;_x000D_
  user-select: none;_x000D_
}
_x000D_
<div class="outline">_x000D_
 outline text_x000D_
</div>_x000D_
_x000D_
<div class="front">_x000D_
 outline text_x000D_
</div>  
_x000D_
_x000D_
_x000D_

Using this, I was able to achieve an outline, because the stroke-width method was not an option if you want your text to remain legible with a very large outline (because with stroke-width the outline will start inside the lettering which makes it not legible when the width gets larger than the letters.

Note: the reason I needed such a fat outline was I was emulating the street labels in "google maps" and I wanted a fat white halo around the text. This solution worked perfectly for me.

Here is a fiddle showing this solution

enter image description here

how to fire event on file select

Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm

  $('#myFile').change(function () {
    LoadFile("myFile");//function to do processing of file.
    $('#myFile').val('');// set the value to empty of myfile control.
    });

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.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

Try the code below. It will work if you enter multiple lines in a single column.

create table  products (prod_id number , prod_desc varchar2(50));

insert into products values(1,'test first

test second

test third');

select replace(replace(prod_desc,chr(10),' '),chr(13),' ') from products  where prod_id=2; 

Output :test first test second test third

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

Force a screen update in Excel VBA

@Hubisans comment worked best for me.

ActiveWindow.SmallScroll down:=1
ActiveWindow.SmallScroll up:=1

Difference between single and double quotes in Bash

If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.

For example, this

#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'

will give this:

double quotes gives you sometext
single quotes gives you $MYVAR

Make an HTTP request with android

With a thread:

private class LoadingThread extends Thread {
    Handler handler;

    LoadingThread(Handler h) {
        handler = h;
    }
    @Override
    public void run() {
        Message m = handler.obtainMessage();
        try {
            BufferedReader in = 
                new BufferedReader(new InputStreamReader(url.openStream()));
            String page = "";
            String inLine;

            while ((inLine = in.readLine()) != null) {
                page += inLine;
            }

            in.close();
            Bundle b = new Bundle();
            b.putString("result", page);
            m.setData(b);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        handler.sendMessage(m);
    }
}

How to upload images into MySQL database using PHP code

Firstly, you should check if your image column is BLOB type!

I don't know anything about your SQL table, but if I'll try to make my own as an example.

We got fields id (int), image (blob) and image_name (varchar(64)).

So the code should look like this (assume ID is always '1' and let's use this mysql_query):

$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
    echo "Something went wrong! :("; 
}

You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.

Also your HTML form is out of standards. It should look like this:

<form action="insert_product.php" method="POST" enctype="multipart/form-data">
    <label>File: </label><input type="file" name="image" />
    <input type="submit" />
</form>

Sidenote:

When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string(), otherwise it will result in a syntax error.

How do you remove duplicates from a list whilst preserving order?

Edit 2020

As of CPython/PyPy 3.6 (and as a language guarantee in 3.7), plain dict is insertion ordered, and even more efficient than the (also C implemented) collections.OrderedDict. So the fastest solution, by far, is also the simplest:

>>> items = [1, 2, 0, 1, 3, 2]
>>> list(dict.fromkeys(items))
[1, 2, 0, 3]

Like list(set(items)) this pushes all the work to the C layer (on CPython), but since dicts are insertion ordered, dict.fromkeys doesn't lose ordering. It's slower than list(set(items)) (takes 50-100% longer typically), but much faster than any other order-preserving solution (takes about half the time of hacks involving use of sets in a listcomp).

Edit 2016

As Raymond pointed out, in python 3.5+ where OrderedDict is implemented in C, the list comprehension approach will be slower than OrderedDict (unless you actually need the list at the end - and even then, only if the input is very short). So the best solution for 3.5+ is OrderedDict.

Important Edit 2015

As @abarnert notes, the more_itertools library (pip install more_itertools) contains a unique_everseen function that is built to solve this problem without any unreadable (not seen.add) mutations in list comprehensions. This is also the fastest solution too:

>>> from  more_itertools import unique_everseen
>>> items = [1, 2, 0, 1, 3, 2]
>>> list(unique_everseen(items))
[1, 2, 0, 3]

Just one simple library import and no hacks. This comes from an implementation of the itertools recipe unique_everseen which looks like:

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

In Python 2.7+ the accepted common idiom (which works but isn't optimized for speed, I would now use unique_everseen) for this uses collections.OrderedDict:

Runtime: O(N)

>>> from collections import OrderedDict
>>> items = [1, 2, 0, 1, 3, 2]
>>> list(OrderedDict.fromkeys(items))
[1, 2, 0, 3]

This looks much nicer than:

seen = set()
[x for x in seq if x not in seen and not seen.add(x)]

and doesn't utilize the ugly hack:

not seen.add(x)

which relies on the fact that set.add is an in-place method that always returns None so not None evaluates to True.

Note however that the hack solution is faster in raw speed though it has the same runtime complexity O(N).

How do I define a method in Razor?

You mean inline helper?

@helper SayHello(string name)
{
    <div>Hello @name</div>
}

@SayHello("John")

Inserting a PDF file in LaTeX

I don't think there would be an automatic way. You might also want to add a page number to the appendix correctly. Assuming that you already have your pdf document of several pages, you'll have to extract each page first of your pdf document using Adobe Acrobat Professional for instance and save each of them as a separate pdf file. Then you'll have to include each of the the pdf documents as images on an each page basis (1 each page) and use newpage between each page e,g,

\appendix
\section{Quiz 1}\label{sec:Quiz}
\begin{figure}[htp] \centering{
\includegraphics[scale=0.82]{quizz.pdf}}
\caption{Experiment 1}
\end{figure}  

\newpage
\section{Sample paper}\label{sec:Sample}
\begin{figure}[htp] \centering{
\includegraphics[scale=0.75]{sampaper.pdf}}
\caption{Experiment 2}
\end{figure}

Now each page will appear with 1 pdf image per page and you'll have a correct page number at the bottom. As shown in my example, you'll have to play a bit with the scale factor for each image to get it in the right size that will fit on a single page. Hope that helps...

Regex, every non-alphanumeric character except white space or colon

[^a-zA-Z\d\s:]
  • \d - numeric class
  • \s - whitespace
  • a-zA-Z - matches all the letters
  • ^ - negates them all - so you get - non numeric chars, non spaces and non colons

Check if textbox has empty value

var inp = $("#txt").val();
if(jQuery.trim(inp).length > 0)
{
   //do something
}

Removes white space before checking. If the user entered only spaces then this will still work.

Conversion failed when converting the nvarchar value ... to data type int

I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:

Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.

Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.

As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

how to destroy bootstrap modal window completely?

I have to destroy the modal right after it is closed through a button click, and so I came up with the following.

$("#closeModal").click(function() {
    $("#modal").modal('hide').on('hidden.bs.modal', function () {
        $("#modal").remove();
    });
});

Note that this works with Bootstrap 3.

Forcing Internet Explorer 9 to use standards document mode

I tried with an alternate method:

Hit F12 key Then, at right hand side in the drop down menu, select internet explorer version 9.

That's it and it worked for me.

Is there a way to check if a file is in use?

You can suffer from a thread race condition on this which there are documented examples of this being used as a security vulnerability. If you check that the file is available, but then try and use it you could throw at that point, which a malicious user could use to force and exploit in your code.

Your best bet is a try catch / finally which tries to get the file handle.

try
{
   using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))
   {
        // File/Stream manipulating code here
   }
} catch {
  //check here why it failed and ask user to retry if the file is in use.
}

how to call a function from another function in Jquery

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

Removing all script tags from html with JS Regular Expression

Here are a variety of shell scripts you can use to strip out different elements.

# doctype
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/<\!DOCTYPE\s\+html[^>]*>/<\!DOCTYPE html>/gi" {} \;

# meta charset
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/<meta[^>]*content=[\"'][^\"']*utf-8[\"'][^>]*>/<meta charset=\"utf-8\">/gi" {} \;

# script text/javascript
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<script[^>]*\)\(\stype=[\"']text\/javascript[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# style text/css
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<style[^>]*\)\(\stype=[\"']text\/css[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# html xmlns
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<html[^>]*\)\(\sxmlns=[\"'][^\"']*[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

# html xml:lang
find . -regex ".*\.\(html\|py\)$" -type f -exec sed -i "s/\(<html[^>]*\)\(\sxml:lang=[\"'][^\"']*[\"']\)\(\s\?[^>]*>\)/\1\3/gi" {} \;

How do I set a ViewModel on a window in XAML using DataContext property?

You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.

See this article for an example.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"

Explanation : [How it works]

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

Hope it work

Other warning

objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int

Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"

[caution: It may void other warning of 64 Bits architecture conversion].

PHP is_numeric or preg_match 0-9 validation

is_numeric() allows any form of number. so 1, 3.14159265, 2.71828e10 are all "numeric", while your regex boils down to the equivalent of is_int()

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

Invoking a jQuery function after .each() has completed

It's probably to late but i think this code work...

$blocks.each(function(i, elm) {
 $(elm).fadeOut(200, function() {
  $(elm).remove();
 });
}).promise().done( function(){ alert("All was done"); } );

How to run multiple Python versions on Windows

The easiest way to run multiple versions of python on windows is described below as follows:-

1)Download the latest versions of python from python.org/downloads by selecting the relevant version for your system.

2)Run the installer and select Add python 3.x to the path to set path automatically in python 3 (you just have to click the checkbox). For python 2 open up your python 2 installer, select whatever preferences you want but just remember to set Add python.exe to path to Will be installed on local hard drive, Now just click next and wait for the installer to finish.

3)When both the installations are complete. Right click on my computer--Go to properties--Select advanced system settings--Go to environment variables--Click on new under System variables and add a new system variable with variable name as PY_PYTHON and set this variable value to 3. Now click on OK and you should be done.

4)Now to test this open the command prompt. Once you are in there type python or py, It should open up python3.

5)Now exit out of python3 by typing exit(). Now type py -2 it should open python 2.

If none of this works then restart the computer and if the problem still persists then uninstall everything and repeat the steps.

Thanks.

Javascript set img src

Wow! when you use src then src of searchPic must be used also.

document["pic1"].src = searchPic.src

looks better

Convert from lowercase to uppercase all values in all character variables in dataframe

From the dplyr package you can also use the mutate_all() function in combination with toupper(). This will affect both character and factor classes.

library(dplyr)
df <- mutate_all(df, funs=toupper)

Java: Check the date format of current string is according to required format or not

You can try this to simple date format valdation

 public Date validateDateFormat(String dateToValdate) {

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HHmmss");
    //To make strict date format validation
    formatter.setLenient(false);
    Date parsedDate = null;
    try {
        parsedDate = formatter.parse(dateToValdate);
        System.out.println("++validated DATE TIME ++"+formatter.format(parsedDate));

    } catch (ParseException e) {
        //Handle exception
    }
    return parsedDate;
}

In Visual Studio Code How do I merge between two local branches?

You can do it without using plugins.

In the latest version of vscode that I'm using (1.17.0) you can simply open the branch that you want (from the bottom left menu) then press ctrl+shift+p and type Git: Merge branch and then choose the other branch that you want to merge from (to the current one)

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

Javascript array search and remove string?

Simple solution (ES6)

If you don't have duplicate element

Array.prototype.remove = function(elem) {
  var indexElement = this.findIndex(el => el === elem);
  if (indexElement != -1)
    this.splice(indexElement, 1);
  return this;
};   

Online demo (fiddle)

Send email with PHP from html form on submit with the same script

If you haven't already, look at your php.ini and make sure the parameters under the [mail function] setting are set correctly to activate the email service. After you can use PHPMailer library and follow the instructions.

Compiling and Running Java Code in Sublime Text 2

By following the steps below, you will have 2 Build Systems in sublime - "JavaC" and "JavaC_Input".

"JavaC" would let you run code that doesn't require user input and display the results in sublime's terminal simulator, which is convenient and nice-looking. "JavaC_Input" lets you run code that requires user input in a separate terminal window, it's able to accept user input. You can also run non-input-requiring code in this build system, so if you don't mind the pop-up, you can just stick with this build system and don't switch. You switch between build systems from Tools -> Build System. And you compile&run code using ctrl+b.

Here are the steps to achieve this:

(note: Make sure you already have the basic setup of the java system: install JDK and set up correct CLASSPATH and PATH, I won't elaborate on this)

"JavaC" build system setup

1, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec.bat".

@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1

2, Then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build (if there isn't any, create one), the contents will be

{
   "cmd": ["javacexec.bat", "$file"],
   "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
   "selector": "source.java"
}

"JavaC_Input" build system setup

1, Install Cygwin [http://www.cygwin.com/]

2, Go to C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\, then create a file called "JavaC_Input.sublime-build" with the following content

{
"cmd": ["javacexec_input.bat", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}

3, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec_input.bat".

@echo off
javac  -Xlint:unchecked %~n1.java 
start cmd /k java -ea %~n1

Is a new line = \n OR \r\n?

If you are programming in PHP, it is useful to split lines by \n and then trim() each line (provided you don't care about whitespace) to give you a "clean" line regardless.

foreach($line in explode("\n", $data))
{
    $line = trim($line);
    ...
}

Removing specific rows from a dataframe

One simple solution:

cond1 <- df$sub == 1 & df$day == 2

cond2 <- df$sub == 3 & df$day == 4

df <- df[!(cond1 | cond2),]

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

Splitting a dataframe string column into multiple different columns

Is this what you are trying to do?

# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)

#  Split into individual elements by the '.' character
#  Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )

#  We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )

#  Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
#  V1 V2  V3  V4
#1  F US CLE V13
#2  F US CA6 U13
#3  F US CA6 U13
#4  F US CA6 U13
#5  F US CA6 U13
#6  F US CA6 U13

Count number of occurrences for each unique value

If i am understanding your question, would this work? (you will have to replace with your actual column and table names)

SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3

Which type of folder structure should be used with Angular 2?

If project is small and will remain small, I would recommend to structure by type (Method 2: ng-book2)

app
|- components
|  |- hero
|  |- hero-list
|  |- villain
|  |- ...
|- services
|  |- hero.service.ts
|  |- ...
|- utils
|- shared

If project will grow you should structure your folders by domain (Method 3: mgechev/angular2-seed)

app
|- heroes
|  |- hero
|  |- hero-list
|  |- hero.service.ts
|- villains
|  |- villain
|  |- ...
|- utils
|- shared

Better to Follow official docs.
https://angular.io/guide/styleguide#application-structure-and-ngmodules

getCurrentPosition() and watchPosition() are deprecated on insecure origins

You could use the https://ipinfo.io API for this (it's my service). It's free for up to 1,000 req/day (with or without SSL support). It gives you coordinates, name and more. Here's an example:

curl ipinfo.io
{
  "ip": "172.56.39.47",
  "hostname": "No Hostname",
  "city": "Oakland",
  "region": "California",
  "country": "US",
  "loc": "37.7350,-122.2088",
  "org": "AS21928 T-Mobile USA, Inc.",
  "postal": "94621"
}

Here's an example which constructs a coords object with the API response that matches what you get from getCurrentPosition():

$.getJSON('https://ipinfo.io/geo', function(response) { 
    var loc = response.loc.split(',');
    var coords = {
        latitude: loc[0],
        longitude: loc[1]
    };
});

And here's a detailed example that shows how you can use it as a fallback for getCurrentPosition():

function do_something(coords) {
    // Do something with the coords here
}

navigator.geolocation.getCurrentPosition(function(position) { 
    do_something(position.coords);
    },
    function(failure) {
        $.getJSON('https://ipinfo.io/geo', function(response) { 
        var loc = response.loc.split(',');
        var coords = {
            latitude: loc[0],
            longitude: loc[1]
        };
        do_something(coords);
        });  
    };
});

See http://ipinfo.io/developers/replacing-navigator-geolocation-getcurrentposition for more details.

Getting values from JSON using Python

Using Python to extract a value from the provided Json

Working sample:-

import json
import sys

//load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

//dumps the json object into an element
json_str = json.dumps(data)

//load the json to a string
resp = json.loads(json_str)

//print the resp
print (resp)

//extract an element in the response
print (resp['test1'])

Perform Button click event when user press Enter key in Textbox

You can do it with javascript/jquery:

<script>
    function runScript(e) {
        if (e.keyCode == 13) {
            $("#myButton").click(); //jquery
            document.getElementById("myButton").click(); //javascript
        }
    }
</script>

<asp:textbox id="txtUsername" runat="server" onkeypress="return runScript(event)" />

<asp:LinkButton id="myButton" text="Login" runat="server" />

Android SDK location should not contain whitespace, as this cause problems with NDK tools

As long as you aren't using the NDK you can just ignore that warning.

By the way: This warning has nothing to do with parallel installations.