Programs & Examples On #Hook

Hook is a broad programming term that usually refers to replacing default behavior with a custom behavior or injecting a listener into a stream of activity.

How to configure Git post commit hook

As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:

#!/usr/bin/python

import sys
from subprocess import call

if __name__ == '__main__':
    for line in sys.stdin.xreadlines():
        old, new, ref = line.strip().split(' ')
        if ref == 'refs/heads/master':
            print "=============================================="
            print "Pushing to master. Triggering jenkins.        "
            print "=============================================="
            sys.stdout.flush()
            call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])

In this case I trigger jenkins jobs only when pushing to master and not other branches.

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

hooks can be executed when some condition is encountered. e.g. some variable changes or some action is called or some event happens. hooks can enter in the process and change things or react upon changes.

changing source on html5 video tag

Just put a div and update the content...

<script>
function setvideo(src) {
    document.getElementById('div_video').innerHTML = '<video autoplay controls id="video_ctrl" style="height: 100px; width: 100px;"><source src="'+src+'" type="video/mp4"></video>';
    document.getElementById('video_ctrl').play();
}
</script>
<button onClick="setvideo('video1.mp4');">Video1</button>
<div id="div_video"> </div>

How do I make the method return type generic?

As you said passing a class would be OK, you could write this:

public <T extends Animal> T callFriend(String name, Class<T> clazz) {
   return (T) friends.get(name);
}

And then use it like this:

jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();

Not perfect, but this is pretty much as far as you get with Java generics. There is a way to implement Typesafe Heterogenous Containers (THC) using Super Type Tokens, but that has its own problems again.

Using HTML5/JavaScript to generate and save a file

Here is a link to the data URI method Mathew suggested, it worked on safari, but not well because I couldn't set the filetype, it gets saved as "unknown" and then i have to go there again later and change it in order to view the file...

http://www.nihilogic.dk/labs/canvas2image/

React Router with optional path parameter

for react-router V5 and above use below syntax for multiple paths

<Route
          exact
          path={[path1, path2]}
          component={component}
        />

linux shell script: split string, put them in an array then loop through them

You can probably skip the step of explicitly creating an array...

One trick that I like to use is to set the inter-field separator (IFS) to the delimiter character. This is especially handy for iterating through the space or return delimited results from the stdout of any of a number of unix commands.

Below is an example using semicolons (as you had mentioned in your question):

export IFS=";"
sentence="one;two;three"
for word in $sentence; do
  echo "$word"
done

Note: in regular Bourne-shell scripting setting and exporting the IFS would occur on two separate lines (IFS='x'; export IFS;).

Get filename and path from URI from mediastore

Since managedQuery has been deprecated, you could try:

CursorLoader cursorLoader = new CursorLoader(context, uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();

Python function as a function argument?

  1. Yes, it's allowed.
  2. You use the function as you would any other: anotherfunc(*extraArgs)

Compare two files and write it to "match" and "nomatch" files

In Eztrieve it's really easy, below is an example how you could code it:

//STEP01   EXEC PGM=EZTPA00                                        
//FILEA    DD DSN=FILEA,DISP=SHR   
//FILEB    DD DSN=FILEB,DISP=SHR
//FILEC    DD DSN=FILEC.DIF,    
//            DISP=(NEW,CATLG,DELETE),                             
//            SPACE=(CYL,(100,50),RLSE),                           
//            UNIT=PRMDA,                                          
//            DCB=(RECFM=FB,LRECL=5200,BLKSIZE=0)                  
//SYSOUT   DD SYSOUT=*                                             
//SRTMSG   DD SYSOUT=*                                             
//SYSPRINT DD SYSOUT=*                                             
//SYSIN    DD *                                                    
 FILE FILEA                                                        
   FA-KEY       1   7 A                                         
   FA-REC1      8  10 A
   FA-REC2     18   5 A

 FILE FILEB                                                        
   FB-KEY       1   7 A                                         
   FB-REC1      8  10 A                                         
   FB-REC2     18   5 A                                         

 FILE FILEC                                                        

 FILE FILED                                                        
   FD-KEY       1   7 A                                         
   FD-REC1      8  10 A                                         
   FD-REC2     18   5 A                                         


 JOB INPUT (FILEA KEY FA-KEY FILEB KEY FB-KEY)                     
   IF MATCHED            
      FD-KEY   =  FB-KEY                                      
      FD-REC1  =  FA-REC1
      FD-REC2  =  FB-REC2
      PUT FILED
   ELSE
      IF FILEA
         PUT FILEC FROM FILEA                                         
      ELSE
         PUT FILEC FROM FILEB
      END-IF                                         
   END-IF                                                          
/*                       

format a Date column in a Data Frame

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)
)

require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]

Can an abstract class have a constructor?

An abstract class can have a constructor BUT you can not create an object of abstract class so how do you use that constructor?

Thing is when you inherit that abstract class in your subclass you can pass values to its(abstract's) constructor through super(value) method in your subclass and no you don't inherit a constructor.

so using super you can pass values in a constructor of the abstract class and as far as I remember it has to be the first statement in your method or constructor.

Cannot use special principal dbo: Error 15405

This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.

Splitting string into multiple rows in Oracle

I had the same problem, and xmltable helped me:

SELECT id, trim(COLUMN_VALUE) text FROM t, xmltable(('"' || REPLACE(text, ',', '","') || '"'))

Jquery onclick on div

Nothing.

$('#content').click(function(e) {  
    alert(1);
});

Will bind to an existing HTML element with the ID set to content, and will show a message box on click.

  • Make sure that #content exists before using that code
  • That the ID is unique
  • Check your Javascript console for any errors or issues

git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

https://twitter.com/Beanstalkapp/status/306129447885631488

Displaying a message in iOS which has the same functionality as Toast in Android

For the ones that using Xamarin.IOS you can do like this:

new UIAlertView(null, message, null, "OK", null).Show();

using UIKit; is required.

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Get the row(s) which have the max value in groups using groupby

Easy solution would be to apply : idxmax() function to get indices of rows with max values. This would filter out all the rows with max value in the group.

In [365]: import pandas as pd

In [366]: df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})

In [367]: df                                                                                                       
Out[367]: 
   count  mt   sp  val
0      3  S1  MM1    a
1      2  S1  MM1    n
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
5      1  S4  MM2  dgb
6      2  S2  MM4   rd
7      2  S2  MM4   cb
8      7  S2  MM4  uyi


### Apply idxmax() and use .loc() on dataframe to filter the rows with max values:
In [368]: df.loc[df.groupby(["sp", "mt"])["count"].idxmax()]                                                       
Out[368]: 
   count  mt   sp  val
0      3  S1  MM1    a
2      5  S3  MM1   cb
3      8  S3  MM2   mk
4     10  S4  MM2   bg
8      7  S2  MM4  uyi

### Just to show what values are returned by .idxmax() above:
In [369]: df.groupby(["sp", "mt"])["count"].idxmax().values                                                        
Out[369]: array([0, 2, 3, 4, 8])

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

Why doesn't java.io.File have a close method?

java.io.File doesn't represent an open file, it represents a path in the filesystem. Therefore having close method on it doesn't make sense.

Actually, this class was misnamed by the library authors, it should be called something like Path.

How to calculate age (in years) based on Date of Birth and getDate()

DECLARE @FromDate DATETIME = '1992-01-2623:59:59.000', 
        @ToDate   DATETIME = '2016-08-10 00:00:00.000',
        @Years INT, @Months INT, @Days INT, @tmpFromDate DATETIME
SET @Years = DATEDIFF(YEAR, @FromDate, @ToDate)
 - (CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, @FromDate, @ToDate),
          @FromDate) > @ToDate THEN 1 ELSE 0 END) 


SET @tmpFromDate = DATEADD(YEAR, @Years , @FromDate)
SET @Months =  DATEDIFF(MONTH, @tmpFromDate, @ToDate)
 - (CASE WHEN DATEADD(MONTH,DATEDIFF(MONTH, @tmpFromDate, @ToDate),
          @tmpFromDate) > @ToDate THEN 1 ELSE 0 END) 

SET @tmpFromDate = DATEADD(MONTH, @Months , @tmpFromDate)
SET @Days =  DATEDIFF(DAY, @tmpFromDate, @ToDate)
 - (CASE WHEN DATEADD(DAY, DATEDIFF(DAY, @tmpFromDate, @ToDate),
          @tmpFromDate) > @ToDate THEN 1 ELSE 0 END) 

SELECT @FromDate FromDate, @ToDate ToDate, 
       @Years Years,  @Months Months, @Days Days

How do I iterate through the files in a directory in Java?

As noted, this is a recursion problem. In particular, you may want to look at

listFiles() 

In the java File API here. It returns an array of all the files in a directory. Using this along with

isDirectory()

to see if you need to recurse further is a good start.

mysqldump data only

mysqldump --no-create-info ...

Also you may use:

  • --skip-triggers: if you are using triggers
  • --no-create-db: if you are using --databases ... option
  • --compact: if you want to get rid of extra comments

How can I check file size in Python?

import os


def convert_bytes(num):
    """
    this function will convert bytes to MB.... GB... etc
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % (num, x)
        num /= 1024.0


def file_size(file_path):
    """
    this function will return the file size
    """
    if os.path.isfile(file_path):
        file_info = os.stat(file_path)
        return convert_bytes(file_info.st_size)


# Lets check the file size of MS Paint exe 
# or you can use any file path
file_path = r"C:\Windows\System32\mspaint.exe"
print file_size(file_path)

Result:

6.1 MB

Remove local git tags that are no longer on the remote repository

Looks like recentish versions of Git (I'm on git v2.20) allow one to simply say

git fetch --prune --prune-tags

Much cleaner!

https://git-scm.com/docs/git-fetch#_pruning

You can also configure git to always prune tags when fetching:

git config fetch.pruneTags true

If you only want to prune tags when fetching from a specific remote, you can use the remote.<remote>.pruneTags option. For example, to always prune tags when fetching from origin but not other remotes,

git config remote.origin.pruneTags true

Clearing coverage highlighting in Eclipse

Added shortcut Ctrl+Shift+X C to Keybindings (Window -> Preferences -> filter for Keys) when 'Editing Java Source' for 'Remove Active Session'.

How to create a CPU spike with a bash command

To load 3 cores for 5 seconds:

seq 3 | xargs -P0 -n1 timeout 5 yes > /dev/null

This results in high kernel (sys) load from the many write() system calls.

If you prefer mostly userland cpu load:

seq 3 | xargs -P0 -n1 timeout 5 md5sum /dev/zero

If you just want the load to continue until you press Ctrl-C:

seq 3 | xargs -P0 -n1 md5sum /dev/zero

SQL Server 2005 Using DateAdd to add a day to a date

DECLARE @date DateTime
SET @date = GetDate()
SET @date = DateAdd(day, 1, @date)

SELECT @date

How to read line by line or a whole text file at once?

I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.

Create aar file in Android Studio

If your library is set up as an Android library (i.e. it uses the apply plugin: 'com.android.library' statement in its build.gradle file), it will output an .aar when it's built. It will show up in the build/outputs/aar/ directory in your module's directory.

You can choose the "Android Library" type in File > New Module to create a new Android Library.

How to properly stop the Thread in Java?

I didn't get the interrupt to work in Android, so I used this method, works perfectly:

boolean shouldCheckUpdates = true;

private void startupCheckForUpdatesEveryFewSeconds() {
    threadCheckChat = new Thread(new CheckUpdates());
    threadCheckChat.start();
}

private class CheckUpdates implements Runnable{
    public void run() {
        while (shouldCheckUpdates){
            System.out.println("Do your thing here");
        }
    }
}

 public void stop(){
        shouldCheckUpdates = false;
 }

How to include a Font Awesome icon in React's render()

If you are new to React JS and using create-react-app cli command to create the application, then run the following NPM command to include the latest version of font-awesome.

npm install --save font-awesome

import font-awesome to your index.js file. Just add below line to your index.js file

import '../node_modules/font-awesome/css/font-awesome.min.css'; 

or

import 'font-awesome/css/font-awesome.min.css';

Don't forget to use className as attribute

 render: function() {
    return <div><i className="fa fa-spinner fa-spin">no spinner but why</i></div>;
}

What is default color for text in textview?

I believe the default color integer value is 16711935 (0x00FF00FF).

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

The requested resource does not support HTTP method 'GET'

just use this attribute

[System.Web.Http.HttpGet]

not need this line of code:

[System.Web.Http.AcceptVerbs("GET", "POST")]

Best implementation for hashCode method for a collection

It is better to use the functionality provided by Eclipse which does a pretty good job and you can put your efforts and energy in developing the business logic.

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

How to run a method every X seconds

You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().

Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds.  One second = 1000 milliseconds.


@Override
protected void onResume() {
   //start handler as activity become visible

    handler.postDelayed( runnable = new Runnable() {
        public void run() {
            //do something

            handler.postDelayed(runnable, delay);
        }
    }, delay);

    super.onResume();
}

// If onPause() is not included the threads will double up when you 
// reload the activity 

@Override
protected void onPause() {
    handler.removeCallbacks(runnable); //stop handler when activity not visible
    super.onPause();
}

How to prompt for user input and read command-line arguments

raw_input is no longer available in Python 3.x. But raw_input was renamed input, so the same functionality exists.

input_var = input("Enter something: ")
print ("you entered " + input_var) 

Documentation of the change

Failed to resolve: com.android.support:appcompat-v7:26.0.0

you forgot to add add alpha1 in module area

compile 'com.android.support:appcompat-v7:26.0.0-alpha1'

use maven repository in project area that's it

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

Disabled form inputs do not appear in the request

To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.

<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

If you prefer jQuery:

<form onsubmit="$(this).find('input').prop('disabled', false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

For ASP.NET MVC C# Razor, you add the submit handler like this:

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
    // Re-enable all input elements on submit so they are all posted, even if currently disabled.
    new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
    <!-- form content with input elements -->
}

Switching to a TabBar tab view programmatically?

Try this code in Swift or Objective-C

Swift

self.tabBarController.selectedIndex = 1

Objective-C

[self.tabBarController setSelectedIndex:1];

Using classes with the Arduino

My Webduino library is all based on a C++ class that implements a web server on top of the Arduino Ethernet shield. I defined the whole class in a .h file that any Arduino code can #include. Feel free to look at the code to see how I do it... I ended up just defining it all inline because there's no real reason to separately compile objects with the Arduino IDE.

Twitter Bootstrap carousel different height images cause bouncing arrows

If you want to have this work with images of any height and without fixing the height, just do this:

$('#myCarousel').on("slide.bs.carousel", function(){
     $(".carousel-control",this).css('top',($(".active img",this).height()*0.46)+'px');
     $(this).off("slide.bs.carousel");
});

How to generate .angular-cli.json file in Angular Cli?

In angular.json you can insert all css and js file in your template. Other ways, you can use from Style.css in src folder for load stylesheets.

@import "../src/fonts/font-awesome/css/font-awesome.min.css";
@import "../src/css/bootstrap.min.css";
@import "../src/css/now-ui-kit.css";
@import "../src/css/plugins/owl.carousel.css";
@import "../src/css/plugins/owl.theme.default.min.css";
@import "../src/css/main.css";

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Recently I faced the issue while working on some legacy code. After googling I found that the issue is everywhere but without any concrete resolution. I worked on various parts of the exception message and analyzed below.

Analysis:

  1. SSLException: exception happened with the SSL (Secure Socket Layer), which is implemented in javax.net.ssl package of the JDK (openJDK/oracleJDK/AndroidSDK)
  2. Read error ssl=# I/O error during system call: Error occured while reading from the Secure socket. It happened while using the native system libraries/driver. Please note that all the platforms solaris, Windows etc. have their own socket libraries which is used by the SSL. Windows uses WINSOCK library.
  3. Connection reset by peer: This message is reported by the system library (Solaris reports ECONNRESET, Windows reports WSAECONNRESET), that the socket used in the data transfer is no longer usable because an existing connection was forcibly closed by the remote host. One needs to create a new secure path between the host and client

Reason:

Understanding the issue, I try finding the reason behind the connection reset and I came up with below reasons:

  • The peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close.
  • This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with Network dropped connection on reset(On Windows(WSAENETRESET)) and Subsequent operations fail withConnection reset by peer(On Windows(WSAECONNRESET)).
  • If the target server is protected by Firewall, which is true in most of the cases, the Time to live (TTL) or timeout associated with the port forcibly closes the idle connection at given timeout. this is something of our interest

Resolution:

  1. Events on the server side such as sudden service stop, rebooted, network interface disabled can not be handled by any means.
  2. On the server side, Configure firewall for the given port with the higher Time to Live (TTL) or timeout values such as 3600 secs.
  3. Clients can "try" keeping the network active to avoid or reduce the Connection reset by peer.
  4. Normally on going network traffic keeps the connection alive and problem/exception is not seen frequently. Strong Wifi has least chances of Connection reset by peer.
  5. With the mobile networks 2G, 3G and 4G where the packet data delivery is intermittent and dependent on the mobile network availability, it may not reset the TTL timer on the server side and results into the Connection reset by peer.

Here are the terms suggested to set on various forums to resolve the issue

  • ConnectionTimeout: Used only at the time out making the connection. If host takes time to connection higher value of this makes the client wait for the connection.
  • SoTimeout: Socket timeout-It says the maximum time within which the a data packet is received to consider the connection as active.If no data received within the given time, the connection is assumed as stalled/broken.
  • Linger: Upto what time the socket should not be closed when data is queued to be sent and the close socket function is called on the socket.
  • TcpNoDelay: Do you want to disable the buffer that holds and accumulates the TCP packets and send them once a threshold is reached? Setting this to true will skip the TCP buffering so that every request is sent immediately. Slowdowns in the network may be caused by an increase in network traffic due to smaller and more frequent packet transmission.

So none of the above parameter helps keeping the network alive and thus ineffective.

I found one setting that may help resolving the issue which is this functions

setKeepAlive(true)
setSoKeepalive(HttpParams params, enableKeepalive="true") 

How did I resolve my issue?

  • Set the HttpConnectionParams.setSoKeepAlive(params, true)
  • Catch the SSLException and check for the exception message for Connection reset by peer
  • If exception is found, store the download/read progress and create a new connection.
  • If possible resume the download/read else restart the download

I hope the details help. Happy Coding...

How to create an array of 20 random bytes?

If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom.

Java 6 & 7:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Java 8 (even more secure):

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

Can you have multiple $(document).ready(function(){ ... }); sections?

I think the better way to go is to put switch to named functions (Check this overflow for more on that subject). That way you can call them from a single event.

Like so:

function firstFunction() {
    console.log("first");
}

function secondFunction() {
    console.log("second");
}


function thirdFunction() {
    console.log("third");
}

That way you can load them in a single ready function.

jQuery(document).on('ready', function(){
   firstFunction();
   secondFunction();
   thirdFunction();

});

This will output the following to your console.log:

first
second
third

This way you can reuse the functions for other events.

jQuery(window).on('resize',function(){
    secondFunction();
});

Check this fiddle for working version

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

How to overcome root domain CNAME restrictions?

You have to put a period at the end of the external domain so it doesn't think you mean customer1.mycompanydomain.com.localdomain;

So just change:

customer1.com IN CNAME customer1.mycompanydomain.com

To

customer1.com IN CNAME customer1.mycompanydomain.com.

How do I 'svn add' all unversioned files to SVN?

This is as documented on svn book and the simplest and works perfect for me

svn add * --force

http://svnbook.red-bean.com/en/1.6/svn.ref.svn.c.add.html

HTML Mobile -forcing the soft keyboard to hide

For further readers/searchers:

As Rene Pot points out on this topic,

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.

This solution also works fine with date-time-pickers which generally already implement controls.

In a URL, should spaces be encoded using %20 or +?

Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded: this specifies + for spaces.

URLs are encoded as RFC 1738 which specifies %20.

In theory I think you should have %20 before the ? and + after:

example.com/foo%20bar?foo+bar

How to transfer some data to another Fragment?

Just to extend previous answers - it could help someone. If your getArguments() returns null, put it to onCreate() method and not to constructor of your fragment:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int index = getArguments().getInt("index");
}

What is the JavaScript equivalent of var_dump or print_r in PHP?

Firebug.

Then, in your javascript:

var blah = {something: 'hi', another: 'noway'};
console.debug("Here is blah: %o", blah);

Now you can look at the console, click on the statement and see what is inside blah

How to handle notification when app in background in Firebase

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

}

is not called every time it is called only when app is in forground

there is one override method this method is called every time , no matter what app is in foreground or in background or killed but this method is available with this firebase api version

this is the version u have to import from gradle

compile 'com.google.firebase:firebase-messaging:10.2.1'

this is the method

@Override
public void handleIntent(Intent intent) {
    super.handleIntent(intent);

    // you can get ur data here 
    //intent.getExtras().get("your_data_key") 


}

with previous firebase api this method was not there so in that case fire base handle itself when app is in background .... now u have this method what ever u want to do ... u can do it here in this method .....

if you are using previous version than default activity will start in that case u can get data same way

if(getIntent().getExtras() != null && getIntent().getExtras().get("your_data_key") != null) {
String strNotificaiton = getIntent().getExtras().get("your_data_key").toString();

// do what ever u want .... }

generally this is the structure from server we get in notification

{
    "notification": {
        "body": "Cool offers. Get them before expiring!",
        "title": "Flat 80% discount",
        "icon": "appicon",
        "click_action": "activity name" //optional if required.....
    },
    "data": {
        "product_id": 11,
        "product_details": "details.....",
        "other_info": "......."
    }
}

it's up to u how u want to give that data key or u want give notification anything u can give ....... what ever u will give here with same key u will get that data .........

there are few cases if u r not sending click action in that case when u will click on notification default activity will open , but if u want to open your specific activity when app is in background u can call your activity from this on handleIntent method because this is called every time

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

If you keep on allocating & keeping references to object, you will fill up any amount of memory you have.

One option is to do a transparent file close & open when they switch tabs (you only keep a pointer to the file, and when the user switches tab, you close & clean all the objects... it'll make the file change slower... but...), and maybe keep only 3 or 4 files on memory.

Other thing you should do is, when the user opens a file, load it, and intercept any OutOfMemoryError, then (as it is not possible to open the file) close that file, clean its objects and warn the user that he should close unused files.

Your idea of dynamically extending virtual memory doesn't solve the issue, for the machine is limited on resources, so you should be carefull & handle memory issues (or at least, be carefull with them).

A couple of hints i've seen with memory leaks is:

--> Keep on mind that if you put something into a collection and afterwards forget about it, you still have a strong reference to it, so nullify the collection, clean it or do something with it... if not you will find a memory leak difficult to find.

--> Maybe, using collections with weak references (weakhashmap...) can help with memory issues, but you must be carefull with it, for you might find that the object you look for has been collected.

--> Another idea i've found is to develope a persistent collection that stored on database objects least used and transparently loaded. This would probably be the best approach...

java.lang.Exception: No runnable methods exception in running JUnits

This solution will apply to a very small percentage of people, typically people implementing their own JUnit test runners and using a separate ClassLoader.

This can happen when you load a class from a different ClassLoader, then attempt to run that test from an instance of JUnitCore loaded from the system class loader. Example:

// Load class
URLClassLoader cl = new URLClassLoader(myTestUrls, null);
Class<?>[] testCls = cl.loadClass("com.gubby.MyTest");

// Run test
JUnitCore junit = new JUnitCore();
junit.run(testCls); // Throws java.lang.Exception: No runnable methods

Looking at the stack trace:

java.lang.Exception: No runnable methods
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:169)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:104)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:355)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)

The problem actually occurs at BlockJUnit4ClassRunner:169 (assuming JUnit 4.11):

https://github.com/junit-team/junit/blob/r4.11/src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java#L95

Where it checks which methods are annotated with @Test:

protected List<FrameworkMethod> computeTestMethods() {
    return getTestClass().getAnnotatedMethods(Test.class);
}

In this case, Test.class will have been loaded with the system ClassLoader (i.e. the one that loaded JUnitCore), therefore technically none of your test methods will have been annotated with that annotation.

Solution is to load JUnitCore in the same ClassLoader as the tests themselves.


Edit: In answer to the question from user3486675, you need to create a ClassLoader that doesn't delegate to the system class loader, e.g.:

private static final class IsolatedURLClassLoader extends URLClassLoader {
    private IsolatedURLClassLoader(URL[] urls) {
        // Prevent delegation to the system class loader.
        super(urls, null);
    }
}

Pass this a set of URLs that includes everything you need. You can create this by filtering the system classpath. Note that you cannot simply delegate to the parent ClassLoader, because those classes would then get loaded by that rather than the ClassLoader of your test classes.

Then you need to kick off the whole JUnit job from a class loaded by this ClassLoader. It gets messy here. Something like this utter filth below:

public static final class ClassLoaderIsolatedTestRunner {

    public ClassLoaderIsolatedTestRunner() {
        // Disallow construction at all from wrong ClassLoader
        ensureLoadedInIsolatedClassLoader(this);
    }

    // Do not rename.
    public void run_invokedReflectively(List<String> testClasses) throws BuildException {
        // Make sure we are not accidentally working in the system CL
        ensureLoadedInIsolatedClassLoader(this);

        // Load classes
        Class<?>[] classes = new Class<?>[testClasses.size()];
        for (int i=0; i<testClasses.size(); i++) {
            String test = testClasses.get(i);
            try {
                classes[i] = Class.forName(test);
            } catch (ClassNotFoundException e) {
                String msg = "Unable to find class file for test ["+test+"]. Make sure all " +
                        "tests sources are either included in this test target via a 'src' " +
                        "declaration.";
                throw new BuildException(msg, e);
            }
        }

        // Run
        JUnitCore junit = new JUnitCore();
        ensureLoadedInIsolatedClassLoader(junit);
        junit.addListener(...);
        junit.run(classes);
    }

    private static void ensureLoadedInIsolatedClassLoader(Object o) {
        String objectClassLoader = o.getClass().getClassLoader().getClass().getName();

        // NB: Can't do instanceof here because they are not instances of each other.
        if (!objectClassLoader.equals(IsolatedURLClassLoader.class.getName())) {
            throw new IllegalStateException(String.format(
                    "Instance of %s not loaded by a IsolatedURLClassLoader (loaded by %s)",
                    cls, objectClassLoader));
        }
    }
}

THEN, you need to invoke the runner via reflection:

Class<?> runnerClass = isolatedClassLoader.loadClass(ClassLoaderIsolatedTestRunner.class.getName());

// Invoke via reflection (List.class is OK because it just uses the string form of it)
Object runner = runnerClass.newInstance();
Method method = runner.getClass().getMethod("run_invokedReflectively", List.class);
method.invoke(...);

How can I display an image from a file in Jupyter Notebook?

If you are trying to display an Image in this way inside a loop, then you need to wrap the Image constructor in a display method.

from IPython.display import Image, display

listOfImageNames = ['/path/to/images/1.png',
                    '/path/to/images/2.png']

for imageName in listOfImageNames:
    display(Image(filename=imageName))

Getting an odd error, SQL Server query using `WITH` clause

always use with statement like ;WITH then you'll never get this error. The WITH command required a ; between it and any previous command, by always using ;WITH you'll never have to remember to do this.

see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:

When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.

executing a function in sql plus

One option would be:

SET SERVEROUTPUT ON

EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));

CSS: Set Div height to 100% - Pixels

Now with css3 you could try to use calc()

.main{
  height: calc(100% - 111px);
}

have a look at this answer: Div width 100% minus fixed amount of pixels

Add a property to a JavaScript object using a variable as the name?

If you want to add fields to an object dynamically, simplest way to do it is as follows:

 var params= [
{key: "k1", value=1},
{key: "k2", value=2},
{key: "k3", value=3}];

for(i=0; i< params.len; i++) {
  data[params[i].key] = params[i].value
}

This will create data object which has following fields:

{k1:1, k2:2, k3:3}

resize2fs: Bad magic number in super-block while trying to open

In Centos 7 default filesystem is xfs.

xfs file system support only extend not reduce. So if you want to resize the filesystem use xfs_growfs rather than resize2fs.

xfs_growfs /dev/root_vg/root 

Note: For ext4 filesystem use

resize2fs /dev/root_vg/root

SQL time difference between two dates result in hh:mm:ss

I came across this post today as I was trying to gather the time difference between fields located in separate tables joined together on a key field. This is the working code for such an endeavor. (tested in sql 2010) Bare in mind that my original query co-joined 6 tables on a common keyfield, in the code below I have removed the other tables as to not cause any confusion for the reader.

The purpose of the query is to calculate the difference between the variables CreatedUTC & BackupUTC, where difference is expressed in days and the field is called 'DaysActive.'

declare @CreatedUTC datetime
declare @BackupUtc datetime


SELECT TOP 500

table02.Column_CreatedUTC AS DeviceCreated,
CAST(DATEDIFF(day, table02.Column_CreatedUTC, table03.Column_EndDateUTC) AS nvarchar(5))+ ' Days' As DaysActive,
table03.Column_EndDateUTC AS LastCompleteBackup

FROM

Operations.table01 AS table01

LEFT OUTER JOIN

    dbo.table02 AS table02
ON
    table02.Column_KeyField = table01.Column_KeyField

LEFT OUTER JOIN 

    dbo.table03 AS table03
ON
    table01.Column_KeyField = table03.Column_KeyField

Where table03.Column_EndDateUTC > dateadd(hour, -24, getutcdate()) --Gathers records with an end date in the last 24 hours
AND table02.[Column_CreatedUTC] = COALESCE(@CreatedUTC, table02.[Column_CreatedUTC])
AND table03.[Column_EndDateUTC] = COALESCE(@BackupUTC, table03.[Column_EndDateUTC])

GROUP BY table03.Column_EndDateUTC, table02.Column_CreatedUTC
ORDER BY table02.Column_CreatedUTC ASC, DaysActive, table03.Column_EndDateUTC DESC

The Output will be as follows:

[DeviceCreated]..[DaysActive]..[LastCompleteBackup]
---------------------------------------------------------
[2/13/12 16:04]..[463 Days]....[5/21/13 12:14]
[2/12/13 22:37]..[97 Days].....[5/20/13 22:10]

Excel 2010 VBA Referencing Specific Cells in other worksheets

Private Sub Click_Click()

 Dim vaFiles As Variant
 Dim i As Long

For j = 1 To 2
vaFiles = Application.GetOpenFilename _
     (FileFilter:="Excel Filer (*.xlsx),*.xlsx", _
     Title:="Open File(s)", MultiSelect:=True)

If Not IsArray(vaFiles) Then Exit Sub

 With Application
  .ScreenUpdating = False
  For i = 1 To UBound(vaFiles)
     Workbooks.Open vaFiles(i)
     wrkbk_name = vaFiles(i)
    Next i
  .ScreenUpdating = True
End With

If j = 1 Then
work1 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
Else: work2 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
End If



Next j

'Filling the values of the group name

'check = Application.WorksheetFunction.Search(Name, work1)
check = InStr(UCase("Qoute Request"), work1)

If check = 1 Then
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
End If

ActiveWorkbook.Sheets("GI Quote Request").Select
ActiveSheet.Range("B4:C12").Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Range("K3").Select
ActiveSheet.Paste


Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select

Range("D3").Value = Range("L3").Value
Range("D7").Value = Range("L9").Value
Range("D11").Value = Range("L7").Value

For i = 4 To 5

If i = 5 Then
GoTo NextIteration
End If

If Left(ActiveSheet.Range("B" & i).Value, Len(ActiveSheet.Range("B" & i).Value) - 1) = Range("K" & i).Value Then
    ActiveSheet.Range("D" & i).Value = Range("L" & i).Value
 End If

NextIteration:
Next i

'eligibles part
Count = Range("D11").Value
For i = 27 To Count + 24
Range("C" & i).EntireRow.Offset(1, 0).Insert
Next i

check = Left(work1, InStrRev(work1, ".") - 1)

'check = InStr("Census", work1)
If check = "Census" Then
workbk = work1
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
workbk = work2
End If

'DOB
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("D2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
ActiveSheet.Range("C27").Select
ActiveSheet.Paste

'Gender
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("C2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False

ActiveSheet.Range("k27").Select
ActiveSheet.Paste

For i = 27 To Count + 27
ActiveSheet.Range("E" & i).Value = Left(ActiveSheet.Range("k" & i).Value, 1)
Next i

'Salary
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("N2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False

ActiveSheet.Range("F27").Select
ActiveSheet.Paste


ActiveSheet.Range("K3:L" & Count).Select
selction.ClearContents
End Sub

What should be the values of GOPATH and GOROOT?

GOPATH is discussed in the cmd/go documentation:

The GOPATH environment variable lists places to look for Go code. On Unix, the value is a colon-separated string. On Windows, the value is a semicolon-separated string. On Plan 9, the value is a list.

GOPATH must be set to get, build and install packages outside the standard Go tree.

GOROOT is discussed in the installation instructions:

The Go binary distributions assume they will be installed in /usr/local/go (or c:\Go under Windows), but it is possible to install the Go tools to a different location. In this case you must set the GOROOT environment variable to point to the directory in which it was installed.

For example, if you installed Go to your home directory you should add the following commands to $HOME/.profile:

export GOROOT=$HOME/go
export PATH=$PATH:$GOROOT/bin

Note: GOROOT must be set only when installing to a custom location.

(updated version of Chris Bunch's answer.)

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

Determine if char is a num or letter

chars are just integers, so you can actually do a straight comparison of your character against literals:

if( c >= '0' && c <= '9' ){

This applies to all characters. See your ascii table.

ctype.h also provides functions to do this for you.

Use virtualenv with Python with Visual Studio Code in Ubuntu

With the latest update to the extension all you need to do is just specify the "python.pythonPath" as follows.

The values for "python.autoComplete.extraPaths" will be determined during runtime, but you are still free to specify custom paths in there.

Please, remember to restart Visual Studio Code once the necessary changes have been made.

{
    "editor.rulers": [80,100],
    "python.pythonPath":"~/dev/venvs/proj/bin/python"
}

How can I redirect a php page to another php page?

<?php  
header('Location: http://www.google.com'); //Send browser to http://www.google.com
?>  

How to disable anchor "jump" when loading a page?

I used dave1010's solution, but it was a bit jumpy when I put it inside the $().ready function. So I did this: (not inside the $().ready)

    if (location.hash) {               // do the test straight away
        window.scrollTo(0, 0);         // execute it straight away
        setTimeout(function() {
            window.scrollTo(0, 0);     // run it a bit later also for browser compatibility
        }, 1);
    }

How to set JAVA_HOME path on Ubuntu?

I normally set paths in

~/.bashrc

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

export JAVA_HOME=......jdk1.7

#export JAVA_HOME=......jdk1.8

notice 1.8 is commented. Once you do

source ~/.bashrc

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

What is the difference between Hibernate and Spring Data JPA

I disagree SpringJPA makes live easy. Yes, it provides some classes and you can make some simple DAO fast, but in fact, it's all you can do. If you want to do something more than findById() or save, you must go through hell:

  • no EntityManager access in org.springframework.data.repository classes (this is basic JPA class!)
  • own transaction management (hibernate transactions disallowed)
  • huge problems with more than one datasources configuration
  • no datasource pooling (HikariCP must be in use as third party library)

Why own transaction management is an disadvantage? Since Java 1.8 allows default methods into interfaces, Spring annotation based transactions, simple doesn't work.

Unfortunately, SpringJPA is based on reflections, and sometimes you need to point a method name or entity package into annotations (!). That's why any refactoring makes big crash. Sadly, @Transactional works for primary DS only :( So, if you have more than one DataSources, remember - transactions works just for primary one :)

What are the main differences between Hibernate and Spring Data JPA?

Hibernate is JPA compatibile, SpringJPA Spring compatibile. Your HibernateJPA DAO can be used with JavaEE or Hibernate Standalone, when SpringJPA can be used within Spring - SpringBoot for example

When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Data JPA?

Use Spring JDBC only when you need to use much Joins or when you need to use Spring having multiple datasource connections. Generally, avoid JPA for Joins.

But my general advice, use fresh solution—Daobab (http://www.daobab.io). Daobab is my Java and any JPA engine integrator, and I believe it will help much in your tasks :)

Best implementation for Key Value Pair Data Structure?

Use something like this:

class Tree < T > : Dictionary < T, IList< Tree < T > > >  
{  
}  

It's ugly, but I think it will give you what you want. Too bad KeyValuePair is sealed.

Removing App ID from Developer Connection

  • As of Apr 2013, it is possible to delete App IDs.
  • As of Sep 2013, it is impossible to delete App IDs again after the big outage. I hope Apple will put it back.
  • As of mid 2014, it is possible to delete App IDs again. However, you can't delete id of apps existing in the App Store.

Is there a list of screen resolutions for all Android based phones and tablets?

Here is a list of almost all resolutions of tablets :

2560*1600
1366*768
1280*800
1280*768
1024*768
1024*600
960*640
960*540
854*480
800*600
800*480
800*400

Of this, the most common resolutions are :

1280*800
1280*768
1024*600
1024*800
1024*768
800*400
800*480

Happy designing .. ! :)

Can I write into the console in a unit test? If yes, why doesn't the console window open?

You could use this line to write to Output Window of the Visual Studio:

System.Diagnostics.Debug.WriteLine("Matrix has you...");

Must run in Debug mode.

Gradle proxy configuration

Create a file called gradle.properties inside the project folder where the build.gradle file is present. Add the following entry

     systemProp.http.proxyHost=proxy_url
     systemProp.http.proxyPort=proxy_port
     systemProp.http.proxyUser=USER
     systemProp.http.proxyPassword=PWD
     systemProp.https.proxyHost=proxy_url 
     systemProp.https.proxyPort=proxy_port
     systemProp.https.proxyUser=USER
     systemProp.https.proxyPassword=PWD

If you are using DNS for proxy then add it like systemProp.https.proxyHost=www.proxysite.com

For IP just specify the IP with out http:// or https://
Check gradle official doc for more details and setting up proxy at global level

Custom UITableViewCell from nib in Swift

swift 4.1.2

xib.

Create ImageCell2.swift

Step 1

import UIKit

class ImageCell2: UITableViewCell {

    @IBOutlet weak var imgBookLogo: UIImageView!
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var lblPublisher: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

step 2 . According Viewcontroller class

  import UIKit

    class ImageListVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tblMainVC: UITableView!

    var arrBook : [BookItem] = [BookItem]()

    override func viewDidLoad() {
        super.viewDidLoad()
         //Regester Cell
        self.tblMainVC.register(UINib.init(nibName: "ImageCell2", bundle: nil), forCellReuseIdentifier: "ImageCell2")
        // Response Call adn Disply Record
        APIManagerData._APIManagerInstance.getAPIBook { (itemInstance) in
            self.arrBook = itemInstance.arrItem!
            self.tblMainVC.reloadData()
        }
    }
    //MARK: DataSource & delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrBook.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//    [enter image description here][2]
        let cell  = tableView.dequeueReusableCell(withIdentifier: "ImageCell2") as! ImageCell2
        cell.lblTitle.text = self.arrBook[indexPath.row].title
        cell.lblPublisher.text = self.arrBook[indexPath.row].publisher
        if let authors = self.arrBook[indexPath.row].author {
            for item in authors{
                print(" item \(item)")
            }
        }
        let  url  = self.arrBook[indexPath.row].imageURL
        if url == nil {
            cell.imgBookLogo.kf.setImage(with: URL.init(string: ""), placeholder: UIImage.init(named: "download.jpeg"))
        }
        else{
            cell.imgBookLogo.kf.setImage(with: URL(string: url!)!, placeholder: UIImage.init(named: "download.jpeg"))
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    } 

}

replace String with another in java

The replace method is what you're looking for.

For example:

String replacedString = someString.replace("HelloBrother", "Brother");

How do I implement charts in Bootstrap?

Update 2018

Here's a simple example using Bootstrap 4 with ChartJs. Use an HTML5 Canvas element for the chart...

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-body">
                    <canvas id="chLine"></canvas>
                </div>
            </div>
        </div>
     </div>     
</div>

And then the appropriate JS to populate the chart...

var colors = ['#007bff','#28a745'];
var chLine = document.getElementById("chLine");
var chartData = {
  labels: ["S", "M", "T", "W", "T", "F", "S"],
  datasets: [{
    data: [589, 445, 483, 503, 689, 692, 634],
    borderColor: colors[0],
    borderWidth: 4,
    pointBackgroundColor: colors[0]
  },
  {
    data: [639, 465, 493, 478, 589, 632, 674],
    borderColor: colors[1],
    borderWidth: 4,
    pointBackgroundColor: colors[1]
  }]
};
if (chLine) {
  new Chart(chLine, {
  type: 'line',
  data: chartData,
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    },
    legend: {
      display: false
    }
  }
  });
}

Bootstrap 4 Charts Demo

How to change sa password in SQL Server 2008 express?

This is what worked for me:

  • Close all Sql Server referencing apps.
  • Open Services in Control Panel.
  • Find the "SQL Server (SQLEXPRESS)" entry and select properties.
  • Stop the service (all Sql Server services).
  • Enter "-m" at the Start parameters" fields.
  • Start the service (click on Start button on General Tab).
  • Open a Command Prompt (right click, Run as administrator if needed).
  • Enter the command:

    osql -S localhost\SQLEXPRESS -E

    (or change localhost to whatever your PC is called).

  • At the prompt type the following commands:

    CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'

    go

    sp_addsrvrolemember 'my_Login_here', 'sysadmin'

    go

    quit

  • Stop the "SQL Server (SQLEXPRESS)" service.

  • Remove the "-m" from the Start parameters field (if still there).

  • Start the service.

  • In Management Studio, use the login and password you just created. This should give it admin permission.

How do I detect a page refresh using jquery?

if you want to bookkeep some variable before page refresh

$(window).on('beforeunload', function(){
    // your logic here
});

if you want o load some content base on some condition

$(window).on('load', function(){
    // your logic here`enter code here`
});

WCF, Service attribute value in the ServiceHost directive could not be found

The problem could also be a in a different namespace in svc file as it is in svc.cs file.

In svc file namespace must be in the following format.

Service="Namespace.SvcClassName"

Java List.add() UnsupportedOperationException

You must initialize your List seeAlso :

List<String> seeAlso = new Vector<String>();

or

List<String> seeAlso = new ArrayList<String>();

How to do a GitHub pull request

In order to make a pull request you need to do the following steps:

  1. Fork a repository (to which you want to make a pull request). Just click the fork button the the repository page and you will have a separate github repository preceded with your github username.
  2. Clone the repository to your local machine. The Github software that you installed on your local machine can do this for you. Click the clone button beside the repository name.
  3. Make local changes/commits to the files
  4. sync the changes
  5. go to your github forked repository and click the "Compare & Review" green button besides the branch button. (The button has icon - no text)
  6. A new page will open showing your changes and then click the pull request link, that will send the request to the original owner of the repository you forked.

It took me a while to figure this, hope this will help someone.

Casting LinkedHashMap to Complex Object

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

Looping each row in datagridview

Best aproach for me was:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

What are the different types of keys in RDBMS?

From here and here: (after i googled your title)

  • Alternate key - An alternate key is any candidate key which is not selected to be the primary key
  • Candidate key - A candidate key is a field or combination of fields that can act as a primary key field for that table to uniquely identify each record in that table.
  • Compound key - compound key (also called a composite key or concatenated key) is a key that consists of 2 or more attributes.
  • Primary key - a primary key is a value that can be used to identify a unique row in a table. Attributes are associated with it. Examples of primary keys are Social Security numbers (associated to a specific person) or ISBNs (associated to a specific book). In the relational model of data, a primary key is a candidate key chosen as the main method of uniquely identifying a tuple in a relation.
  • Superkey - A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a superkey can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.
  • Foreign key - a foreign key (FK) is a field or group of fields in a database record that points to a key field or group of fields forming a key of another database record in some (usually different) table. Usually a foreign key in one table refers to the primary key (PK) of another table. This way references can be made to link information together and it is an essential part of database normalization

How to change the locale in chrome browser

[on hold: broken in Chrome 72; reported to work in Chrome 71]

The "Quick Language Switcher" extension may help too: https://chrome.google.com/webstore/detail/quick-language-switcher/pmjbhfmaphnpbehdanbjphdcniaelfie

The Quick Language Switcher extension allows the user to supersede the locale the browser is currently using in favor of the value chosen through the extension.

How to trigger click on page load?

$("document").ready({
    $("ul.galleria li:first-child img").click(function(){alert('i work click triggered'});
}); 

$("document").ready(function() { 
    $("ul.galleria li:first-child img").trigger('click'); 
}); 

just make sure the click handler is added prior to the trigger event in the call stack sequence.

  $("document").ready(function() { 
        $("ul.galleria li:first-child img").trigger('click'); 
    }); 

   $("document").ready({
        $("ul.galleria li:first-child img").click(function(){alert('i fail click triggered'});
    }); 

How to change column order in a table using sql query in sql server 2005?

You can change this using SQL query. Here is sql query to change the sequence of column.

ALTER TABLE table name 
CHANGE COLUMN `column1` `column1` INT(11) NOT NULL COMMENT '' AFTER `column2`;

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @seconds AS int = 896434;
SELECT
    CONVERT(varchar, (@seconds / 86400))                --Days
    + ':' +
    CONVERT(varchar, DATEADD(ss, @seconds, 0), 108);    --Hours, Minutes, Seconds

Outputs:

10:09:00:34

Scatter plot with error bars

To summarize Laryx Decidua's answer:

define and use a function like the following

plot.with.errorbars <- function(x, y, err, ylim=NULL, ...) {
  if (is.null(ylim))
    ylim <- c(min(y-err), max(y+err))
  plot(x, y, ylim=ylim, pch=19, ...)
  arrows(x, y-err, x, y+err, length=0.05, angle=90, code=3)
}

where one can override the automatic ylim, and also pass extra parameters such as main, xlab, ylab.

Executing Shell Scripts from the OS X Dock?

I know this is old but in case it is helpful to others:

If you need to run a script and want the terminal to pop up so you can see the results you can do like Abyss Knight said and change the extension to .command. If you double click on it it will open a terminal window and run.

I however needed this to run from automator or appleScript. So to get this to open a new terminal the command I ran from "run shell script" was "open myShellScript.command" and it opened in a new terminal.

Git stash pop- needs merge, unable to refresh index

Its much simpler than the accepted answer. You need to:

  1. Check git status and unmerged paths under it. Fix the conflicts. You can skip this step if you'd rather do it later.

  2. Add all these files under unmerged paths to index using git add <filename>.

  3. Now do git stash pop. If you get any conflicts these will again need to be resolved.

C#: Looping through lines of multiline string

from MSDN for StringReader

    string textReaderText = "TextReader is the abstract base " +
        "class of StreamReader and StringReader, which read " +
        "characters from streams and strings, respectively.\n\n" +

        "Create an instance of TextReader to open a text file " +
        "for reading a specified range of characters, or to " +
        "create a reader based on an existing stream.\n\n" +

        "You can also use an instance of TextReader to read " +
        "text from a custom backing store using the same " +
        "APIs you would use for a string or a stream.\n\n";

    Console.WriteLine("Original text:\n\n{0}", textReaderText);

    // From textReaderText, create a continuous paragraph 
    // with two spaces between each sentence.
    string aLine, aParagraph = null;
    StringReader strReader = new StringReader(textReaderText);
    while(true)
    {
        aLine = strReader.ReadLine();
        if(aLine != null)
        {
            aParagraph = aParagraph + aLine + " ";
        }
        else
        {
            aParagraph = aParagraph + "\n";
            break;
        }
    }
    Console.WriteLine("Modified text:\n\n{0}", aParagraph);

How do I get sed to read from standard input?

To make sed catch from stdin , instead of from a file, you should use -e.

Like this:

curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk  'BEGIN{FS=":"} {print $4}'

How to set a header for a HTTP GET request, and trigger file download?

I'm adding another option. The answers above were very useful for me, but I wanted to use jQuery instead of ic-ajax (it seems to have a dependency with Ember when I tried to install through bower). Keep in mind that this solution only works on modern browsers.

In order to implement this on jQuery I used jQuery BinaryTransport. This is a nice plugin to read AJAX responses in binary format.

Then you can do this to download the file and send the headers:

$.ajax({
    url: url,
    type: 'GET',
    dataType: 'binary',
    headers: headers,
    processData: false,
    success: function(blob) {
        var windowUrl = window.URL || window.webkitURL;
        var url = windowUrl.createObjectURL(blob);
        anchor.prop('href', url);
        anchor.prop('download', fileName);
        anchor.get(0).click();
        windowUrl.revokeObjectURL(url);
    }
});

The vars in the above script mean:

  • url: the URL of the file
  • headers: a Javascript object with the headers to send
  • fileName: the filename the user will see when downloading the file
  • anchor: it is a DOM element that is needed to simulate the download that must be wrapped with jQuery in this case. For example $('a.download-link').

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

How to make a div 100% height of the browser window

Add min-height: 100% and don't specify a height (or put it on auto). It totally did the job for me:

.container{     
    margin: auto;
    background-color: #909090;
    width: 60%;
    padding: none;
    min-height: 100%;
}

How do I download a binary file over HTTP?

The simplest way is the platform-specific solution:

 #!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`

Probably you are searching for:

require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

Edit: Changed. Thank You.

Edit2: The solution which saves part of a file while downloading:

# instead of http.get
f = open('sample.flv')
begin
    http.request_get('/sample.flv') do |resp|
        resp.read_body do |segment|
            f.write(segment)
        end
    end
ensure
    f.close()
end

How to get difference between two rows for a column field?

Does SQL Server support analytic functions?

select   rowint,
         value,
         value - lag(value) over (order by rowint) diff
from     myTable
order by rowint
/

Save the console.log in Chrome to a file

I have found a great and easy way for this.

  1. In the console - right click on the console logged object

  2. Click on 'Store as global variable'

  3. See the name of the new variable - e.g. it is variableName1

  4. Type in the console: JSON.stringify(variableName1)

  5. Copy the variable string content: e.g. {"a":1,"b":2,"c":3}

enter image description here

  1. Go to some JSON online editor: e.g. https://jsoneditoronline.org/

enter image description here

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Check your computer's Date and Time. If it is wrong, update it to the current time or set it automatically to get the time from the Internet.

Because certificates are tied to a fixed time period, if your clock is wrong, you are likely to get errors like this. In that scenario, by fixing the time, the problem will be fixed.

Oracle 11g SQL to get unique values in one column of a multi-column query

This will be more efficient, plus you have control over the ordering it uses to pick a value:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language
               ORDER BY person)
      ,language
FROM   tableA;

If you really don't care which person is picked for each language, you can omit the ORDER BY clause:

SELECT DISTINCT
       FIRST_VALUE(person)
          OVER(PARTITION BY language)
      ,language
FROM   tableA;

Getting data posted in between two dates

$query = $this->db
              ->get_where('orders',array('order_date <='=>$first_date,'order_date >='=>$second_date))
              ->result_array();

I have filtered my Excel data and now I want to number the rows. How do I do that?

Try this:

On first row set value 1 (e.g cell A1)

on next row set: =A1+1

Finally autocomplete the remaining rows

DataGridView changing cell background color

int rowscount = dataGridView1.Rows.Count;         

for (int i = 0; i < rowscount; i++)
{            
    if (!(dataGridView1.Rows[i].Cells[8].Value == null))
    {
        dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow;
    }
}

In Gradle, is there a better way to get Environment Variables?

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

jQuery: load txt file and insert into div

 <script type="text/javascript">     
   $("#textFileID").html("Loading...").load("URL TEXT");
 </script>  

 <div id="textFileID"></div>

How to send password securely over HTTP?

You can use SRP to use secure passwords over an insecure channel. The advantage is that even if an attacker sniffs the traffic, or compromises the server, they can't use the passwords on a different server. https://github.com/alax/jsrp is a javascript library that supports secure passwords over HTTP in the browser, or server side (via node).

SSH SCP Local file to Remote in Terminal Mac Os X

Watch that your file name doesn't have : in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt and then scp no-colons.txt server: then don't forget to mv back on the server. Just in case this was an issue.

How to install an APK file on an Android phone?

If you dont have SDK or you are setting up 3rd party app here is another way:

  1. Copy the .APK file to your device.
  2. Use file manager to locate the file.
  3. Then click on it.
  4. Android App installer should be one of the options in pop-up.
  5. Select it and it installs.

How to read a file in reverse order?

Read the file line by line and then add it on a list in reverse order.

Here is an example of code :

reverse = []
with open("file.txt", "r") as file:
    for line in file:
        line = line.strip()
         reverse[0:0] = line

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

Remove redundant paths from $PATH variable

In bash you simply can ${var/find/replace}

PATH=${PATH/%:\/home\/wrong\/dir\//}

Or in this case (as the replace bit is empty) just:

PATH=${PATH%:\/home\/wrong\/dir\/}

I came here first but went else ware as I thought there would be a parameter expansion to do this. Easier than sed!.

How to replace placeholder character or word in variable with value from another variable in Bash?

How to choose multiple files using File Upload Control?

There are other options you can use these controls which have multiple upload options and these controls have also Ajax support

1) Flajxian
2) Valums
3) Subgurim FileUpload

When to use LinkedList over ArrayList in Java?

1) Underlying Data Structure

The first difference between ArrayList and LinkedList comes with the fact that ArrayList is backed by Array while LinkedList is backed by LinkedList. This will lead to further differences in performance.

2) LinkedList implements Deque

Another difference between ArrayList and LinkedList is that apart from the List interface, LinkedList also implements Deque interface, which provides first in first out operations for add() and poll() and several other Deque functions. 3) Adding elements in ArrayList Adding element in ArrayList is O(1) operation if it doesn't trigger re-size of Array, in which case it becomes O(log(n)), On the other hand, appending an element in LinkedList is O(1) operation, as it doesn't require any navigation.

4) Removing an element from a position

In order to remove an element from a particular index e.g. by calling remove(index), ArrayList performs a copy operation which makes it close to O(n) while LinkedList needs to traverse to that point which also makes it O(n/2), as it can traverse from either direction based upon proximity.

5) Iterating over ArrayList or LinkedList

Iteration is the O(n) operation for both LinkedList and ArrayList where n is a number of an element.

6) Retrieving element from a position

The get(index) operation is O(1) in ArrayList while its O(n/2) in LinkedList, as it needs to traverse till that entry. Though, in Big O notation O(n/2) is just O(n) because we ignore constants there.

7) Memory

LinkedList uses a wrapper object, Entry, which is a static nested class for storing data and two nodes next and previous while ArrayList just stores data in Array.

So memory requirement seems less in the case of ArrayList than LinkedList except for the case where Array performs the re-size operation when it copies content from one Array to another.

If Array is large enough it may take a lot of memory at that point and trigger Garbage collection, which can slow response time.

From all the above differences between ArrayList vs LinkedList, It looks ArrayList is the better choice than LinkedList in almost all cases, except when you do a frequent add() operation than remove(), or get().

It's easier to modify a linked list than ArrayList, especially if you are adding or removing elements from start or end because linked list internally keeps references of those positions and they are accessible in O(1) time.

In other words, you don't need to traverse through the linked list to reach the position where you want to add elements, in that case, addition becomes O(n) operation. For example, inserting or deleting an element in the middle of a linked list.

In my opinion, use ArrayList over LinkedList for most of the practical purpose in Java.

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

3 steps to download the Google Play services Using Genymotion emulator

1. click the right bottom arrow in the toolbar enter image description here

2. Downloading Bar

enter image description here

3. Needs to restart

enter image description here

Uncaught TypeError: .indexOf is not a function

Convert timeofday to string to use indexOf

var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
console.log(typeof(timeofday)) // for testing will log number
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
    var pos = time.indexOf('.');
    var hrs = time.substr(1, pos - 1);
    var min = (time.substr(pos, 2)) * 60;

    if (hrs > 11) {
        hrs = (hrs - 12) + ":" + min + " PM";
    } else {
        hrs += ":" + min + " AM";
    }
    return hrs;
}
 // "" for typecasting to string
 document.getElementById("oset").innerHTML = timeD2C(""+timeofday);

Test Here

Solution 2

use toString() to convert to string

document.getElementById("oset").innerHTML = timeD2C(timeofday.toString());

jsfiddle with toString()

Disable color change of anchor tag when visited

You can't. You can only style the visited state.

For other people who find this, make sure that you have them in the right order:

a {color:#FF0000;}         /* Unvisited link  */
a:visited {color:#00FF00;} /* Visited link    */
a:hover {color:#FF00FF;}   /* Mouse over link */
a:active {color:#0000FF;}  /* Selected link   */

How to get a product's image in Magento?

You can try to replace $this-> by Mage:: in some cases. You need to convert to string.

In my case i'm using DirectResize extension (direct link), so my code is like this:

(string)Mage::helper('catalog/image')->init($_product, 'image')->directResize(150,150,3)

The ratio options (3rd param) are :

  • none proportional. The image will be resized at the Width and Height values.
  • proportional, based on the Width value 2
  • proportional, based on the Height value 3
  • proportional for the new image can fit in the Width and the Height values. 4
  • proportional. The new image will cover an area with the Width and the Height values.

Update: other info and versions here


The common way, without plugin would be:

(string)Mage::helper('catalog/image')->init($_product, 'image')->resize(150)

You can replace 'image' with 'small_image' or 'thumbnail'.

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

angular 4: *ngIf with multiple conditions

<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">

Bootstrap 3.0: How to have text and input on same line?

all please check the updated code as we have to use

 form-control-static not only form-control

http://jsfiddle.net/tusharD/58LCQ/34/

thanks with regards

How do I convert NSInteger to NSString datatype?

The answer is given but think that for some situation this will be also interesting way to get string from NSInteger

NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];

Image resizing in React Native

In my case I could not set 'width' and 'height' to null because I'm using TypeScript.

The way I fixed it was by setting them to '100%':

backgroundImage: {
    flex: 1,
    width: '100%',
    height: '100%',
    resizeMode: 'cover',        
}

What is the "continue" keyword and how does it work in Java?

If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:

for(int i=0; i < 10; ++i) {
  if (i % 2 == 0) {
    continue;
  }
  System.out.println(i);
}

This will print out only the odd numbers.

.NET Core vs Mono

You have chosen not only a realistic path, but arguably one of the best ecosystems strongly backed(also X-platforms) by MS. Still you should consider following points:

  • Update: Main doc about .Net platform standard is here: https://github.com/dotnet/corefx/blob/master/Documentation/architecture/net-platform-standard.md
  • Update: Current Mono 4.4.1 cannot run latest Asp.Net core 1.0 RTM
  • Although mono is more feature complete, its future is unclear, because MS owns it for some months now and its a duplicate work for them to support it. But MS is definitely committed to .Net Core and betting big on it.
  • Although .Net core is released, the 3rd party ecosystem is not quite there. For example Nhibernate, Umbraco etc cannot run over .Net core yet. But they have a plan.
  • There are some features missing in .Net Core like System.Drawing, you should look for 3rd party libraries
  • You should use nginx as front server with kestrelserver for asp.net apps, because kestrelserver is not quite ready for production. For example HTTP/2 is not implemented.

I hope it helps

how to replace characters in hive?

There is no OOTB feature at this moment which allows this. One way to achieve that could be to write a custom InputFormat and/or SerDe that will do this for you. You might this JIRA useful : https://issues.apache.org/jira/browse/HIVE-3751. (not related directly to your problem though).

Where do I put my php files to have Xampp parse them?

When in a window, go to GO ---> ENTER LOCATION... And then copy paste this: /opt/lampp/htdocs

Now you are at the htdocs folder. Then you can add your files there, or in a new folder inside this one (for example "myproyects" folder and inside it your files... and then from a navigator you access it by writting: localhost/myproyects/nameofthefile.php

What I did to find it easily everytime, was right click on "myproyects" folder and "Make link..."... then I moved this link I created to the Desktop and then I didn't have to go anymore to the htdocs, but just enter the folder I created in my Desktop.

Hope it helps!!

How to read data from a zip file without having to unzip the entire file

Here is how a UTF8 text file can be read from a zip archive into a string variable (.NET Framework 4.5 and up):

string zipFileFullPath = "{{TypeYourZipFileFullPathHere}}";
string targetFileName = "{{TypeYourTargetFileNameHere}}";
string text = new string(
            (new System.IO.StreamReader(
             System.IO.Compression.ZipFile.OpenRead(zipFileFullPath)
             .Entries.Where(x => x.Name.Equals(targetFileName,
                                          StringComparison.InvariantCulture))
             .FirstOrDefault()
             .Open(), Encoding.UTF8)
             .ReadToEnd())
             .ToArray());

Better way to find control in ASP.NET

Late as usual. If anyone is still interested in this there are a number of related SO questions and answers. My version of recursive extension method for resolving this:

public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
                                                        where T : Control
{
    foreach (Control child in parent.Controls)
    {
        if (child is T)
        {
            yield return (T)child;
        }
        else if (child.Controls.Count > 0)
        {
            foreach (T grandChild in child.FindControlsOfType<T>())
            {
                yield return grandChild;
            }
        }
    }
}

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)

or

if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

Convert string to List<string> in one line?

Use the Stringify.Library nuget package

//Default delimiter is ,
var split = new StringConverter().ConvertTo<List<string>>(names);

//You can also have your custom delimiter for e.g. ;
var split = new StringConverter().ConvertTo<List<string>>(names, new ConverterOptions { Delimiter = ';' });

What is the best regular expression to check if a string is a valid URL?

https?:\/{2}(?:[\/-\w.]|(?:%[\da-fA-F]{2}))+

You can use this pattern for detecting URLs.

Following is the proof of concept

RegExr: URL Detector

How can I check if a string contains ANY letters from the alphabet?

You can use islower() on your string to see if it contains some lowercase letters (amongst other characters). or it with isupper() to also check if contains some uppercase letters:

below: letters in the string: test yields true

>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True

below: no letters in the string: test yields false.

>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>> 

Not to be mixed up with isalpha() which returns True only if all characters are letters, which isn't what you want.

Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.

Another git process seems to be running in this repository

Deleting my commit message worked for me.

rm .git/COMMIT_EDITMSG

It then said.

fatal: cannot lock ref 'HEAD': Unable to create '.git/refs/heads/[your-branch-name].lock': File exists.

Do notice that your branch name might be different than mine. You can delete this lock file by doing;

rm .git/refs/heads/[your-branch-name].lock

Hope this helps someone.

How to check queue length in Python

len(queue) should give you the result, 3 in this case.

Specifically, len(object) function will call object.__len__ method [reference link]. And the object in this case is deque, which implements __len__ method (you can see it by dir(deque)).


queue= deque([])   #is this length 0 queue?

Yes it will be 0 for empty deque.

How can I cast int to enum?

Sometimes you have an object to the MyEnum type. Like

var MyEnumType = typeof(MyEnum);

Then:

Enum.ToObject(typeof(MyEnum), 3)

Greyscale Background Css Images

Here you go:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(yourimagehere.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(yourimagehere.jpg);
    }
</style>
</head>
<body>
    <div class="nongrayscale">
        this is a non-grayscale of the bg image
    </div>
    <div class="grayscale">
        this is a grayscale of the bg image
    </div>
</body>
</html>

Tested it in FireFox, Chrome and IE. I've also attached an image to show my results of my implementation of this.Grayscale Background Image in DIV Sample

EDIT: Also, if you want the image to just toggle back and forth with jQuery, here's the page source for that...I've included the web link to jQuery and and image that's online so you should just be able to copy/paste to test it out:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>bluantinoo CSS Grayscale Bg Image Sample</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<style type="text/css">
    div {
        border: 1px solid black;
        padding: 5px;
        margin: 5px;
        width: 600px;
        height: 600px;
        float: left;
        color: white;
    }
     .grayscale {
         background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
         -moz-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -o-filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
         -webkit-filter: grayscale(100%);
         filter: gray;
         filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
     }

    .nongrayscale {
        background: url(http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg);
    }
</style>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#image").mouseover(function () {
                $(".nongrayscale").removeClass().fadeTo(400,0.8).addClass("grayscale").fadeTo(400, 1);
            });
            $("#image").mouseout(function () {
                $(".grayscale").removeClass().fadeTo(400, 0.8).addClass("nongrayscale").fadeTo(400, 1);
            });
        });
</script>
</head>
<body>
    <div id="image" class="nongrayscale">
        rollover this image to toggle grayscale
    </div>
</body>
</html>

EDIT 2 (For IE10-11 Users): The solution above will not work with the changes Microsoft has made to the browser as of late, so here's an updated solution that will allow you to grayscale (or desaturate) your images.

_x000D_
_x000D_
<svg>_x000D_
  <defs>_x000D_
    <filter xmlns="http://www.w3.org/2000/svg" id="desaturate">_x000D_
      <feColorMatrix type="saturate" values="0" />_x000D_
    </filter>_x000D_
  </defs>_x000D_
  <image xlink:href="http://www.polyrootstattoo.com/images/Artists/Buda/40.jpg" width="600" height="600" filter="url(#desaturate)" />_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Using CSS in Laravel views?

Since Laravel 5 the HTML class is not included by default anymore.

If you're using Form or HTML helpers, you will see an error stating class 'Form' not found or class 'Html' not found. The Form and HTML helpers have been deprecated in Laravel 5.0; however, there are community-driven replacements such as those maintained by the Laravel Collective.

You can make use of the following line to include your CSS or JS files:

<link href="{{ URL::asset('css/base.css') }}" rel="stylesheet">
<link href="{{ URL::asset('js/project.js') }}" rel="script">

jQuery get specific option tag text

You can get one of following ways

$("#list").find('option').filter('[value=2]').text()

$("#list").find('option[value=2]').text()

$("#list").children('option[value=2]').text()

$("#list option[value='2']").text()

_x000D_
_x000D_
$(function(){    _x000D_
    _x000D_
    console.log($("#list").find('option').filter('[value=2]').text());_x000D_
    console.log($("#list").find('option[value=2]').text());_x000D_
    console.log($("#list").children('option[value=2]').text());_x000D_
    console.log($("#list option[value='2']").text());_x000D_
    _x000D_
});
_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<select id='list'>_x000D_
    <option value='1'>Option A</option>_x000D_
    <option value='2'>Option B</option>_x000D_
    <option value='3'>Option C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

showing that a date is greater than current date

For SQL Server

select *
from YourTable
where DateCol between getdate() and dateadd(d, 90, getdate())

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

What are the differences between .gitignore and .gitkeep?

This is not an answer to the original question "What are the differences between .gitignore and .gitkeep?" but posting here to help people to keep track of empty dir in a simple fashion. To track empty directory and knowling that .gitkeep is not official part of git,

enter image description here

just add a empty (with no content) .gitignore file in it.

So for e.g. if you have /project/content/posts and sometimes posts directory might be empty then create empty file /project/content/posts/.gitignore with no content to track that directory and its future files in git.

How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

if you are getting id from url try

$id = (isset($_GET['id']) ? $_GET['id'] : '');

if getting from form you need to use POST method cause your form has method="post"

 $id = (isset($_POST['id']) ? $_POST['id'] : '');

For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

$id= '';

ALTER TABLE to add a composite primary key

It`s definitely better to use COMPOSITE UNIQUE KEY, as @GranadaCoder offered, a little bit tricky example though:

ALTER IGNORE TABLE table_name ADD UNIQUES INDEX idx_name(some_id, another_id, one_more_id);

load scripts asynchronously

Thanks to HTML5, you can now declare the scripts that you want to load asynchronously by adding "async" in the tag:

<script async>...</script>

Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).

Note: There are several ways an external script can be executed:

  • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)
  • If async is not present and defer is present: The script is executed when the page has finished parsing
  • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page

See this: http://www.w3schools.com/tags/att_script_async.asp

How do I check that a number is float or integer?

try this one
function amountcheck()
    {
        var dpamt=$('#dpamt').val()/5000;
        var ints=dpamt.toString();
        var isint=ints.split('.');
        if(isint[1]>0)
        {
            alert('float value');
            return false;
        }
        else
        {   
            alert('int value');
        }
    }

Font is not available to the JVM with Jasper Reports

If you are using maven in your project, you can just add the jasper-fonts dependency to pom.xml:

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports-fonts</artifactId>
    <version>6.8.1</version>
</dependency>

Installing the missing font on the system may be a working solution but not for me, I didn't want to have to install the missing fonts after each deployment in a new server, instead I opted for embedding the font with the application.

Regards.

Create a Date with a set timezone without using a string representation

I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.

And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.

Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.

Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int constructor for GMT times.

On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:

var months = [ '', 'January', 'February', ..., 'December'];

function createGMTDate(xiYear, xiMonth, xiDate) {
   return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

Grega's answer is great in explaining why the original code does not work and two ways to fix the issue. However, this solution is not very flexible; consider the case where your closure includes a method call on a non-Serializable class that you have no control over. You can neither add the Serializable tag to this class nor change the underlying implementation to change the method into a function.

Nilesh presents a great workaround for this, but the solution can be made both more concise and general:

def genMapper[A, B](f: A => B): A => B = {
  val locker = com.twitter.chill.MeatLocker(f)
  x => locker.get.apply(x)
}

This function-serializer can then be used to automatically wrap closures and method calls:

rdd map genMapper(someFunc)

This technique also has the benefit of not requiring the additional Shark dependencies in order to access KryoSerializationWrapper, since Twitter's Chill is already pulled in by core Spark

How to create a temporary directory and get the path / file name in Python

In Python 3, TemporaryDirectory in the tempfile module can be used.

This is straight from the examples:

import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
     print('created temporary directory', tmpdirname)
# directory and contents have been removed

If you would like to keep the directory a bit longer, you could do something like this:

import tempfile

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()

The documentation also says that "On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem." So at the end of the program, for example, Python will clean up the directory if it wasn't explicitly removed. Python's unittest may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory... if you rely on this, though.

keytool error Keystore was tampered with, or password was incorrect

Using changeit for the password is important too.

This command finally worked for me(with jetty):

 keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass changeit -validity 360 -keysize 2048

Adb install failure: INSTALL_CANCELED_BY_USER

In MIUI 8 go to Developer Settings and toggle "Install over USB" to enable it.

jQuery.inArray(), how to use it right?

jQuery inArray() method is use to search a value in an array and return its index not a Boolean value. And if the value was not found it’ll return -1.

So, to check if a value is present in an array, follow the below practice:

myArray = new Array("php", "tutor");
if( $.inArray("php", myArray) !== -1 ) {

    alert("found");
}

Reference

how to toggle attr() in jquery

$(".list-toggle").click(function() {
    $(this).attr('colspan') ? 
    $(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});

stopPropagation vs. stopImmediatePropagation

Here is a demo to illustrate the difference:

_x000D_
_x000D_
document.querySelectorAll("button")[0].addEventListener('click', e=>{
  e.stopPropagation();
  alert(1);
});
document.querySelectorAll("button")[1].addEventListener('click', e=>{
  e.stopImmediatePropagation();
  alert(1);
});
document.querySelectorAll("button")[0].addEventListener('click', e=>{
  alert(2);
});
document.querySelectorAll("button")[1].addEventListener('click', e=>{
  alert(2);
});
_x000D_
<div onclick="alert(3)">
   <button>1...2</button>
   <button>1</button>
</div>
_x000D_
_x000D_
_x000D_

Notice that you can attach multiple event handlers to an event on an element.

SyntaxError: cannot assign to operator

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)

Vertically centering Bootstrap modal window

The best solution to centralize your modal with width and height is, in css add and in modal add this 'centralize' as a class..

.centralize{
   position:absolute;
   left:50%;
   top:50%;

   background-color:#fff;
   transform: translate(-50%, -50%);
   width: 40%; //specify watever u want
   height: 50%;
   }

Powershell Get-ChildItem most recent file in directory

If you want the latest file in the directory and you are using only the LastWriteTime to determine the latest file, you can do something like below:

gci path | sort LastWriteTime | select -last 1

On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar

gci path | select -last 1

Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}

Do I need to close() both FileReader and BufferedReader?

According to BufferedReader source, in this case bReader.close call fReader.close so technically you do not have to call the latter.

What is the meaning of the word logits in TensorFlow?

They are basically the fullest learned model you can get from the network, before it's been squashed down to apply to only the number of classes we are interested in. Check out how some researchers use them to train a shallow neural net based on what a deep network has learned: https://arxiv.org/pdf/1312.6184.pdf

It's kind of like how when learning a subject in detail, you will learn a great many minor points, but then when teaching a student, you will try to compress it to the simplest case. If the student now tried to teach, it'd be quite difficult, but would be able to describe it just well enough to use the language.

How to use in jQuery :not and hasClass() to get a specific element without a class

Use the not function instead:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.

Highcharts - how to have a chart with dynamic height?

When using percentage, the height it relative to the width and will dynamically change along with it:

chart: {
    height: (9 / 16 * 100) + '%' // 16:9 ratio
},

JSFiddle Highcharts with percentage height

MySQL, create a simple function

Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR this portion to CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT

and change the following line too.

DECLARE NAME_FOUND TEXT DEFAULT "";

It should work.

Getting the last argument passed to a shell script

The following will set LAST to last argument without changing current environment:

LAST=$({
   shift $(($#-1))
   echo $1
})
echo $LAST

If other arguments are no longer needed and can be shifted it can be simplified to:

shift $(($#-1))
echo $1

For portability reasons following:

shift $(($#-1));

can be replaced with:

shift `expr $# - 1`

Replacing also $() with backquotes we get:

LAST=`{
   shift \`expr $# - 1\`
   echo $1
}`
echo $LAST

window.open with target "_blank" in Chrome

"_blank" is not guaranteed to be a new tab or window. It's implemented differently per-browser.

You can, however, put anything into target. I usually just say "_tab", and every browser I know of just opens it in a new tab.

Be aware that it means it's a named target, so if you try to open 2 URLs, they will use the same tab.

javascript filter array multiple conditions

This is an easily understandable functional solution

_x000D_
_x000D_
let filtersObject = {_x000D_
  address: "England",_x000D_
  name: "Mark"_x000D_
};_x000D_
_x000D_
let users = [{_x000D_
    name: 'John',_x000D_
    email: '[email protected]',_x000D_
    age: 25,_x000D_
    address: 'USA'_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    email: '[email protected]',_x000D_
    age: 35,_x000D_
    address: 'England'_x000D_
  },_x000D_
  {_x000D_
    name: 'Mark',_x000D_
    email: '[email protected]',_x000D_
    age: 28,_x000D_
    address: 'England'_x000D_
  }_x000D_
];_x000D_
_x000D_
function filterUsers(users, filtersObject) {_x000D_
  //Loop through all key-value pairs in filtersObject_x000D_
  Object.keys(filtersObject).forEach(function(key) {_x000D_
    //Loop through users array checking each userObject_x000D_
    users = users.filter(function(userObject) {_x000D_
      //If userObject's key:value is same as filtersObject's key:value, they stay in users array_x000D_
      return userObject[key] === filtersObject[key]_x000D_
    })_x000D_
  });_x000D_
  return users;_x000D_
}_x000D_
_x000D_
//ES6_x000D_
function filterUsersES(users, filtersObject) {_x000D_
  for (let key in filtersObject) {_x000D_
    users = users.filter((userObject) => userObject[key] === filtersObject[key]);_x000D_
  }_x000D_
  return users;_x000D_
}_x000D_
_x000D_
console.log(filterUsers(users, filtersObject));_x000D_
console.log(filterUsersES(users, filtersObject));
_x000D_
_x000D_
_x000D_

Fastest way to implode an associative array with keys

This is the most basic version I can think of:

public function implode_key($glue = "", $pieces = array())
{
    $keys = array_keys($pieces);
    return implode($glue, $keys);
}

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

How to configure and troubleshoot <p:fileUpload> depends on PrimeFaces and JSF version.

All PrimeFaces versions

The below requirements apply to all PrimeFaces versions:

  1. The enctype attribute of the <h:form> needs to be set to multipart/form-data. When this is absent, the ajax upload may just work, but the general browser behavior is unspecified and dependent on form composition and webbrowser make/version. Just always specify it to be on the safe side.

  2. When using mode="advanced" (i.e. ajax upload, this is the default), then make sure that you've a <h:head> in the (master) template. This will ensure that the necessary JavaScript files are properly included. This is not required for mode="simple" (non-ajax upload), but this would break look'n'feel and functionality of all other PrimeFaces components, so you don't want to miss that anyway.

  3. When using mode="simple" (i.e. non-ajax upload), then ajax must be disabled on any PrimeFaces command buttons/links by ajax="false", and you must use <p:fileUpload value> with <p:commandButton action> instead of <p:fileUpload listener>.

So, if you want (auto) file upload with ajax support (mind the <h:head>!):

<h:form enctype="multipart/form-data">
    <p:fileUpload listener="#{bean.upload}" auto="true" /> // For PrimeFaces version older than 8.x this should be fileUploadListener instead of listener.
</h:form>
public void upload(FileUploadEvent event) {
    UploadedFile uploadedFile = event.getFile();
    String fileName = uploadedFile.getFileName();
    String contentType = uploadedFile.getContentType();
    byte[] contents = uploadedFile.getContents(); // Or getInputStream()
    // ... Save it, now!
}

Or if you want non-ajax file upload:

<h:form enctype="multipart/form-data">
    <p:fileUpload mode="simple" value="#{bean.uploadedFile}" />
    <p:commandButton value="Upload" action="#{bean.upload}" ajax="false" />
</h:form>
private transient UploadedFile uploadedFile; // +getter+setter

public void upload() {
    String fileName = uploadedFile.getFileName();
    String contentType = uploadedFile.getContentType();
    byte[] contents = uploadedFile.getContents(); // Or getInputStream()
    // ... Save it, now!
}

Do note that ajax-related attributes such as auto, allowTypes, update, onstart, oncomplete, etc are ignored in mode="simple". So it's needless to specify them in such case.

Also note that you should read the file contents immediately inside the abovementioned methods and not in a different bean method invoked by a later HTTP request. This is because the uploaded file contents is request scoped and thus unavailable in a later/different HTTP request. Any attempt to read it in a later request will most likely end up with java.io.FileNotFoundException on the temporary file.


PrimeFaces 8.x

Configuration is identical to the 5.x version info below, but if your listener is not called, check if the method attribute is called listener and not (like with pre 8.x versions) fileUploadListener.


PrimeFaces 5.x

This does not require any additional configuration if you're using JSF 2.2 and your faces-config.xml is also declared conform JSF 2.2 version. You do not need the PrimeFaces file upload filter at all and you also do not need the primefaces.UPLOADER context parameter in web.xml. In case it's unclear to you how to properly install and configure JSF depending on the target server used, head to How to properly install and configure JSF libraries via Maven? and "Installing JSF" section of our JSF wiki page.

If you're however not using JSF 2.2 yet and you can't upgrade it (should be effortless when already on a Servlet 3.0 compatible container), then you need to manually register the below PrimeFaces file upload filter in web.xml (it will parse the multi part request and fill the regular request parameter map so that FacesServlet can continue working as usual):

<filter>
    <filter-name>primeFacesFileUploadFilter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>primeFacesFileUploadFilter</filter-name>
    <servlet-name>facesServlet</servlet-name>
</filter-mapping>

The <servlet-name> value of facesServlet must match exactly the value in the <servlet> entry of the javax.faces.webapp.FacesServlet in the same web.xml. So if it's e.g. Faces Servlet, then you need to edit it accordingly to match.


PrimeFaces 4.x

The same story as PrimeFaces 5.x applies on 4.x as well.

There's only a potential problem in getting the uploaded file content by UploadedFile#getContents(). This will return null when native API is used instead of Apache Commons FileUpload. You need to use UploadedFile#getInputStream() instead. See also How to insert uploaded image from p:fileUpload as BLOB in MySQL?

Another potential problem with native API will manifest is when the upload component is present in a form on which a different "regular" ajax request is fired which does not process the upload component. See also File upload doesn't work with AJAX in PrimeFaces 4.0/JSF 2.2.x - javax.servlet.ServletException: The request content-type is not a multipart/form-data.

Both problems can also be solved by switching to Apache Commons FileUpload. See PrimeFaces 3.x section for detail.


PrimeFaces 3.x

This version does not support JSF 2.2 / Servlet 3.0 native file upload. You need to manually install Apache Commons FileUpload and explicitly register the file upload filter in web.xml.

You need the following libraries:

Those must be present in the webapp's runtime classpath. When using Maven, make sure they are at least runtime scoped (default scope of compile is also good). When manually carrying around JARs, make sure they end up in /WEB-INF/lib folder.

The file upload filter registration detail can be found in PrimeFaces 5.x section here above. In case you're using PrimeFaces 4+ and you'd like to explicitly use Apache Commons FileUpload instead of JSF 2.2 / Servlet 3.0 native file upload, then you need next to the mentioned libraries and filter also the below context param in web.xml:

<context-param>
    <param-name>primefaces.UPLOADER</param-name>
    <param-value>commons</param-value><!-- Allowed values: auto, native and commons. -->
</context-param>

Troubleshooting

In case it still doesn't work, here are another possible causes unrelated to PrimeFaces configuration:

  1. Only if you're using the PrimeFaces file upload filter: There's another Filter in your webapp which runs before the PrimeFaces file upload filter and has already consumed the request body by e.g. calling getParameter(), getParameterMap(), getReader(), etcetera. A request body can be parsed only once. When you call one of those methods before the file upload filter does its job, then the file upload filter will get an empty request body.

    To fix this, you'd need to put the <filter-mapping> of the file upload filter before the other filter in web.xml. If the request is not a multipart/form-data request, then the file upload filter will just continue as if nothing happened. If you use filters that are automagically added because they use annotations (e.g. PrettyFaces), you might need to add explicit ordering via web.xml. See How to define servlet filter order of execution using annotations in WAR

  2. Only if you're using the PrimeFaces file upload filter: There's another Filter in your webapp which runs before the PrimeFaces file upload filter and has performed a RequestDispatcher#forward() call. Usually, URL rewrite filters such as PrettyFaces do this. This triggers the FORWARD dispatcher, but filters listen by default on REQUEST dispatcher only.

    To fix this, you'd need to either put the PrimeFaces file upload filter before the forwarding filter, or to reconfigure the PrimeFaces file upload filter to listen on FORWARD dispatcher too:

     <filter-mapping>
         <filter-name>primeFacesFileUploadFilter</filter-name>
         <servlet-name>facesServlet</servlet-name>
         <dispatcher>REQUEST</dispatcher>
         <dispatcher>FORWARD</dispatcher>
     </filter-mapping>
    
  3. There's a nested <h:form>. This is illegal in HTML and the browser behavior is unspecified. More than often, the browser won't send the expected data on submit. Make sure that you are not nesting <h:form>. This is completely regardless of the form's enctype. Just do not nest forms at all.

If you're still having problems, well, debug the HTTP traffic. Open the webbrowser's developer toolset (press F12 in Chrome/Firebug23+/IE9+) and check the Net/Network section. If the HTTP part looks fine, then debug the JSF code. Put a breakpoint on FileUploadRenderer#decode() and advance from there.


Saving uploaded file

After you finally got it to work, your next question shall probably be like "How/where do I save the uploaded file?". Well, continue here: How to save uploaded file in JSF.

Why can't I push to this bare repository?

I use SourceTree git client, and I see that their initial commit/push command is:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I had trouble for a number of days and was hacking around. This link proved out to be extremely helpful for me. It helped me to do a successful upgrade of the SSL on MAC OS X 9.

Http Post request with content type application/x-www-form-urlencoded not working in Spring

You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"})

It would be helpful if you posted your code.

CSS disable hover effect

I tried the following and it works for me better

Code:

.unstyled-link{ 
  color: inherit;
  text-decoration: inherit;
  &:link,
  &:hover {
    color: inherit;
    text-decoration: inherit;
  }
}

Select N random elements from a List<T> in C#

I combined several of the above answers to create a Lazily-evaluated extension method. My testing showed that Kyle's approach (Order(N)) is many times slower than drzaus' use of a set to propose the random indices to choose (Order(K)). The former performs many more calls to the random number generator, plus iterates more times over the items.

The goals of my implementation were:

1) Do not realize the full list if given an IEnumerable that is not an IList. If I am given a sequence of a zillion items, I do not want to run out of memory. Use Kyle's approach for an on-line solution.

2) If I can tell that it is an IList, use drzaus' approach, with a twist. If K is more than half of N, I risk thrashing as I choose many random indices again and again and have to skip them. Thus I compose a list of the indices to NOT keep.

3) I guarantee that the items will be returned in the same order that they were encountered. Kyle's algorithm required no alteration. drzaus' algorithm required that I not emit items in the order that the random indices are chosen. I gather all the indices into a SortedSet, then emit items in sorted index order.

4) If K is large compared to N and I invert the sense of the set, then I enumerate all items and test if the index is not in the set. This means that I lose the Order(K) run time, but since K is close to N in these cases, I do not lose much.

Here is the code:

    /// <summary>
    /// Takes k elements from the next n elements at random, preserving their order.
    /// 
    /// If there are fewer than n elements in items, this may return fewer than k elements.
    /// </summary>
    /// <typeparam name="TElem">Type of element in the items collection.</typeparam>
    /// <param name="items">Items to be randomly selected.</param>
    /// <param name="k">Number of items to pick.</param>
    /// <param name="n">Total number of items to choose from.
    /// If the items collection contains more than this number, the extra members will be skipped.
    /// If the items collection contains fewer than this number, it is possible that fewer than k items will be returned.</param>
    /// <returns>Enumerable over the retained items.
    /// 
    /// See http://stackoverflow.com/questions/48087/select-a-random-n-elements-from-listt-in-c-sharp for the commentary.
    /// </returns>
    public static IEnumerable<TElem> TakeRandom<TElem>(this IEnumerable<TElem> items, int k, int n)
    {
        var r = new FastRandom();
        var itemsList = items as IList<TElem>;

        if (k >= n || (itemsList != null && k >= itemsList.Count))
            foreach (var item in items) yield return item;
        else
        {  
            // If we have a list, we can infer more information and choose a better algorithm.
            // When using an IList, this is about 7 times faster (on one benchmark)!
            if (itemsList != null && k < n/2)
            {
                // Since we have a List, we can use an algorithm suitable for Lists.
                // If there are fewer than n elements, reduce n.
                n = Math.Min(n, itemsList.Count);

                // This algorithm picks K index-values randomly and directly chooses those items to be selected.
                // If k is more than half of n, then we will spend a fair amount of time thrashing, picking
                // indices that we have already picked and having to try again.   
                var invertSet = k >= n/2;  
                var positions = invertSet ? (ISet<int>) new HashSet<int>() : (ISet<int>) new SortedSet<int>();

                var numbersNeeded = invertSet ? n - k : k;
                while (numbersNeeded > 0)
                    if (positions.Add(r.Next(0, n))) numbersNeeded--;

                if (invertSet)
                {
                    // positions contains all the indices of elements to Skip.
                    for (var itemIndex = 0; itemIndex < n; itemIndex++)
                    {
                        if (!positions.Contains(itemIndex))
                            yield return itemsList[itemIndex];
                    }
                }
                else
                {
                    // positions contains all the indices of elements to Take.
                    foreach (var itemIndex in positions)
                        yield return itemsList[itemIndex];              
                }
            }
            else
            {
                // Since we do not have a list, we will use an online algorithm.
                // This permits is to skip the rest as soon as we have enough items.
                var found = 0;
                var scanned = 0;
                foreach (var item in items)
                {
                    var rand = r.Next(0,n-scanned);
                    if (rand < k - found)
                    {
                        yield return item;
                        found++;
                    }
                    scanned++;
                    if (found >= k || scanned >= n)
                        break;
                }
            }
        }  
    } 

I use a specialized random number generator, but you can just use C#'s Random if you want. (FastRandom was written by Colin Green and is part of SharpNEAT. It has a period of 2^128-1 which is better than many RNGs.)

Here are the unit tests:

[TestClass]
public class TakeRandomTests
{
    /// <summary>
    /// Ensure that when randomly choosing items from an array, all items are chosen with roughly equal probability.
    /// </summary>
    [TestMethod]
    public void TakeRandom_Array_Uniformity()
    {
        const int numTrials = 2000000;
        const int expectedCount = numTrials/20;
        var timesChosen = new int[100];
        var century = new int[100];
        for (var i = 0; i < century.Length; i++)
            century[i] = i;

        for (var trial = 0; trial < numTrials; trial++)
        {
            foreach (var i in century.TakeRandom(5, 100))
                timesChosen[i]++;
        }
        var avg = timesChosen.Average();
        var max = timesChosen.Max();
        var min = timesChosen.Min();
        var allowedDifference = expectedCount/100;
        AssertBetween(avg, expectedCount - 2, expectedCount + 2, "Average");
        //AssertBetween(min, expectedCount - allowedDifference, expectedCount, "Min");
        //AssertBetween(max, expectedCount, expectedCount + allowedDifference, "Max");

        var countInRange = timesChosen.Count(i => i >= expectedCount - allowedDifference && i <= expectedCount + allowedDifference);
        Assert.IsTrue(countInRange >= 90, String.Format("Not enough were in range: {0}", countInRange));
    }

    /// <summary>
    /// Ensure that when randomly choosing items from an IEnumerable that is not an IList, 
    /// all items are chosen with roughly equal probability.
    /// </summary>
    [TestMethod]
    public void TakeRandom_IEnumerable_Uniformity()
    {
        const int numTrials = 2000000;
        const int expectedCount = numTrials / 20;
        var timesChosen = new int[100];

        for (var trial = 0; trial < numTrials; trial++)
        {
            foreach (var i in Range(0,100).TakeRandom(5, 100))
                timesChosen[i]++;
        }
        var avg = timesChosen.Average();
        var max = timesChosen.Max();
        var min = timesChosen.Min();
        var allowedDifference = expectedCount / 100;
        var countInRange =
            timesChosen.Count(i => i >= expectedCount - allowedDifference && i <= expectedCount + allowedDifference);
        Assert.IsTrue(countInRange >= 90, String.Format("Not enough were in range: {0}", countInRange));
    }

    private IEnumerable<int> Range(int low, int count)
    {
        for (var i = low; i < low + count; i++)
            yield return i;
    }

    private static void AssertBetween(int x, int low, int high, String message)
    {
        Assert.IsTrue(x > low, String.Format("Value {0} is less than lower limit of {1}. {2}", x, low, message));
        Assert.IsTrue(x < high, String.Format("Value {0} is more than upper limit of {1}. {2}", x, high, message));
    }

    private static void AssertBetween(double x, double low, double high, String message)
    {
        Assert.IsTrue(x > low, String.Format("Value {0} is less than lower limit of {1}. {2}", x, low, message));
        Assert.IsTrue(x < high, String.Format("Value {0} is more than upper limit of {1}. {2}", x, high, message));
    }
}

What's the best way to build a string of delimited items in Java?

You can use Java's StringBuilder type for this. There's also StringBuffer, but it contains extra thread safety logic that is often unnecessary.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

This error was caused, for me, by different circumstances. A downloaded project tutorial had a default setting of [Project]>Targets>Build Settings>Architectures>Build Active Architecture Only>Release = "Yes." I wasn't intending to build a release, so the solution was to set Release (which presumably requires not just a developer profile but distribution profile) to "No."

Where does Console.WriteLine go in ASP.NET?

Unless you are in a strict console application, I wouldn't use it, because you can't really see it. I would use Trace.WriteLine() for debugging-type information that can be turned on and off in production.

How do I parse JSON into an int?

It depends on the property type that you are parsing.

If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:

(long) jsonObj.get("id") // with id = 5, cast `5` to long 

After getting the long,you could cast again to int, resulting in:

(int) (long) jsonObj.get("id")

If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();

Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long

The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.

If not using Java Generics, the best way to deal with these runtime exceptions that I use is:

if(jsonObj.get("id") == null) {
   // do something here
}

int id;
try{
    id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
  // handle here
}

You could also remove that first if and add the exception to the catch. Hope this helps.

How can I control the width of a label tag?

You can either give class name to all label so that all can have same width :

 .class-name {  width:200px;}

Example

.labelname{  width:200px;}

or you can simple give rest of label

label {  width:200px;  display: inline-block;}

The identity used to sign the executable is no longer valid

I selected None from Team dropdown in target general settings. Then selected the original team. Xcode shows some spinner next to it. Wait for it to complete and then everything works. Tried it in Xcode 6.2

Removing whitespace between HTML elements when using line breaks

After way too much research, trial and error I found a way that seems to works fine and doesn't require to manually re-set the font size manually on the children elements, allowing me to have a standardized em font size across the whole doc.

In Firefox this is fairly simple, just set word-spacing: -1em on the parent element. For some reason, Chrome ignore this (and as far as I tested, it ignores the word spacing regardless of the value). So besides this I add letter-spacing: -.31em to the parent and letter-spacing: normal to the children. This fraction of an em is the size of the space ONLY IF your em size is standardized. Firefox, in turn, ignores negative values for letter-spacing, so it won't add it to the word spacing.

I tested this on Firefox 13 (win/ubuntu, 14 on android), Google Chrome 20 (win/ubuntu), Android Browser on ICS 4.0.4 and IE 9. And I'm tempted to say this may also work on Safari, but I don't really know...

Here's a demo http://jsbin.com/acucam

How can I convert a string to boolean in JavaScript?

The Boolean object doesn't have a 'parse' method. Boolean('false') returns true, so that won't work. !!'false' also returns true, so that won't work also.

If you want string 'true' to return boolean true and string 'false' to return boolean false, then the simplest solution is to use eval(). eval('true') returns true and eval('false') returns false. Keep in mind the performance implications when using eval() though.

bower proxy configuration

Inside your local project open the .bowerrc that contains:

{
   "directory": "bower_components"
 }

and add the following code-line:

{
   "directory": "bower_components",
  "proxy": "http://yourProxy:yourPort",
  "https-proxy":"http://yourProxy:yourPort"
}

bower version: 1.7.1

Cheers

Can I escape html special chars in javascript?

DOM Elements support converting text to HTML by assigning to innerText. innerText is not a function but assigning to it works as if the text were escaped.

document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';

Initialize/reset struct to zero/null

You can use memset with the size of the struct:

struct x x_instance;
memset (&x_instance, 0, sizeof(x_instance));

php form action php self

If you want to be secure use this:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Measuring elapsed time with the Time module

In programming, there are 2 main ways to measure time, with different results:

>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001  # took  0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075       # took 10 seconds and a bit
  • Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

    • Use time.process_time()
  • Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

    • Use time.perf_counter()

      • time.time() also measures wall-clock time but can be reset, so you could go back in time
      • time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()

Dynamically creating keys in a JavaScript associative array

All modern browsers support a Map, which is a key/value data structure. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

Fastest way to determine if an integer's square root is an integer

Regarding the Carmac method, it seems like it would be quite easy just to iterate once more, which should double the number of digits of accuracy. It is, after all, an extremely truncated iterative method -- Newton's, with a very good first guess.

Regarding your current best, I see two micro-optimizations:

  • move the check vs. 0 after the check using mod255
  • rearrange the dividing out powers of four to skip all the checks for the usual (75%) case.

I.e:

// Divide out powers of 4 using binary search

if((n & 0x3L) == 0) {
  n >>=2;

  if((n & 0xffffffffL) == 0)
    n >>= 32;
  if((n & 0xffffL) == 0)
      n >>= 16;
  if((n & 0xffL) == 0)
      n >>= 8;
  if((n & 0xfL) == 0)
      n >>= 4;
  if((n & 0x3L) == 0)
      n >>= 2;
}

Even better might be a simple

while ((n & 0x03L) == 0) n >>= 2;

Obviously, it would be interesting to know how many numbers get culled at each checkpoint -- I rather doubt the checks are truly independent, which makes things tricky.

string decode utf-8

A string needs no encoding. It is simply a sequence of Unicode characters.

You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.

Encoding of a String is carried out by:

String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into

You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).

Decoding:

String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded 

If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"

HTML img align="middle" doesn't align an image

Try this:

style="margin: auto"

CURL to pass SSL certifcate and password

Addition to previous answer make sure that your curl installation supports https.
You can use curl --version to get information about supported protocols.

If your curl supports https follow the previous answer.

curl --cert certificate_path:password https://www.example.com

If it does not support https, you need to install a cURL version that supports https.