Programs & Examples On #Spoof

Disable / Check for Mock Location (prevent gps spoofing)

It seems that the only way to do this is to prevent Location Spoofing preventing MockLocations. The down side is there are some users who use Bluetooth GPS devices to get a better signal, they won't be able to use the app as they are required to use the mock locations.

To do this, I did the following :

// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(getContentResolver(),
       Settings.Secure.ALLOW_MOCK_LOCATION).equals("0")) 
       return false; 
       else return true;

Auto margins don't center image in page

add display:block; and it'll work. Images are inline by default

To clarify, the default width for a block element is auto, which of course fills the entire available width of the containing element.

By setting the margin to auto, the browser assigns half the remaining space to margin-left and the other half to margin-right.

Android 6.0 multiple permissions

Checking every situation

if denied - showing Alert dialog to user why we need permission

public static final int MULTIPLE_PERMISSIONS = 1;
public static final int CAMERA_PERMISSION_REQUEST_CODE = 2;
public static final int STORAGE_PERMISSION_REQUEST_CODE = 3;

    private void askPermissions() {

    int permissionCheckStorage = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE);

    int permissionCheckCamera = ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA); 

   // we already asked for permisson & Permission granted, call camera intent
    if (permissionCheckStorage == PackageManager.PERMISSION_GRANTED && permissionCheckCamera == PackageManager.PERMISSION_GRANTED) {

        launchCamera();

    } //asking permission for the first time
     else if (permissionCheckStorage != PackageManager.PERMISSION_GRANTED && permissionCheckCamera != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MULTIPLE_PERMISSIONS);

    } else {
        // Permission denied, so request permission

        // if camera request is denied
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("You need to give permission to take pictures in order to work this feature.");
            builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.setPositiveButton("GIVE PERMISSION", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();

                    // Show permission request popup
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            CAMERA_PERMISSION_REQUEST_CODE);
                }
            });
            builder.show();

        }   // if storage request is denied
                else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("You need to give permission to access storage in order to work this feature.");
            builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });
            builder.setPositiveButton("GIVE PERMISSION", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();

                    // Show permission request popup
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            STORAGE_PERMISSION_REQUEST_CODE);
                }
            });
            builder.show();

        } 

    }
}

Checking Permission Results

 @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case CAMERA_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.CAMERA)) {
                // check whether camera permission granted or not.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    launchCamera();
                }
            }
            break;
        case STORAGE_PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // check whether storage permission granted or not.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    launchCamera();
                }
            }
            break;
        case MULTIPLE_PERMISSIONS:
            if (grantResults.length > 0 && permissions[0].equals(Manifest.permission.CAMERA) && permissions[1].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // check whether All permission granted or not.
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    launchCamera();

                }
            }
            break;
        default:
            break;
    }
}

you can just copy and paste this code, it works fine. change context(this) & permissions according to you.

passing object by reference in C++

A reference is really a pointer with enough sugar to make it taste nice... ;)

But it also uses a different syntax to pointers, which makes it a bit easier to use references than pointers. Because of this, we don't need & when calling the function that takes the pointer - the compiler deals with that for you. And you don't need * to get the content of a reference.

To call a reference an alias is a pretty accurate description - it is "another name for the same thing". So when a is passed as a reference, we're really passing a, not a copy of a - it is done (internally) by passing the address of a, but you don't need to worry about how that works [unless you are writing your own compiler, but then there are lots of other fun things you need to know when writing your own compiler, that you don't need to worry about when you are just programming].

Note that references work the same way for int or a class type.

Difference between two dates in Python

Another short solution:

from datetime import date

def diff_dates(date1, date2):
    return abs(date2-date1).days

def main():
    d1 = date(2013,1,1)
    d2 = date(2013,9,13)
    result1 = diff_dates(d2, d1)
    print '{} days between {} and {}'.format(result1, d1, d2)
    print ("Happy programmer's day!")

main()

How to select records from last 24 hours using SQL?

In Oracle (For last 24 hours):

SELECT  *
FROM    my_table
WHERE   date_column >= SYSDATE - 24/24

In case, for any reason, you have rows with future dates, you can use between, like this:

SELECT  *
FROM    my_table
WHERE   date_column BETWEEN (SYSDATE - 24/24) AND SYSDATE

Error 1022 - Can't write; duplicate key in table

I just spent the last 4 hours with the same issue. What I did was to simply make sure the constraints had unique names.

You can rename the constraints. I appended a number to mine so I could easily trace the number of occurrences.

Example

If a constraint in a table is named boy with a foreign key X The next constraint with the foreign key X can be called boy1

I'm sure you'd figure out better names than I did.

How to download dependencies in gradle

There is no task to download dependencies; they are downloaded on demand. To learn how to manage dependencies with Gradle, see "Chapter 8. Dependency Management Basics" in the Gradle User Guide.

Efficient way to do batch INSERTS with JDBC

You can use this rewriteBatchedStatements parameter to make the batch insert even faster.

you can read here about the param: MySQL and JDBC with rewriteBatchedStatements=true

Swift - How to convert String to Double

For a little more Swift feeling, using NSFormatter() avoids casting to NSString, and returns nil when the string does not contain a Double value (e.g. "test" will not return 0.0).

let double = NSNumberFormatter().numberFromString(myString)?.doubleValue

Alternatively, extending Swift's String type:

extension String {
    func toDouble() -> Double? {
        return NumberFormatter().number(from: self)?.doubleValue
    }
}

and use it like toInt():

var myString = "4.2"
var myDouble = myString.toDouble()

This returns an optional Double? which has to be unwrapped.

Either with forced unwrapping:

println("The value is \(myDouble!)") // prints: The value is 4.2

or with an if let statement:

if let myDouble = myDouble {
    println("The value is \(myDouble)") // prints: The value is 4.2
}

Update: For localization, it is very easy to apply locales to the NSFormatter as follows:

let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "fr_FR")
let double = formatter.numberFromString("100,25")

Finally, you can use NSNumberFormatterCurrencyStyle on the formatter if you are working with currencies where the string contains the currency symbol.

How do you post data with a link

You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>

Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:

isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']

And in the streeview.php make links like that:

<a href="house.php?houseVar=$houseNum"></a>

Or something else. I just don't know your files and what inside it.

Difference between signed / unsigned char

The same way how an int can be positive or negative. There is no difference. Actually on many platforms unqualified char is signed.

FAIL - Application at context path /Hello could not be started

Your web.xml ends with <web-app>, but must end with </web-app>

Which by the way is almost literally what the exception tells you.

How can I set focus on an element in an HTML form using JavaScript?

For plain Javascript, try the following:

window.onload = function() {
  document.getElementById("TextBoxName").focus();
};

Find the files that have been changed in last 24 hours

On GNU-compatible systems (i.e. Linux):

find . -mtime 0 -printf '%T+\t%s\t%p\n' 2>/dev/null | sort -r | more

This will list files and directories that have been modified in the last 24 hours (-mtime 0). It will list them with the last modified time in a format that is both sortable and human-readable (%T+), followed by the file size (%s), followed by the full filename (%p), each separated by tabs (\t).

2>/dev/null throws away any stderr output, so that error messages don't muddy the waters; sort -r sorts the results by most recently modified first; and | more lists one page of results at a time.

When & why to use delegates?

I agree with everything that is said already, just trying to put some other words on it.

A delegate can be seen as a placeholder for a/some method(s).

By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called".

Typical use is of course events. All the OnEventX delegate to the methods the user defines.

Delegates are useful to offer to the user of your objects some ability to customize their behavior. Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.

how to git commit a whole folder?

You don't "commit the folder" - you add the folder, as you have done, and then simply commit all changes. The command should be:

git add foldername
git commit -m "commit operation"

How to write a simple Html.DropDownListFor()?

With "Please select one Item"

@Html.DropDownListFor(model => model.ContentManagement_Send_Section,
  new List<SelectListItem> { new SelectListItem { Value = "0", Text = "Plese Select one Item" } }
    .Concat(db.NameOfPaperSections.Select(x => new SelectListItem { Text = x.NameOfPaperSection, Value = x.PaperSectionID.ToString() })),
  new { @class = "myselect" })  

Derived from the codes: Master Programmer && Joel Wahlund ;
King Reference : https://stackoverflow.com/a/1528193/1395101 JaredPar ;

Thanks Master Programmer && Joel Wahlund && JaredPar ;

Good luck friends.

How to loop through files matching wildcard in batch file

Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.

According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:

for %%f in (*.in) do call process.cmd %%~nf

Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:

echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt

There might be a better way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.

EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...

Eclipse: Frustration with Java 1.7 (unbound library)

Updated eclipse.ini file with key-value property

-Dosgi.requiredJavaVersion=1.5 

to

-Dosgi.requiredJavaVersion=1.8

because, that is my JAVA version.

Also, selected JRE 1.8 as my project library

Git log to get commits only for a specific branch

Here I present an alias based on Richard Hansen's answer (and Ben C's suggestion), but that I adapted to exclude tags. The alias should be fairly robust.

# For Git 1.22+
git config --global alias.only '!b=${1:-$(git branch --show-current)}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'
# For older Git:
git config --global alias.only '!b=${1:-$(git symbolic-ref -q --short HEAD)}; b=${b##heads/}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'

Example of use:

git only mybranch  # Show commits that are in mybranch ONLY
git only           # Show commits that are ONLY in current branch

Note that ONLY means commits that would be LOST (after garbage collection) if the given branch was deleted (excluding the effect of tags). The alias should work even if there is unfortunately a tag named mybranch (thanks to prefix heads/). Note also that no commits are shown if they are part of any remote branch (including upstream if any), in compliance with the definition of ONLY.

The alias shows the one-line history as a graph of the selected commits.

  a --- b --- c --- master
   \           \
    \           d
     \           \
      e --- f --- g --- mybranch (HEAD)
       \
        h --- origin/other

With example above, git only would show:

  * (mybranch,HEAD)
  * g
  |\
  | * d
  * f 

In order to include tags (but still excluding HEAD), the alias becomes (adapt as above for older Git):

git config --global alias.only '!b=${1:-$(git branch --show-current)};  git log --oneline --graph --all --not --exclude="refs/heads/$b" --exclude=HEAD --all #'

Or the variant that includes all the tags including HEAD (and removing current branch as default since it won't output anything):

git config --global alias.only '!git log --oneline --graph --all --not --exclude=\"refs/heads/$1\" --all #'

This last version is the only one that really satisfies the criteria commits-that-are-lost-if-given-branch-is-deleted, since a branch cannot be deleted if it is checked out, and no commit pointed by HEAD or any other tag will be lost. However the first two variants are more useful.

Finally, the alias does not work with remote branches (eg. git only origin/master). The alias must be modified, for instance:

git config --global alias.remote-only '!git log --oneline --graph "$1" --not --exclude="$1" --remotes --branches #'

Firebase FCM notifications click_action payload

Now it is possible to set click_action in Firebase Console. You just go to notifications-send message-advanced option and there you will have two fields for key and value. In first field you put click_action and in second you put some text which represents value of that action. And you add intent-filter in your Manifest and give him the same value as you wrote in console. And that is simulation of real click_action.

Entityframework Join using join method and lambdas

If you have configured navigation property 1-n I would recommend you to use:

var query = db.Categories                                  // source
   .SelectMany(c=>c.CategoryMaps,                          // join
      (c, cm) => new { Category = c, CategoryMaps = cm })  // project result
   .Select(x => x.Category);                               // select result

Much more clearer to me and looks better with multiple nested joins.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

What are database normal forms and can you give examples?

1NF is the most basic of normal forms - each cell in a table must contain only one piece of information, and there can be no duplicate rows.

2NF and 3NF are all about being dependent on the primary key. Recall that a primary key can be made up of multiple columns. As Chris said in his response:

The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF] (so help me Codd).

2NF

Say you have a table containing courses that are taken in a certain semester, and you have the following data:

|-----Primary Key----|               uh oh |
                                           V
CourseID | SemesterID | #Places  | Course Name  |
------------------------------------------------|
IT101    |   2009-1   | 100      | Programming  |
IT101    |   2009-2   | 100      | Programming  |
IT102    |   2009-1   | 200      | Databases    |
IT102    |   2010-1   | 150      | Databases    |
IT103    |   2009-2   | 120      | Web Design   |

This is not in 2NF, because the fourth column does not rely upon the entire key - but only a part of it. The course name is dependent on the Course's ID, but has nothing to do with which semester it's taken in. Thus, as you can see, we have duplicate information - several rows telling us that IT101 is programming, and IT102 is Databases. So we fix that by moving the course name into another table, where CourseID is the ENTIRE key.

Primary Key |

CourseID    |  Course Name |
---------------------------|
IT101       | Programming  |
IT102       | Databases    |
IT103       | Web Design   |

No redundancy!

3NF

Okay, so let's say we also add the name of the teacher of the course, and some details about them, into the RDBMS:

|-----Primary Key----|                           uh oh |
                                                       V
Course  |  Semester  |  #Places   |  TeacherID  | TeacherName  |
---------------------------------------------------------------|
IT101   |   2009-1   |  100       |  332        |  Mr Jones    |
IT101   |   2009-2   |  100       |  332        |  Mr Jones    |
IT102   |   2009-1   |  200       |  495        |  Mr Bentley  |
IT102   |   2010-1   |  150       |  332        |  Mr Jones    |
IT103   |   2009-2   |  120       |  242        |  Mrs Smith   |

Now hopefully it should be obvious that TeacherName is dependent on TeacherID - so this is not in 3NF. To fix this, we do much the same as we did in 2NF - take the TeacherName field out of this table, and put it in its own, which has TeacherID as the key.

 Primary Key |

 TeacherID   | TeacherName  |
 ---------------------------|
 332         |  Mr Jones    |
 495         |  Mr Bentley  |
 242         |  Mrs Smith   |

No redundancy!!

One important thing to remember is that if something is not in 1NF, it is not in 2NF or 3NF either. So each additional Normal Form requires everything that the lower normal forms had, plus some extra conditions, which must all be fulfilled.

Writing to an Excel spreadsheet

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

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

Your program would look something like this:

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

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

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

wb.save('example.xlsx')

Creating random numbers with no duplicates

The simplest way would be to create a list of the possible numbers (1..20 or whatever) and then shuffle them with Collections.shuffle. Then just take however many elements you want. This is great if your range is equal to the number of elements you need in the end (e.g. for shuffling a deck of cards).

That doesn't work so well if you want (say) 10 random elements in the range 1..10,000 - you'd end up doing a lot of work unnecessarily. At that point, it's probably better to keep a set of values you've generated so far, and just keep generating numbers in a loop until the next one isn't already present:

if (max < numbersNeeded)
{
    throw new IllegalArgumentException("Can't ask for more numbers than are available");
}
Random rng = new Random(); // Ideally just create one instance globally
// Note: use LinkedHashSet to maintain insertion order
Set<Integer> generated = new LinkedHashSet<Integer>();
while (generated.size() < numbersNeeded)
{
    Integer next = rng.nextInt(max) + 1;
    // As we're adding to a set, this will automatically do a containment check
    generated.add(next);
}

Be careful with the set choice though - I've very deliberately used LinkedHashSet as it maintains insertion order, which we care about here.

Yet another option is to always make progress, by reducing the range each time and compensating for existing values. So for example, suppose you wanted 3 values in the range 0..9. On the first iteration you'd generate any number in the range 0..9 - let's say you generate a 4.

On the second iteration you'd then generate a number in the range 0..8. If the generated number is less than 4, you'd keep it as is... otherwise you add one to it. That gets you a result range of 0..9 without 4. Suppose we get 7 that way.

On the third iteration you'd generate a number in the range 0..7. If the generated number is less than 4, you'd keep it as is. If it's 4 or 5, you'd add one. If it's 6 or 7, you'd add two. That way the result range is 0..9 without 4 or 6.

The VMware Authorization Service is not running

I've also had this problem recently.

The solution that worked for me was to uninstall vmware, restart windows, and the reinstall vmware.

Swift - Split string over multiple lines

Swift:

@connor is the right answer, but if you want to add lines in a print statement what you are looking for is \n and/or \r, these are called Escape Sequences or Escaped Characters, this is a link to Apple documentation on the topic..

Example:

print("First line\nSecond Line\rThirdLine...")

how to get param in method post spring mvc?

You should use @RequestParam on those resources with method = RequestMethod.GET

In order to post parameters, you must send them as the request body. A body like JSON or another data representation would depending on your implementation (I mean, consume and produce MediaType).

Typically, multipart/form-data is used to upload files.

SQL Server insert if not exists best practice

Ok, this was asked 7 years ago, but I think the best solution here is to forego the new table entirely and just do this as a custom view. That way you're not duplicating data, there's no worry about unique data, and it doesn't touch the actual database structure. Something like this:

CREATE VIEW vw_competitions
  AS
  SELECT
   Id int
   CompetitionName nvarchar(75)
   CompetitionType nvarchar(50)
   OtherField1 int
   OtherField2 nvarchar(64)  --add the fields you want viewed from the Competition table
  FROM Competitions
GO

Other items can be added here like joins on other tables, WHERE clauses, etc. This is most likely the most elegant solution to this problem, as you now can just query the view:

SELECT *
FROM vw_competitions

...and add any WHERE, IN, or EXISTS clauses to the view query.

Adjusting the Xcode iPhone simulator scale and size

However iOS Simulator->HardWare->Device menu.

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

How to open a new window on form submit

I generally use a small jQuery snippet globally to open any external links in a new tab / window. I've added the selector for a form for my own site and it works fine so far:

// URL target
    $('a[href*="//"]:not([href*="'+ location.hostname +'"]),form[action*="//"]:not([href*="'+ location.hostname +'"]').attr('target','_blank');

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Regular Expression to match only alphabetic characters

In Ruby and other languages that support POSIX character classes in bracket expressions, you can do simply:

/\A[[:alpha:]]+\z/i

That will match alpha-chars in all Unicode alphabet languages. Easy peasy.

More info: http://en.wikipedia.org/wiki/Regular_expression#Character_classes http://ruby-doc.org/core-2.0/Regexp.html

REST API Token-based Authentication

A pure RESTful API should use the underlying protocol standard features:

  1. For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.

  2. RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.

Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.

I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.

Select Rows with id having even number

You are not using Oracle, so you should be using the modulus operator:

SELECT * FROM Orders where OrderID % 2 = 0;

The MOD() function exists in Oracle, which is the source of your confusion.

Have a look at this SO question which discusses your problem.

Connecting an input stream to an outputstream

How about just using

void feedInputToOutput(InputStream in, OutputStream out) {
   IOUtils.copy(in, out);
}

and be done with it?

from jakarta apache commons i/o library which is used by a huge amount of projects already so you probably already have the jar in your classpath already.

Rethrowing exceptions in Java without losing the stack trace

something like this

try 
{
  ...
}
catch (FooException e) 
{
  throw e;
}
catch (Exception e)
{
  ...
}

clearInterval() not working

i think you should do:

var myInterval
on.onclick = function() {
    myInterval=setInterval(fontChange, 500);
};

off.onclick = function() {
    clearInterval(myInterval);
}; 

Launch Pycharm from command line (terminal)

The included utility that installs to /usr/local/bin/charm did not work for me on OS X, so I hacked together this utility instead. It actually works!

#!/usr/bin/env bash

if [ -z "$1" ]
then
  echo ""
  echo "Usage: charm <filename>"
  exit
fi
FILENAME=$1

function myreadlink() {
  (
  cd $(dirname $1)         # or  cd ${1%/*}
  echo $PWD/$(basename $1) # or  echo $PWD/${1##*/}
  )
}

FULL_FILE=`myreadlink $FILENAME`;

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm $FULL_FILE

Using a .php file to generate a MySQL dump

<?php
    $toDay = date('d-m-Y');

    $dbhost =   "localhost";
    $dbuser =   "YOUR DB USER";
    $dbpass =   "USER PASSWORD";
    $dbname =   "DB NAME";

    exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");


?>

Tensorflow import error: No module named 'tensorflow'

for python 3.8 version go for anaconda navigator then go for environments --> then go for base(root)----> not installed from drop box--->then search for tensorflow then install it then run the program.......hope it may helpful

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

Git reset has 5 main modes: soft, mixed, merged, hard, keep. The difference between them is to change or not change head, stage (index), working directory.

Git reset --hard will change head, index and working directory.
Git reset --soft will change head only. No change to index, working directory.

So in other words if you want to undo your commit, --soft should be good enough. But after that you still have the changes from bad commit in your index and working directory. You can modify the files, fix them, add them to index and commit again.

With the --hard, you completely get a clean slate in your project. As if there hasn't been any change from the last commit. If you are sure this is what you want then move forward. But once you do this, you'll lose your last commit completely. (Note: there are still ways to recover the lost commit).

Local Storage vs Cookies

With localStorage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request. Large amounts of data can be stored locally, without affecting website performance. Although localStorage is more modern, there are some pros and cons to both techniques.

Cookies

Pros

  • Legacy support (it's been around forever)
  • Persistent data
  • Expiration dates

Cons

  • Each domain stores all its cookies in a single string, which can make parsing data difficult
  • Data is unencrypted, which becomes an issue because... ... though small in size, cookies are sent with every HTTP request Limited size (4KB)
  • SQL injection can be performed from a cookie

Local storage

Pros

  • Support by most modern browsers
  • Persistent data that is stored directly in the browser
  • Same-origin rules apply to local storage data
  • Is not sent with every HTTP request
  • ~5MB storage per domain (that's 5120KB)

Cons

  • Not supported by anything before: IE 8, Firefox 3.5, Safari 4, Chrome 4, Opera 10.5, iOS 2.0, Android 2.0
  • If the server needs stored client information you purposely have to send it.

localStorage usage is almost identical with the session one. They have pretty much exact methods, so switching from session to localStorage is really child's play. However, if stored data is really crucial for your application, you will probably use cookies as a backup in case localStorage is not available. If you want to check browser support for localStorage, all you have to do is run this simple script:

/* 
* function body that test if storage is available
* returns true if localStorage is available and false if it's not
*/
function lsTest(){
    var test = 'test';
    try {
        localStorage.setItem(test, test);
        localStorage.removeItem(test);
        return true;
    } catch(e) {
        return false;
    }
}

/* 
* execute Test and run our custom script 
*/
if(lsTest()) {
    // window.sessionStorage.setItem(name, 1); // session and storage methods are very similar
    window.localStorage.setItem(name, 1);
    console.log('localStorage where used'); // log
} else {
    document.cookie="name=1; expires=Mon, 28 Mar 2016 12:00:00 UTC";
    console.log('Cookie where used'); // log
}

"localStorage values on Secure (SSL) pages are isolated" as someone noticed keep in mind that localStorage will not be available if you switch from 'http' to 'https' secured protocol, where the cookie will still be accesible. This is kind of important to be aware of if you work with secure protocols.

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

Magento How to debug blank white screen

My solution: Activating the plugin via System -> Config > Advanced > Advanced

How to get the nth element of a python list or a default if not available

Using Python 3.4's contextlib.suppress(exceptions) to build a getitem() method similar to getattr().

import contextlib

def getitem(iterable, index, default=None):
    """Return iterable[index] or default if IndexError is raised."""
    with contextlib.suppress(IndexError):
        return iterable[index]
    return default

psql - save results of command to a file

Approach for docker

via psql command

 docker exec -i %containerid% psql -U %user% -c '\dt' > tables.txt

or query from sql file

docker exec -i %containerid% psql -U %user% < file.sql > data.txt

How does a PreparedStatement avoid or prevent SQL injection?

In Prepared Statements the user is forced to enter data as parameters . If user enters some vulnerable statements like DROP TABLE or SELECT * FROM USERS then data won't be affected as these would be considered as parameters of the SQL statement

What is href="#" and why is it used?

Putting the "#" symbol as the href for something means that it points not to a different URL, but rather to another id or name tag on the same page. For example:

<a href="#bottomOfPage">Click to go to the bottom of the page</a>
blah blah
blah blah
...
<a id="bottomOfPage"></a>

However, if there is no id or name then it goes "no where."

Here's another similar question asked HTML Anchors with 'name' or 'id'?

Can I remove the URL from my print css, so the web address doesn't print?

It depends on your web browser. If you're using Firefox you can adjust or turn off those header and footer lines (URL, page number, etc) by going into File > Page Setup then clicking the Margins & Header/Footer tab.

How to Set Focus on Input Field using JQuery

Try this, to set the focus to the first input field:

$(this).parent().siblings('div.bottom').find("input.post").focus();

CSS horizontal centering of a fixed div?

Edit September 2016: Although it's nice to still get an occasional up-vote for this, because the world has moved on, I'd now go with the answer that uses transform (and which has a ton of upvotes). I wouldn't do it this way any more.

Another way not to have to calculate a margin or need a sub-container:

#menu {
    position: fixed;   /* Take it out of the flow of the document */
    left: 0;           /* Left edge at left for now */
    right: 0;          /* Right edge at right for now, so full width */ 
    top: 30px;         /* Move it down from top of window */
    width: 500px;      /* Give it the desired width */ 
    margin: auto;      /* Center it */
    max-width: 100%;   /* Make it fit window if under 500px */ 
    z-index: 10000;    /* Whatever needed to force to front (1 might do) */
}

parseInt with jQuery

Two issues:

  1. You're passing the jQuery wrapper of the element into parseInt, which isn't what you want, as parseInt will call toString on it and get back "[object Object]". You need to use val or text or something (depending on what the element is) to get the string you want.

  2. You're not telling parseInt what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt guesses which radix to use.

Fix if the element is a form field:

//                               vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
//                                    ^^^^-- tell parseInt to use decimal (base 10)

Fix if the element is something else and you want to use the text within it:

//                               vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
//                                     ^^^^-- tell parseInt to use decimal (base 10)

Hibernate openSession() vs getCurrentSession()

As explained in this forum post, 1 and 2 are related. If you set hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context - you don't need to close this.

If you are using Spring or EJBs to manage transactions you can configure them to open / close sessions along with the transactions.

You should never use one session per web app - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

How to create many labels and textboxes dynamically depending on the value of an integer variable?

I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.

Simple way to do it would be:

int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
    TextBox[] textBoxes = new TextBox[n];
    Label[] labels = new Label[n];

    for (int i = 0; i < n; i++)
    {
        textBoxes[i] = new TextBox();
        // Here you can modify the value of the textbox which is at textBoxes[i]

        labels[i] = new Label();
        // Here you can modify the value of the label which is at labels[i]
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(textBoxes[i]);
        this.Controls.Add(labels[i]);
    }
}

The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.

To do it using a User Control simply do this.

Okay, first of all go and create a new user control and put a text box and label in it.

Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:

public string GetTextBoxValue() 
{ 
    return this.txtSomeTextBox.Text; 
} 

public string GetLabelValue() 
{ 
    return this.lblSomeLabel.Text; 
} 

public void SetTextBoxValue(string newText) 
{ 
    this.txtSomeTextBox.Text = newText; 
} 

public void SetLabelValue(string newText) 
{ 
    this.lblSomeLabel.Text = newText; 
}

Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):

private void btnDisplay_Click(object sender, EventArgs e)
{
    MyUserControl[] controls = new MyUserControl[n];

    for (int i = 0; i < n; i++)
    {
        controls[i] = new MyUserControl();

        controls[i].setTextBoxValue("some value to display in text");
        controls[i].setLabelValue("some value to display in label");
        // Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(controls[i]);
    }
}

Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:

public TextBox myTextBox;
public Label myLabel;

In the constructor of the user control do this:

myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;

Then in your program if you want to modify the text value of either just do this.

control[i].myTextBox.Text = "some random text"; // Same applies to myLabel

Hope it helped :)

Permutation of array

Do like this...

import java.util.ArrayList;
import java.util.Arrays;

public class rohit {

    public static void main(String[] args) {
        ArrayList<Integer> a=new ArrayList<Integer>();
        ArrayList<Integer> b=new ArrayList<Integer>();
        b.add(1);
        b.add(2);
        b.add(3);
        permu(a,b);
    }

    public static void permu(ArrayList<Integer> prefix,ArrayList<Integer> value) {
        if(value.size()==0) {
            System.out.println(prefix);
        } else {
            for(int i=0;i<value.size();i++) {
                ArrayList<Integer> a=new ArrayList<Integer>();
                a.addAll(prefix);
                a.add(value.get(i));

                ArrayList<Integer> b=new ArrayList<Integer>();

                b.addAll(value.subList(0, i));
                b.addAll(value.subList(i+1, value.size()));

                permu(a,b);
            }
        }
    }

}

Object of class mysqli_result could not be converted to string in

The query() function returns an object, you'll want fetch a record from what's returned from that function. Look at the examples on this page to learn how to print data from mysql

Running Groovy script from the command line

You need to run the script like this:

groovy helloworld.groovy

Android Relative Layout Align Center

Use this in your RelativeLayout

android:gravity="center_vertical"

Angular redirect to login page

Here's an updated example using Angular 4 (also compatible with Angular 5 - 8)

Routes with home route protected by AuthGuard

import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { AuthGuard } from './_guards/index';

const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },

    // home route protected by auth guard
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(appRoutes);

AuthGuard redirects to login page if user isn't logged in

Updated to pass original url in query params to login page

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

For the full example and working demo you can check out this post

How to create a cron job using Bash automatically without the interactive editor?

script function to add cronjobs. check duplicate entries,useable expressions * > "

cronjob_creator () {         
# usage: cronjob_creator '<interval>' '<command>'

  if [[ -z $1 ]] ;then
    printf " no interval specified\n"
elif [[ -z $2 ]] ;then
    printf " no command specified\n"
else
    CRONIN="/tmp/cti_tmp"
    crontab -l | grep -vw "$1 $2" > "$CRONIN"
    echo "$1 $2" >> $CRONIN
    crontab "$CRONIN"
    rm $CRONIN
fi
}

tested :

$ ./cronjob_creator.sh '*/10 * * * *' 'echo "this is a test" > export_file'
$ crontab  -l
$ */10 * * * * echo "this is a test" > export_file

source : my brain ;)

Show popup after page load

    <script type="text/javascript">
        $(window).on('load',function(){
            setTimeout(function(){ alert(" //show popup"); }, 5000); 
        });
    </script>

Adding n hours to a date in Java?

To simplify @Christopher's example.

Say you have a constant

public static final long HOUR = 3600*1000; // in milli-seconds.

You can write.

Date newDate = new Date(oldDate.getTime() + 2 * HOUR);

If you use long to store date/time instead of the Date object you can do

long newDate = oldDate + 2 * HOUR;

HashMap - getting First Key value

You can also try below:

Map.Entry<String, Integer> entry = myMap.firstEntry();
System.out.println("First Value = " + entry);

How to check if IEnumerable is null or empty?

The way I do it, taking advantage of some modern C# features:

Option 1)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any() ?? false);
    }
}

Option 2)

public static class Utils {
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> list) {
        return !(list?.Any()).GetValueOrDefault();
    }
}

And by the way, never use Count == 0 or Count() == 0 just to check if a collection is empty. Always use Linq's .Any()

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

Its given the error because of security. for this please use "https" not "http" in the website url.

For example :

   "https://code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css"
   "https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"

Linux: where are environment variables stored?

It's stored in the process (shell) and since you've exported it, any processes that process spawns.

Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.

Android Studio suddenly cannot resolve symbols

For me it was a "progaurd" build entry in my build.gradle. I removed the entire build section, then did a re-sync and problem solved.

Including non-Python files with setup.py

This works in 2020!

As others said create "MANIFEST.in" where your setup.py is located.

Next in manifest include/exclude all the necessary things. Be careful here regarding the syntax. Ex: lets say we have template folder to be included in the source package.

in manifest file do this :

recursive-include template *

Make sure you leave space between dir-name and pattern for files/dirs like above. Dont do like this like we do in .gitignore

recursive-include template/* [this won't work]

Other option is to use include. There are bunch of options. Look up here at their docs for Manifest.in

And the final important step, include this param in your setup.py and you are good to go!

   setup(
    ...
    include_package_data=True,
    ......
)

Hope that helps! Happy Coding!

What is the best way to determine a session variable is null or empty in C#?

I also like to wrap session variables in properties. The setters here are trivial, but I like to write the get methods so they have only one exit point. To do that I usually check for null and set it to a default value before returning the value of the session variable. Something like this:

string Name
{
   get 
   {
       if(Session["Name"] == Null)
           Session["Name"] = "Default value";
       return (string)Session["Name"];
   }
   set { Session["Name"] = value; }
}

}

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

Try this. I hope it helps

$options = [
    'cache_wsdl'     => WSDL_CACHE_NONE,
    'trace'          => 1,
    'stream_context' => stream_context_create(
        [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            ]
        ]
    )
];

$client = new SoapClient($url, $options);

Parse json string using JSON.NET

I did not test the following snippet... hopefully it will point you towards the right direction:

    var jsreader = new JsonTextReader(new StringReader(stringData));
    var json = (JObject)new JsonSerializer().Deserialize(jsreader);
    var tableRows = from p in json["items"]
                 select new
                 {
                     Name = (string)p["Name"],
                     Age = (int)p["Age"],
                     Job = (string)p["Job"]
                 };

Reading Properties file in Java

You can't use this keyword like -

props.load(this.getClass().getResourceAsStream("myProps.properties"));

in a static context.

The best thing would be to get hold of application context like -

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/spring/app-context.xml");

then you can load the resource file from the classpath -

//load a properties file from class path, inside static method
        prop.load(context.getClassLoader().getResourceAsStream("config.properties"));

This will work for both static and non static context and the best part is this properties file can be in any package/folder included in the application's classpath.

Dynamically change bootstrap progress bar value when checkboxes checked

Try this maybe :

Bootply : http://www.bootply.com/106527

Js :

$('input').on('click', function(){
  var valeur = 0;
  $('input:checked').each(function(){
       if ( $(this).attr('value') > valeur )
       {
           valeur =  $(this).attr('value');
       }
  });
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    
});

HTML :

 <div class="progress progress-striped active">
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
        </div>
    </div>
<div class="row tasks">
        <div class="col-md-6">
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-29</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="10">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="20">
        </div>
      </div><!-- tasks -->

<div class="row tasks">
        <div class="col-md-6">
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-25</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="30">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="40">
        </div>
      </div><!-- tasks -->

Css

.tasks{
    background-color: #F6F8F8;
    padding: 10px;
    border-radius: 5px;
    margin-top: 10px;
}
.tasks span{
    font-weight: bold;
}
.tasks input{
    display: block;
    margin: 0 auto;
    margin-top: 10px;
}
.tasks a{
    color: #000;
    text-decoration: none;
    border:none;
}
.tasks a:hover{
    border-bottom: dashed 1px #0088cc;
}
.tasks label{
    display: block;
    text-align: center;
}

_x000D_
_x000D_
$(function(){_x000D_
$('input').on('click', function(){_x000D_
  var valeur = 0;_x000D_
  $('input:checked').each(function(){_x000D_
       if ( $(this).attr('value') > valeur )_x000D_
       {_x000D_
           valeur =  $(this).attr('value');_x000D_
       }_x000D_
  });_x000D_
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
 background-color: #F6F8F8;_x000D_
 padding: 10px;_x000D_
 border-radius: 5px;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
 font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
 display: block;_x000D_
 margin: 0 auto;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
 color: #000;_x000D_
 text-decoration: none;_x000D_
 border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
 border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
 display: block;_x000D_
 text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
 <div class="progress progress-striped active">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
        </div>_x000D_
    </div>_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-29</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="10">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="20">_x000D_
        </div>_x000D_
      </div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-25</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="30">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="40">_x000D_
        </div>_x000D_
      </div><!-- tasks -->
_x000D_
_x000D_
_x000D_

How to limit file upload type file size in PHP?

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

Look into the docs for move_uploaded_file() (it's called move not store) for more.

MVC which submit button has been pressed

// Buttons
<input name="submit" type="submit" id="submit" value="Save" />
<input name="process" type="submit" id="process" value="Process" />

// Controller
[HttpPost]
public ActionResult index(FormCollection collection)
{
    string submitType = "unknown";

    if(collection["submit"] != null)
    {
        submitType = "submit";
    }
    else if (collection["process"] != null)
    {
        submitType = "process";
    }

} // End of the index method

Disable spell-checking on HTML textfields

For Grammarly you can use:

<textarea data-gramm="false" />

Android LinearLayout Gradient Background

I don't know if this will help anybody, but my problem was I was trying to set the gradient to the "src" property of an ImageView like so:

<ImageView 
    android:id="@+id/imgToast"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:src="@drawable/toast_bg"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"/>

Not 100% sure why that didn't work, but now I changed it and put the drawable in the "background" property of the ImageView's parent, which is a RelativeLayout in my case, like so: (this worked successfully)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/custom_toast_layout_id"
    android:layout_height="match_parent"
    android:background="@drawable/toast_bg">

How does MySQL process ORDER BY and LIMIT in a query?

You could add [asc] or [desc] at the end of the order by to get the earliest or latest records

For example, this will give you the latest records first

ORDER BY stamp DESC

Append the LIMIT clause after ORDER BY

Return array in a function

Just define a type[ ] as return value, like:

        private string[] functionReturnValueArray(string one, string two)
    {

        string[] x = {one, two};


        x[0] = "a";
        x[1] = "b";

        return x;
    }

. . . function call:

string[] y;
y = functionReturnValueArray(stringOne, stringTwo)

Remove useless zero digits from decimals in PHP

For everyone coming to this site having the same problem with commata instead, change:

$num = number_format($value, 1, ',', '');

to:

$num = str_replace(',0', '', number_format($value, 1, ',', '')); // e.g. 100,0 becomes 100


If there are two zeros to be removed, then change to:

$num = str_replace(',00', '', number_format($value, 2, ',', '')); // e.g. 100,00 becomes 100

More here: PHP number: decimal point visible only if needed

How do I find all files containing specific text on Linux?

There's a new utility called The Silversearcher

sudo apt install silversearcher-ag

It works closely with Git and other VCS. So you won't get anything in a .git or another directory.

You can simply use

ag "Search query"

And it will do the task for you!

How can I strip first X characters from string using sed?

Well, there have been solutions here with sed, awk, cut and using bash syntax. I just want to throw in another POSIX conform variant:

$ echo "pid: 1234" | tail -c +6
1234

-c tells tail at which byte offset to start, counting from the end of the input data, yet if the the number starts with a + sign, it is from the beginning of the input data to the end.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

I eventually figured out there was a byte mark exception and removed it using this code:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
    if (xml.StartsWith(_byteOrderMarkUtf8))
    {
        var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;
        xml = xml.Remove(0, lastIndexOfUtf8);
    }

Is there a pretty print for PHP?

Since I found this via google searching for how to format json to make it more readable for troubleshooting.

ob_start() ;  print_r( $json ); $ob_out=ob_get_contents(); ob_end_clean(); echo "\$json".str_replace( '}', "}\n", $ob_out );

Is there an auto increment in sqlite?

Yes, this is possible. According to the SQLite FAQ:

A column declared INTEGER PRIMARY KEY will autoincrement.

How to modify JsonNode in Java?

Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):

Exception in thread "main" java.lang.ClassCastException: 
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

The solution is to get the 'parent' node, and perform a put, effectively replacing the entire node, regardless of original node type.

If you need to "modify" the node using the existing value of the node:

  1. get the value/array of the JsonNode
  2. Perform your modification on that value/array
  3. Proceed to call put on the parent.

Code, where the goal is to modify subfield, which is the child node of NodeA and Node1:

JsonNode nodeParent = someNode.get("NodeA")
                .get("Node1");

// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");

Credits:

I got this inspiration from here, thanks to wassgreen@

Are members of a C++ struct initialized to 0 by default?

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.

Catching exceptions from Guzzle

Depending on your project, disabling exceptions for guzzle might be necessary. Sometimes coding rules disallow exceptions for flow control. You can disable exceptions for Guzzle 3 like this:

$client = new \Guzzle\Http\Client($httpBase, array(
  'request.options' => array(
     'exceptions' => false,
   )
));

This does not disable curl exceptions for something like timeouts, but now you can get every status code easily:

$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();

To check, if you got a valid code, you can use something like this:

if ($statuscode > 300) {
  // Do some error handling
}

... or better handle all expected codes:

if (200 === $statuscode) {
  // Do something
}
elseif (304 === $statuscode) {
  // Nothing to do
}
elseif (404 === $statuscode) {
  // Clean up DB or something like this
}
else {
  throw new MyException("Invalid response from api...");
}

For Guzzle 5.3

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );

Thanks to @mika

For Guzzle 6

$client = new \GuzzleHttp\Client(['http_errors' => false]);

Why isn't textarea an input[type="textarea"]?

So that its value can easily contain quotes and <> characters and respect whitespace and newlines.

The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Yes I can</title>
</head>
<body>
    <textarea name="test">
        I can put < and > and & signs in 
        my textarea without any problems.
    </textarea>
</body>
</html>

How to make a JTable non-editable

table.setDefaultEditor(Object.class, null);

MySQL Workbench: How to keep the connection alive

I was getting this error 2013 and none of the above preference changes did anything to fix the problem. I restarted mysql service and the problem went away.

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Another scenario where this could happen is when you are launching an instance of eclipse (for debug etc.) from a host eclipse - in which case, altering the project's level or JRE library on the project's classpath alone doesn't help. What matters is the JRE used to launch the target eclipse environment.

JSON.Net Self referencing loop detected

The fix is to ignore loop references and not to serialize them. This behaviour is specified in JsonSerializerSettings.

Single JsonConvert with an overload:

JsonConvert.SerializeObject((from a in db.Events where a.Active select a).ToList(), Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

If you'd like to make this the default behaviour, add a Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

How to find the size of a table in SQL?

SQL Server, nicely formatted table for all tables in KB/MB:

SELECT 
    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.NAME NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    t.Name

How to use Typescript with native ES6 Promises

Using native ES6 Promises with Typescript in Visual Studio 2015 + Node.js tools 1.2

No npm install required as ES6 Promises is native.

Node.js project -> Properties -> Typescript Build tab ECMAScript version = ECMAScript6

import http = require('http');
import fs = require('fs');

function findFolderAsync(directory : string): Promise<string> {

    let p = new Promise<string>(function (resolve, reject) {

        fs.stat(directory, function (err, stats) {

            //Check if error defined and the error code is "not exists"
            if (err && err.code === "ENOENT") {
                reject("Directory does not exist");
            }
            else {
                resolve("Directory exists");
            }
        });

    });
    return p;
}

findFolderAsync("myFolder").then(

    function (msg : string) {
        console.log("Promise resolved as " + msg); 
    },
    function (msg : string) {
        console.log("Promise rejected as " + msg); 
    }
);

Eclipse Error: "Failed to connect to remote VM"

Use 0.0.0.0 for addresses to be able to connect form any remote machine i.e.:

-Xdebug -Xrunjdwp:transport=dt_socket,address=0.0.0.0:8000,server=y,suspend=y

plot with custom text for x axis points

This worked for me. Each month on X axis

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

Creating a UITableView Programmatically

You might be do that its works 100% .

- (void)viewDidLoad
{
    [super viewDidLoad];
    // init table view
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

    // must set delegate & dataSource, otherwise the the table will be empty and not responsive
    tableView.delegate = self;
    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor cyanColor];

    // add to canvas
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}

// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but 
    JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    // Just want to test, so I hardcode the data
    cell.descriptionLabel.text = @"Testing";

    return cell;
}

#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected %d row", indexPath.row);
}

@end

Trigger validation of all fields in Angular Form submit

You can try this:

_x000D_
_x000D_
// The controller_x000D_
_x000D_
$scope.submitForm = function(form){_x000D_
     //Force the field validation_x000D_
     angular.forEach(form, function(obj){_x000D_
      if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))_x000D_
      { _x000D_
       obj.$setDirty();_x000D_
      }_x000D_
     })_x000D_
        _x000D_
        if (form.$valid){_x000D_
  _x000D_
   $scope.myResource.$save(function(data){_x000D_
        //...._x000D_
   });_x000D_
  }_x000D_
}
_x000D_
<!-- FORM -->_x000D_
_x000D_
  <form name="myForm"  role="form" novalidate="novalidate">_x000D_
<!-- FORM GROUP to field 1 -->_x000D_
  <div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">_x000D_
      <label for="field1">My field 1</label>_x000D_
        <span class="nullable"> _x000D_
        <select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"_x000D_
          class="form-control input-sm" required>_x000D_
            <option value="">Select One</option>_x000D_
        </select>_x000D_
        </span>_x000D_
        <div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>_x000D_
  </div>_x000D_
    _x000D_
<!-- FORM GROUP to field 2 -->_x000D_
  <div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">_x000D_
    <label class="control-label labelsmall" for="field2">field2</label> _x000D_
      <input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number" _x000D_
      class="form-control input-sm" required>_x000D_
    <div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>_x000D_
  </div>_x000D_
_x000D_
  </form>_x000D_
_x000D_
<!-- ... -->_x000D_
<button type="submit" ng-click="submitForm(myForm)">Send</button>
_x000D_
_x000D_
_x000D_

Adding an onclick event to a div element

Its possible, we can specify onclick event in

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>????????????????????????????????
<script>
function fun1(i) {
    document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
    document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>

How do you use "git --bare init" repository?

I'm adding this answer because after arriving here (with the same question), none of the answers really describe all the required steps needed to go from nothing to a fully usable remote (bare) repo.

Note: this example uses local paths for the location of the bare repo, but other git protocols (like SSH indicated by the OP) should work just fine.

I've tried to add some notes along the way for those less familiar with git.

1. Initialise the bare repo...

> git init --bare /path/to/bare/repo.git
Initialised empty Git repository in /path/to/bare/repo.git/

This creates a folder (repo.git) and populates it with git files representing a git repo. As it stands, this repo is useless - it has no commits and more importantly, no branches. Although you can clone this repo, you cannot pull from it.

Next, we need to create a working folder. There are a couple of ways of doing this, depending upon whether you have existing files.

2a. Create a new working folder (no existing files) by cloning the empty repo

git clone /path/to/bare/repo.git /path/to/work
Cloning into '/path/to/work'...
warning: You appear to have cloned an empty repository.
done.

This command will only work if /path/to/work does not exist or is an empty folder. Take note of the warning - at this stage, you still don't have anything useful. If you cd /path/to/work and run git status, you'll get something like:

On branch master

Initial commit

nothing to commit (create/copy files and use "git add" to track)

but this is a lie. You are not really on branch master (because git branch returns nothing) and so far, there are no commits.

Next, copy/move/create some files in the working folder, add them to git and create the first commit.

> cd /path/to/work
> echo 123 > afile.txt
> git add .
> git config --local user.name adelphus
> git config --local user.email [email protected]
> git commit -m "added afile"
[master (root-commit) 614ab02] added afile
 1 file changed, 1 insertion(+)
 create mode 100644 afile.txt

The git config commands are only needed if you haven't already told git who you are. Note that if you now run git branch, you'll now see the master branch listed. Now run git status:

On branch master
Your branch is based on 'origin/master', but the upstream is gone.
  (use "git branch --unset-upstream" to fixup)

nothing to commit, working directory clean

This is also misleading - upstream has not "gone", it just hasn't been created yet and git branch --unset-upstream will not help. But that's OK, now that we have our first commit, we can push and master will be created on the bare repo.

> git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 207 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master

At this point, we have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

> git pull
Already up-to-date.
> git push origin master
Everything up-to-date

2b. Create a working folder from existing files If you already have a folder with files in it (so you cannot clone into it), you can initialise a new git repo, add a first commit and then link it to the bare repo afterwards.

> cd /path/to/work_with_stuff
> git init 
Initialised empty Git repository in /path/to/work_with_stuff
> git add .
# add git config stuff if needed
> git commit -m "added stuff"

[master (root-commit) 614ab02] added stuff
 20 files changed, 1431 insertions(+)
 create mode 100644 stuff.txt
...

At this point we have our first commit and a local master branch which we need to turn into a remote-tracked upstream branch.

> git remote add origin /path/to/bare/repo.git
> git push -u origin master
Counting objects: 31, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (31/31), done.
Writing objects: 100% (31/31), 43.23 KiB | 0 bytes/s, done.
Total 31 (delta 11), reused 0 (delta 0)
To /path/to/bare/repo.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from origin.

Note the -u flag on git push to set the (new) tracked upstream branch. Just as before, we now have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.

All this may seem obvious to some, but git confuses me at the best of times (it's error and status messages really need some rework) - hopefully, this will help others.

How do I send an HTML email?

Set content type. Look at this method.

message.setContent("<h1>Hello</h1>", "text/html");

Propagation Delay vs Transmission delay

Obviously , packet length * propagation delay = trasmission delay is wrong.

Let us assume that you have a packet which has 4 bits 1010.You have to send it from A to B.

For this scenario,Transmission delay is the time taken by the sender to place the packet on the link(Transmission medium).Because the bits(1010) has to be converted in to signals.So it takes some time.Note that here only the packet is placed.It is not moving to receiver.

Propagation delay is the time taken by a bit(Mostly MSB ,Here 1) to reach from sender(A) to receiver(B).

to call onChange event after pressing Enter key

I prefer onKeyUp since it only fires when the key is released. onKeyDown, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter key to make a network request, you don't want that to fire multiple times since it can be expensive.

// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />

handleKeyPress(e) {
if (e.key === 'Enter') {
  // do whatever
}

}

Also, stay away from keyCode since it will be deprecated some time.

Getting a timestamp for today at midnight?

_x000D_
_x000D_
function getTodaysTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const startOfDay = currentTimeStamp - (currentTimeStamp % 86400);_x000D_
  return { startOfDay, endOfDay: startOfDay + 86400 - 1 };_x000D_
}_x000D_
_x000D_
// starts from sunday_x000D_
function getThisWeeksTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const currentDay = new Date(currentTimeStamp * 1000);_x000D_
  const startOfWeek = currentTimeStamp - (currentDay.getDay() * 86400) - (currentTimeStamp % 86400);_x000D_
  return { startOfWeek, endOfWeek: startOfWeek + 7 * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
function getThisMonthsTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const currentDay = new Date(currentTimeStamp * 1000);_x000D_
  const startOfMonth = currentTimeStamp - ((currentDay.getDate() - 1) * 86400) - (currentTimeStamp % 86400);_x000D_
  const currentMonth = currentDay.getMonth() + 1;_x000D_
  let daysInMonth = 0;_x000D_
  if (currentMonth === 2) daysInMonth = 28;_x000D_
  else if ([1, 3, 5, 7, 8, 10, 12].includes(currentMonth)) daysInMonth = 31;_x000D_
  else daysInMonth = 30;_x000D_
  return { startOfMonth, endOfMonth: startOfMonth + daysInMonth * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
console.log(getTodaysTimeStamp());_x000D_
console.log(getThisWeeksTimeStamp());_x000D_
console.log(getThisMonthsTimeStamp());
_x000D_
_x000D_
_x000D_

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

Install gitk on Mac

There are two ways to fix this:

  1. Unix Way (simple and recommended)
  2. Homebrew Way

1. Unix Way: In 4 simple steps

  1. Execute which git in the terminal to know the location of your git executable. Open that directory & locate gitk inside the bin folder. Copy the path --- typically /usr/local/git/bin
  2. Edit your ~/.bash_profile to add the location of local git & gitk in the paths or, simply copy-pasta from the sample written below.

Sample bash_profile:

# enabling gitk
export PATH=/usr/local/git/bin:$PATH

If you don't have a bash_profile want to learn how to create one, then click here.

  1. This step is relevant if you're using El Capitan or higher & you run into an unknown color name “lime” error. Locate gitk executable (typically at /usr/local/bin/gitk), take a backup & open it in a text editor. Find all occurences of lime in the file & replace them with "#99FF00".
  2. Reload bash: source ~/.bash_profile

Now, run gitk


2. HomeBrew way

Updates - If you do not have homebrew on your mac, get it installed first. It may require sudo privileges.

  • brew update
  • brew doctor
  • brew link git
  • added /usr/local/Cellar/git/2.4.0/bin to path & then reload bash & run gitk
  • No luck yet? Proceed further.
  • Run which git & observe if git is still linked to /usr/bin/git
  • If yes, then open the directory & locate the was a binary executable.
  • Take its backup, may be save with a name git.bak & delete the original file
  • Reload the terminal - source ~/.bash_profile

TimeSpan to DateTime conversion

A problem with all of the above is that the conversion returns the incorrect number of days as specified in the TimeSpan.
Using the above, the below returns 3 and not 2.

Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?

public void should_return_totaldays()
{
    _ts = new TimeSpan(2, 1, 30, 10);
    var format = "dd";
    var returnedVal = _ts.ToString(format);
    Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}

Cropping an UIImage

On iOS9.2SDK ,I use below method to convert frame from UIView to UIImage

-(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect
{
  CGSize cropSize = rect.size;
  CGFloat widthScale = image.size.width/self.imageViewOriginal.bounds.size.width;
  CGFloat heightScale = image.size.height/self.imageViewOriginal.bounds.size.height;
  cropSize = CGSizeMake(rect.size.width*widthScale, 
              rect.size.height*heightScale);
  CGPoint pointCrop = CGPointMake(rect.origin.x*widthScale,
             rect.origin.y*heightScale);
  rect = CGRectMake(pointCrop.x, pointCrop.y, cropSize.width, cropSize.height);
  CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect);
  UIImage *croppedImage = [UIImage imageWithCGImage:subImage];
  CGImageRelease(subImage);

  return croppedImage;
}

How do format a phone number as a String in Java?

If you really need the right way then you can use Google's recently open sourced libphonenumber

What is the most efficient way to concatenate N arrays?

Shorten with ES6.

new Set([].concat(...Array));

This does concat and unique the multiple arrays;

Demo on codepen

Div table-cell vertical align not working

An element styled as follows will be aligned vertically to middle:

.content{
     position:relative;
     -webkit-transform: translateY(-50%);
     -ms-transform: translateY(-50%);
     transform: translateY(-50%);
     top:50%;
}

However, the parent element must have a fixed height. See this fiddle: https://jsfiddle.net/15d0qfdg/12/

Body set to overflow-y:hidden but page is still scrollable in Chrome

Try this when you want to "fix" your body's scroll:

jQuery('body').css('height', '100vh').css('overflow-y', 'hidden');

and this when you want to turn it normal again:

jQuery('body').css('height', '').css('overflow-y', '');

Replace only some groups with Regex

Here is a version similar to Daniel's but replacing multiple matches:

public static string ReplaceGroup(string input, string pattern, RegexOptions options, string groupName, string replacement)
{
    Match match;
    while ((match = Regex.Match(input, pattern, options)).Success)
    {
        var group = match.Groups[groupName];

        var sb = new StringBuilder();

        // Anything before the match
        if (match.Index > 0)
            sb.Append(input.Substring(0, match.Index));

        // The match itself
        var startIndex = group.Index - match.Index;
        var length = group.Length;
        var original = match.Value;
        var prior = original.Substring(0, startIndex);
        var trailing = original.Substring(startIndex + length);
        sb.Append(prior);
        sb.Append(replacement);
        sb.Append(trailing);

        // Anything after the match
        if (match.Index + match.Length < input.Length)
            sb.Append(input.Substring(match.Index + match.Length));

        input = sb.ToString();
    }

    return input;

How to check list A contains any value from list B?

You can Intersect the two lists:

if (A.Intersect(B).Any())

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

The page cannot be displayed because an internal server error has occurred on server

it seems it works after I commented this line in web.config

<compilation debug="true" targetFramework="4.5.2" />

Laravel-5 'LIKE' equivalent (Eloquent)

I think this is better, following the good practices of passing parameters to the query:

BookingDates::whereRaw('email = ? or name like ?', [$request->email,"%{$request->name}%"])->get();

You can see it in the documentation, Laravel 5.5.

You can also use the Laravel scout and make it easier with search. Here is the documentation.

How to Convert datetime value to yyyymmddhhmmss in SQL server?

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

How can I rename a project folder from within Visual Studio?

I often had the same problem of renaming a project in Visual Studio and editing the folder name, project name, and .sln file in order to accomplish that. I just wrote a VBScript script that accomplishes all that. You have to be careful with the strings you choose for replacing.

You just have to put the .vbs file in the same directory as the .sln file of the solution.

' Script parameters'
Solution = "Rename_Visual_Studio_Project" '.sln'
Project = "Rename_Visual_Studio_Project" '.csproj'
NewProject = "SUCCESS"

Const ForReading = 1
Const ForWriting = 2

Set objFso = CreateObject("Scripting.FileSystemObject")
scriptDirr = objFso.GetParentFolderName(wscript.ScriptFullName)

' Rename the all project references in the .sln file'
Set objFile = objFso.OpenTextFile(scriptDirr + "\" + Solution + ".sln", ForReading)
fileText = objFile.ReadAll
newFileText = Replace(fileText, Project, NewProject)
Set objFile = objFSO.OpenTextFile(scriptDirr + "\" + Solution + ".sln", ForWriting)
objFile.WriteLine(newFileText)
objFile.Close

' Rename the .csproj file'
objFso.MoveFile scriptDirr + "\" + Project + "\" + Project + ".csproj", scriptDirr + "\" + Project + "\" + NewProject + ".csproj"

' Rename the folder of the .csproj file'
objFso.MoveFolder scriptDirr + "\" + Project, scriptDirr + "\" + NewProject

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

var datatable_jquery_script = document.createElement("script");
datatable_jquery_script.src = "vendor/datatables/jquery.dataTables.min.js";
document.body.appendChild(datatable_jquery_script);
setTimeout(function(){
    var datatable_bootstrap_script = document.createElement("script");
    datatable_bootstrap_script.src = "vendor/datatables/dataTables.bootstrap4.min.js";
    document.body.appendChild(datatable_bootstrap_script);
},100);

I used setTimeOut to make sure datatables.min.js loads first. I inspected the waterfall loading of each, bootstrap4.min.js always loads first.

How to create full path with node's fs.mkdirSync?

Using reduce we can verify if each path exists and create it if necessary, also this way I think it is easier to follow. Edited, thanks @Arvin, we should use path.sep to get the proper platform-specific path segment separator.

const path = require('path');

// Path separators could change depending on the platform
const pathToCreate = 'path/to/dir'; 
pathToCreate
 .split(path.sep)
 .reduce((prevPath, folder) => {
   const currentPath = path.join(prevPath, folder, path.sep);
   if (!fs.existsSync(currentPath)){
     fs.mkdirSync(currentPath);
   }
   return currentPath;
 }, '');

Why Maven uses JDK 1.6 but my java -version is 1.7

You can also explicitly tell maven which java version to compile for. You can try adding the maven-compiler-plugin to your pom.

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
    [...]
  </build>
  [...]
</project>

If you imported a maven project into an IDE, then there is probably a maven setting in your IDE for default compiler that your maven runner is using.

CSS - center two images in css side by side

Try changing

#fblogo {
    display: block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}

to

.fblogo {
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    height: 30px; 
}

#images{
    text-align:center;
}

HTML

<div id="images">
    <a href="mailto:[email protected]">
    <img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/07/email-icon-e1343123697991.jpg"/></a>
    <a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
    <img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>
</div>?

DEMO.

HTML table headers always visible at top of window when viewing a large table

If you're targeting modern css3 compliant browsers (Browser support: https://caniuse.com/#feat=css-sticky) you can use position:sticky, which doesn't require JS and won't break the table layout miss-aligning th and td of the same column. Nor does it require fixed column width to work properly.

Example for a single header row:

thead th
{
    position: sticky;
    top: 0px;
}

For theads with 1 or 2 rows, you can use something like this:

thead > :last-child th
{
    position: sticky;
    top: 30px; /* This is for all the the "th" elements in the second row, (in this casa is the last child element into the thead) */
}

thead > :first-child th
{
    position: sticky;
    top: 0px; /* This is for all the the "th" elements in the first child row */
}

You might need to play a bit with the top property of the last child changing the number of pixels to match the height of the first row (+ the margin + the border + the padding, if any), so the second row sticks just down bellow the first one.

Also both solutions work even if you have more than one table in the same page: the th element of each one starts to be sticky when its top position is the one indicated into the css definition and just disappear when all the table scrolls down. So if there are more tables all work beautifully the same way.

Why to use last-child before and first-child after in the css?

Because css rules are rendered by the browser in the same order as you write them into the css file and because of this if you have just 1 row into the thead element the first row is simultaneously the last row too and the first-child rule need to override the last-child one. If not you will have an offset of the row 30 px from the top margin which I suppose you don't want to.

A known problem of position: sticky is that it doesn't work on thead elements or table rows: you must target th elements. Hopping this issue will be solved on future browser versions.

Working Soap client example

Calculator SOAP service test from SoapUI, Online SoapClient Calculator

Generate the SoapMessage object form the input SoapEnvelopeXML and SoapDataXml.

SoapEnvelopeXML

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:Add xmlns:tem="http://tempuri.org/">
         <tem:intA>3</tem:intA>
         <tem:intB>4</tem:intB>
      </tem:Add>
   </soapenv:Body>
</soapenv:Envelope>

use the following code to get SoapMessage Object.

MessageFactory messageFactory = MessageFactory.newInstance();
    MimeHeaders headers = new MimeHeaders();
    ByteArrayInputStream xmlByteStream = new ByteArrayInputStream(SoapEnvelopeXML.getBytes());
SOAPMessage soapMsg = messageFactory.createMessage(headers, xmlByteStream);

SoapDataXml

<tem:Add xmlns:tem="http://tempuri.org/">
    <tem:intA>3</tem:intA>
    <tem:intB>4</tem:intB>
</tem:Add>

use below code to get SoapMessage Object.

public static SOAPMessage getSOAPMessagefromDataXML(String saopBodyXML) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    dbFactory.setIgnoringComments(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    InputSource ips = new org.xml.sax.InputSource(new StringReader(saopBodyXML));
    Document docBody = dBuilder.parse(ips);
    System.out.println("Data Document: "+docBody.getDocumentElement());
    
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMsg = messageFactory.createMessage();
    
    SOAPBody soapBody = soapMsg.getSOAPPart().getEnvelope().getBody();
    soapBody.addDocument(docBody);
    
    return soapMsg;
}

By getting the SoapMessage Object. It is clear that the Soap XML is valid. Then prepare to hit the service to get response. It can be done in many ways.

  1. Using Client Code Generated form WSDL.
java.net.URL endpointURL = new java.net.URL(endPointUrl);
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.2");
CalculatorSoap12Stub obj_axis = new CalculatorSoap12Stub(endpointURL, service);
int add = obj_axis.add(10, 20);
System.out.println("Response: "+ add);
  1. Using javax.xml.soap.SOAPConnection.
public static void getSOAPConnection(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== SOAPConnection =====");
    MimeHeaders headers = soapMsg.getMimeHeaders(); // new MimeHeaders();
    headers.addHeader("SoapBinding",   serverDetails.get("SoapBinding") );
    headers.addHeader("MethodName",    serverDetails.get("MethodName") );
    headers.addHeader("SOAPAction",    serverDetails.get("SOAPAction") );
    headers.addHeader("Content-Type",  serverDetails.get("Content-Type"));
    headers.addHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    if (soapMsg.saveRequired()) {
        soapMsg.saveChanges();
    }
    
    SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
    javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
    SOAPMessage soapMsgResponse = connection.call(soapMsg, getURL( serverDetails.get("SoapServerURI"), 5*1000 ));
    
    getSOAPXMLasString(soapMsgResponse);
}
  1. Form HTTP Connection Classes org.apache.commons.httpclient.
public static void getHttpConnection(SOAPMessage soapMsg) throws SOAPException, IOException {
    System.out.println("===== HttpClient =====");
    HttpClient httpClient = new HttpClient();
    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(3 * 1000); // Connection timed out
    params.setSoTimeout(3 * 1000);         // Request timed out
    params.setParameter("http.useragent", "Web Service Test Client");

    PostMethod methodPost = new PostMethod( serverDetails.get("SoapServerURI") );
    methodPost.setRequestBody( getSOAPXMLasString(soapMsg) );
    methodPost.setRequestHeader("Content-Type", serverDetails.get("Content-Type") );
    methodPost.setRequestHeader("SoapBinding",  serverDetails.get("SoapBinding") );
    methodPost.setRequestHeader("MethodName",   serverDetails.get("MethodName") );
    methodPost.setRequestHeader("SOAPAction",   serverDetails.get("SOAPAction") );

    methodPost.setRequestHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));

    try {
        int returnCode = httpClient.executeMethod(methodPost);
        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.out.println("The Post method is not implemented by this URI");
            methodPost.getResponseBodyAsString();
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(methodPost.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }
            br.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        methodPost.releaseConnection();
    }
}
public static void accessResource_AppachePOST(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== HttpClientBuilder =====");
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    URIBuilder builder = new URIBuilder( serverDetails.get("SoapServerURI") );
    HttpPost methodPost = new HttpPost(builder.build());
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(5 * 1000)
            .setConnectionRequestTimeout(5 * 1000)
            .setSocketTimeout(5 * 1000)
            .build();
    methodPost.setConfig(config);
        HttpEntity xmlEntity = new StringEntity(getSOAPXMLasString(soapMsg), "utf-8");
    methodPost.setEntity(xmlEntity);
        
    methodPost.setHeader("Content-Type", serverDetails.get("Content-Type"));
    methodPost.setHeader("SoapBinding", serverDetails.get("SoapBinding") );
    methodPost.setHeader("MethodName", serverDetails.get("MethodName") );
    methodPost.setHeader("SOAPAction", serverDetails.get("SOAPAction") );
    methodPost.setHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    
    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status <= 500) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }
            return "";
        }
    };
    String execute = httpClient.execute( methodPost, responseHandler );
    System.out.println("AppachePOST : "+execute);
}

Full Example:

public class SOAP_Calculator {
    static HashMap<String, String> serverDetails = new HashMap<>();
    static {
        // Calculator
        serverDetails.put("SoapServerURI", "http://www.dneonline.com/calculator.asmx");
        serverDetails.put("SoapWSDL", "http://www.dneonline.com/calculator.asmx?wsdl");
        serverDetails.put("SoapBinding", "CalculatorSoap");        // <wsdl:binding name="CalculatorSoap12" type="tns:CalculatorSoap">
        serverDetails.put("MethodName", "Add");                    // <wsdl:operation name="Add">
        serverDetails.put("SOAPAction", "http://tempuri.org/Add"); // <soap12:operation soapAction="http://tempuri.org/Add" style="document"/>
        serverDetails.put("SoapXML", "<tem:Add xmlns:tem=\"http://tempuri.org/\"><tem:intA>2</tem:intA><tem:intB>4</tem:intB></tem:Add>");
        
        serverDetails.put("Accept-Encoding", "gzip,deflate");
        serverDetails.put("Content-Type", "");
    }
    public static void callSoapService( ) throws Exception {
        String xmlData = serverDetails.get("SoapXML");
        
        SOAPMessage soapMsg = getSOAPMessagefromDataXML(xmlData);
        System.out.println("Requesting SOAP Message:\n"+ getSOAPXMLasString(soapMsg) +"\n");
        
        SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
        if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
            System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
            serverDetails.put("Content-Type", "text/xml; charset=utf-8");
        } else {
            System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
            serverDetails.put("Content-Type", "application/soap+xml; charset=utf-8");
        }
        
        getHttpConnection(soapMsg);
        getSOAPConnection(soapMsg);
        accessResource_AppachePOST(soapMsg);
    }
    public static void main(String[] args) throws Exception {
        callSoapService();
    }

    private static URL getURL(String endPointUrl, final int timeOutinSeconds) throws MalformedURLException {
        URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
            protected URLConnection openConnection(URL url) throws IOException {
                URL clone = new URL(url.toString());
                URLConnection connection = clone.openConnection();
                connection.setConnectTimeout(timeOutinSeconds);
                connection.setReadTimeout(timeOutinSeconds);
                //connection.addRequestProperty("Developer-Mood", "Happy"); // Custom header
                return connection;
            }
        });
        return endpoint;
    }
    public static String getSOAPXMLasString(SOAPMessage soapMsg) throws SOAPException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapMsg.writeTo(out);
        // soapMsg.writeTo(System.out);
        String strMsg = new String(out.toByteArray());
        System.out.println("Soap XML: "+ strMsg);
        return strMsg;
    }
}

@See list of some WebServices at http://sofa.uqam.ca/soda/webservices.php

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

If you want it to be List<string>, get rid of the anonymous type and add a .ToList() call:

List<string> list = (from char c in source
                     select c.ToString()).ToList();

Print directly from browser without print popup window

For IE browsers, the "VBScript solution" works.

But as mentioned by @purefusion at Bypass Printdialog in IE9, Use Print() rather than window.print()

What is the significance of 1/1/1753 in SQL Server?

Incidentally, Windows no longer knows how to correctly convert UTC to U.S. local time for certain dates in March/April or October/November of past years. UTC-based timestamps from those dates are now somewhat nonsensical. It would be very icky for the OS to simply refuse to handle any timestamps prior to the U.S. government's latest set of DST rules, so it simply handles some of them wrong. SQL Server refuses to process dates before 1753 because lots of extra special logic would be required to handle them correctly and it doesn't want to handle them wrong.

Count all duplicates of each value

If you want to check repetition more than 1 in descending order then implement below query.

SELECT   duplicate_data,COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
HAVING   COUNT(duplicate_data) > 1
ORDER BY COUNT(duplicate_data) DESC

If want simple count query.

SELECT   COUNT(duplicate_data) AS duplicate_data
FROM     duplicate_data_table_name 
GROUP BY duplicate_data
ORDER BY COUNT(duplicate_data) DESC

Take n rows from a spark dataframe and pass to toPandas()

You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])

df_pandas = pd.DataFrame(df.head(3), columns=df.columns)

In [4]: df_pandas
Out[4]: 
     name  age
0   Alice    1
1     Jim    2
2  Sandra    3

Downloading folders from aws s3, cp or sync?

You've many options to do that, but the best one is using the AWS CLI.

Here's a walk-through:

  1. Download and install AWS CLI in your machine:

  2. Configure AWS CLI:

enter image description here

Make sure you input valid access and secret keys, which you received when you created the account.

  1. Sync the S3 bucket using:

     aws s3 sync s3://yourbucket/yourfolder /local/path
    

In the above command, replace the following fields:

  • yourbucket/yourfolder >> your S3 bucket and the folder that you want to download.
  • /local/path >> path in your local system where you want to download all the files.

Clone an image in cv2 python

The first answer is correct but you say that you are using cv2 which inherently uses numpy arrays. So, to make a complete different copy of say "myImage":

newImage = myImage.copy()

The above is enough. No need to import numpy.

Have a fixed position div that needs to scroll if content overflows

The problem with using height:100% is that it will be 100% of the page instead of 100% of the window (as you would probably expect it to be). This will cause the problem that you're seeing, because the non-fixed content is long enough to include the fixed content with 100% height without requiring a scroll bar. The browser doesn't know/care that you can't actually scroll that bar down to see it

You can use fixed to accomplish what you're trying to do.

.fixed-content {
    top: 0;
    bottom:0;
    position:fixed;
    overflow-y:scroll;
    overflow-x:hidden;
}

This fork of your fiddle shows my fix: http://jsfiddle.net/strider820/84AsW/1/

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

How to make the main content div fill height of screen with css

There is a CSS unit called viewport height / viewport width.

Example

.mainbody{height: 100vh;} similarly html,body{width: 100vw;}

or 90vh = 90% of the viewport height.

**IE9+ and most modern browsers.

jQuery window scroll event does not fire up

$('#div').scroll(function () {
   if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight-1) {

     //fire your event


    }
}

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Please ensure that you have following import. Ofcourse other standard imports

import org.springframework.core.io.FileSystemResource


    void uploadzipFiles(String token) {

        RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)

        def zipFile = new File("testdata.zip")
        def Id = "001G00000"
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
        form.add("id", id)
        form.add('file',new FileSystemResource(zipFile))
        def urld ='''http://URL''';
        def resp = rest.post(urld) {
            header('X-Auth-Token', clientSecret)
            contentType "multipart/form-data"
            body(form)
        }
        println "resp::"+resp
        println "resp::"+resp.text
        println "resp::"+resp.headers
        println "resp::"+resp.body
        println "resp::"+resp.status
    }

Check if all checkboxes are selected

Part 1 of your question:

var allChecked = true;
$("input.abc").each(function(index, element){
  if(!element.checked){
    allChecked = false;
    return false;
  } 
});

EDIT:

The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.

How to change the color of a button?

If you are trying to set the background as some other resource file in your drawable folder, say, a custom-button.xml, then try this:

button_name.setBackgroundResource(R.drawable.custom_button_file_name);

eg. Say, you have a custom-button.xml file. Then,

button_name.setBackgroundResource(R.drawable.custom_button);

Will set the button background as the custom-button.xml file.

Value cannot be null. Parameter name: source

Using the .Count() without checking for null is one strong reason for this error.

THE FIX:

if(someList != null & someList.Count()>0)
{
    //Now, put your hackable code here!
}

Abstract methods in Python

Abstract base classes are deep magic. Periodically I implement something using them and am amazed at my own cleverness, very shortly afterwards I find myself completely confused by my own cleverness (this may well just be a personal limitation though).

Another way of doing this (should be in the python std libs if you ask me) is to make a decorator.

def abstractmethod(method):
    """
    An @abstractmethod member fn decorator.
    (put this in some library somewhere for reuse).

    """
    def default_abstract_method(*args, **kwargs):
        raise NotImplementedError('call to abstract method ' 
                                  + repr(method))
    default_abstract_method.__name__ = method.__name__    
    return default_abstract_method


class Shape(object):

    def __init__(self, shape_name):
       self.shape = shape_name

    @abstractmethod
    def foo(self):
        print "bar"
        return

class Rectangle(Shape):
    # note you don't need to do the constructor twice either
    pass  

r = Rectangle("x")
r.foo()

I didn't write the decorator. It just occurred to me someone would have. You can find it here: http://code.activestate.com/recipes/577666-abstract-method-decorator/ Good one jimmy2times. Note the discussion at the bottom of that page r.e. type safety of the decorator. (That could be fixed with the inspect module if anyone was so inclined).

How do I automatically set the $DISPLAY variable for my current session?

Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.

Ring Buffer in Java

Since Guava 15.0 (released September 2013) there's EvictingQueue:

A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.

This class is not thread-safe, and does not accept null elements.

Example use:

EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]

Token Authentication vs. Cookies

One of the primary differences is that cookies are subject to Same Origin Policy whereas tokens are not. This creates all kinds of down stream effects.

Since cookies are only sent to and from a particular host that host must bear the burden of authenticating the user and the user must create an account with security data with that host in order to be verifiable.

Tokens on the other hand are issued and are not subject to same origin policy. The issuer can be literally anybody and it is up to the host to decide which issuers to trust. An issuer like Google and Facebook is typically well trusted so a host can shift the burden of authenticating the user (including storing all user security data) to another party and the user can consolidate their personal data under a specific issuer and not have to remember a bunch of different passwords for each host they interact with.

This allows for single sign on scenarios that reduce overall friction in the user experience. In theory the web also becomes more secure as specialised identity providers emerge to provide auth services instead of having every ma and pa website spinning up their own, likely half baked, auth systems. And as these providers emerge the cost of providing secure web resources for even very basic resources trends towards zero.

So in general tokens reduce the friction and costs associated with providing authentication and shifts the burden of the various aspects of a secure web to centralised parties better able to both implement and maintain security systems.

How can I add a table of contents to a Jupyter / JupyterLab notebook?

There are now two packages that can be used to handle Jupyter extensions:

  1. jupyter_contrib_nbextensions that installs extensions, including table of contents;

  2. jupyter_nbextensions_configurator that provides graphical user interfaces for configuring which nbextensions are enabled (load automatically for every notebook) and provides controls to configure the nbextensions' options.

UPDATE:

Starting from recent versions of jupyter_contrib_nbextensions, at least with conda you don't need to install jupyter_nbextensions_configurator because it gets installed together with those extensions.

How to download python from command-line?

wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz  
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.

./configure  
make  
sudo make install  

For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz

For other versions and the most up to date download links:
http://www.python.org/getit/

How to execute logic on Optional if not present?

I don't think you can do it in a single statement. Better do:

if (!obj.isPresent()) {
    logger.fatal(...);   
} else {
    obj.get().setAvailable(true);
}
return obj;

How do I iterate over the words of a string?

I like to use the boost/regex methods for this task since they provide maximum flexibility for specifying the splitting criteria.

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main() {
    std::string line("A:::line::to:split");
    const boost::regex re(":+"); // one or more colons

    // -1 means find inverse matches aka split
    boost::sregex_token_iterator tokens(line.begin(),line.end(),re,-1);
    boost::sregex_token_iterator end;

    for (; tokens != end; ++tokens)
        std::cout << *tokens << std::endl;
}

android edittext onchange listener

Anyone using ButterKnife. You can use like:

@OnTextChanged(R.id.zip_code)
void onZipCodeTextChanged(CharSequence zipCode, int start, int count, int after) {

}

"Error 404 Not Found" in Magento Admin Login Page

I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.

But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin

It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area

CSV new-line character seen in unquoted field error

Alternative and fast solution : I faced the same error. I reopened the "wierd" csv file in GNUMERIC on my lubuntu machine and exported the file as csv file. This corrected the issue.

What does getActivity() mean?

getActivity() is used for fragment. For activity, wherever you can use this, you can replace the this in fragment in similar cases with getActivity().

How do you set EditText to only accept numeric values in Android?

<EditText
android:id="@+id/age"
android:numeric="integer" 
/>

How to parse a string into a nullable int

C# < 7.1

using default operator

var result = int.TryParse(foo, out var f) ? f : default(int?);

C# >= 7.1

using default literal

var result = int.TryParse(foo, out var f) ? f : default;

See C# language versioning to ascertain what language version your project supports

Sources:

Python: List vs Dict for look up table

A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part.


EDIT: for your new question, YES, a set would be better. Just create 2 sets, one for sequences ended in 1 and other for the sequences ended in 89. I have sucessfully solved this problem using sets.

How do I implement Toastr JS?

Toastr is a very nice component, and you can show messages with theses commands:

// for success - green box
toastr.success('Success messages');

// for errors - red box
toastr.error('errors messages');

// for warning - orange box
toastr.warning('warning messages');

// for info - blue box
toastr.info('info messages');

If you want to provide a title on the toastr message, just add a second argument:

// for info - blue box
toastr.success('The process has been saved.', 'Success');

you also can change the default behaviour using something like this:

toastr.options.timeOut = 3000; // 3s

See more on the github of the project.

Edits

A sample of use:

$(document).ready(function() {

    // show when page load
    toastr.info('Page Loaded!');

    $('#linkButton').click(function() {
       // show when the button is clicked
       toastr.success('Click Button');

    });

});

and a html:

<a id='linkButton'>Show Message</a>

SQL: How to get the id of values I just INSERTed?

SELECT @@Scope_Identity as Id

There is also @@identity, but if you have a trigger, it will return the results of something that happened during the trigger, where scope_identity respects your scope.

Search code inside a Github project

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

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

How to show a GUI message box from a bash script in linux?

The zenity application appears to be what you are looking for.

To take input from zenity, you can specify a variable and have the output of zenity --entry saved to it. It looks something like this:

my_variable=$(zenity --entry)

If you look at the value in my_variable now, it will be whatever was typed in the zenity pop up entry dialog.

If you want to give some sort of prompt as to what the user (or you) should enter in the dialog, add the --text switch with the label that you want. It looks something like this:

my_variable=$(zenity --entry --text="What's my variable:")

Zenity has lot of other nice options that are for specific tasks, so you might want to check those out as well with zenity --help. One example is the --calendar option that let's you select a date from a graphical calendar.

my_date=$(zenity --calendar)

Which gives a nicely formatted date based on what the user clicked on:

echo ${my_date}

gives:

08/05/2009

There are also options for slider selectors, errors, lists and so on.

Hope this helps.

How can I remove an element from a list?

Use - (Negative sign) along with position of element, example if 3rd element is to be removed use it as your_list[-3]

Input

my_list <- list(a = 3, b = 3, c = 4, d = "Hello", e = NA)
my_list
# $`a`
# [1] 3

# $b
# [1] 3

# $c
# [1] 4

# $d
# [1] "Hello"

# $e
# [1] NA

Remove single element from list

 my_list[-3]
 # $`a`
 # [1] 3

 # $b
 # [1] 3

 # $d
 # [1] "Hello"

 # $e
 [1] NA

Remove multiple elements from list

 my_list[c(-1,-3,-2)]
 # $`d`
 # [1] "Hello"

 # $e
 # [1] NA

 my_list[c(-3:-5)]
 # $`a`
 # [1] 3

 # $b
 # [1] 3

 my_list[-seq(1:2)]
 # $`c`
 # [1] 4

 # $d
 # [1] "Hello"

 # $e
 # [1] NA

Write to text file without overwriting in Java

For some reason, none of the other methods worked for me...So i tried this and worked. Hope it helps..

JFileChooser c= new JFileChooser();
c.showOpenDialog(c);
File write_file = c.getSelectedFile();
String Content = "Writing into file\n hi \n hello \n hola";
try 
{
    RandomAccessFile raf = new RandomAccessFile(write_file, "rw");
    long length = raf.length();
    System.out.println(length);
    raf.setLength(length + 1); //+ (integer value) for spacing
    raf.seek(raf.length());
    raf.writeBytes(Content);
    raf.close();
} 
catch (Exception e) {
    System.out.println(e);
}

Add a properties file to IntelliJ's classpath

This is one of the dumb mistakes I've done. I spent a lot of time trying to debug this problem and tried all the responses posted above, but in the end, it was one of my many dumb mistakes.

I was using org.apache.logging.log4j.Logger (:fml:) whereas I should have used org.apache.log4j.Logger. Using this correct logger saved my evening.

How to plot multiple functions on the same figure, in Matplotlib?

Just use the function plot as follows

figure()
...
plot(t, a)
plot(t, b)
plot(t, c)

Eclipse error: "The import XXX cannot be resolved"

Or in you module-info.java, add:

requires org.hibernate;

Regular expression to stop at first match

Use non-greedy matching, if your engine supports it. Add the ? inside the capture.

/location="(.*?)"/

Stacking DIVs on top of each other?

All the answers seem pretty old :) I'd prefer CSS grid for a better page layout (absolute divs can be overridden by other divs in the page.)

<div class="container">
  <div class="inner" style="background-color: white;"></div>
  <div class="inner" style="background-color: red;"></div>
  <div class="inner" style="background-color: green;"></div>
  <div class="inner" style="background-color: blue;"></div>
  <div class="inner" style="background-color: purple;"></div>
  <div class="inner no-display" style="background-color: black;"></div>
</div>

<style>
.container {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-color: yellow;
  display: grid;
  place-items: center;
  grid-template-areas:
                  "inners";
}

.inner {
  grid-area: inners;
  height: 100px;
  width: 100px;
}

.no-display {
  display: none;
}
</style>

Here's a working link

Redirect to external URL with return in laravel

For Laravel 5.x we can redirect with just

return redirect()->to($url);

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

You need to access image IDs using R.mipmap.yourImageName

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

Optional Parameters in Go?

I am a little late, but if you like fluent interface you might design your setters for chained calls like this:

type myType struct {
  s string
  a, b int
}

func New(s string, err *error) *myType {
  if s == "" {
    *err = errors.New(
      "Mandatory argument `s` must not be empty!")
  }
  return &myType{s: s}
}

func (this *myType) setA (a int, err *error) *myType {
  if *err == nil {
    if a == 42 {
      *err = errors.New("42 is not the answer!")
    } else {
      this.a = a
    }
  }
  return this
}

func (this *myType) setB (b int, _ *error) *myType {
  this.b = b
  return this
}

And then call it like this:

func main() {
  var err error = nil
  instance :=
    New("hello", &err).
    setA(1, &err).
    setB(2, &err)

  if err != nil {
    fmt.Println("Failed: ", err)
  } else {
    fmt.Println(instance)
  }
}

This is similar to the Functional options idiom presented on @Ripounet answer and enjoys the same benefits but has some drawbacks:

  1. If an error occurs it will not abort immediately, thus, it would be slightly less efficient if you expect your constructor to report errors often.
  2. You'll have to spend a line declaring an err variable and zeroing it.

There is, however, a possible small advantage, this type of function calls should be easier for the compiler to inline but I am really not a specialist.

How can I make all images of different height and width the same via CSS?

You can use the object-fit property to size the img elements:

  • cover stretches or shrinks the image proportionally to fill the container. The image is cropped horizontally -or- vertically if necessary.
  • contain stretches or shrinks the image proportionally to fit inside the container.
  • scale-down shrinks the image proportionally to fit inside the container.

_x000D_
_x000D_
.example {_x000D_
  margin: 1em 0;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.example img {_x000D_
  width: 30vw;_x000D_
  height: 30vw;_x000D_
}_x000D_
_x000D_
.example-cover img {_x000D_
  object-fit: cover;_x000D_
}_x000D_
_x000D_
.example-contain img {_x000D_
  object-fit: contain;_x000D_
}
_x000D_
<div class="example example-cover">_x000D_
  <img src="https://i.stack.imgur.com/B0EAo.png">_x000D_
  <img src="https://i.stack.imgur.com/iYkNH.png">_x000D_
  <img src="https://i.stack.imgur.com/gne9N.png">_x000D_
</div>_x000D_
_x000D_
<div class="example example-contain">_x000D_
  <img src="https://i.stack.imgur.com/B0EAo.png">_x000D_
  <img src="https://i.stack.imgur.com/iYkNH.png">_x000D_
  <img src="https://i.stack.imgur.com/gne9N.png">_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example: red is landscape, green is portrait and blue is square image. The checkered pattern consists of 16x16px squares.

What is the difference between active and passive FTP?

Active mode: -server initiates the connection.

Passive mode: -client initiates the connection.

form action with javascript

A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.

The best is to just set form action to your PHP script; if you need to do anything before submission you can just add to onsubmit

Edit turned out you didn't need any extra function, just a small change here:

function validateFormOnSubmit(theForm) {
    var reason = "";
    reason += validateName(theForm.name);
    reason += validatePhone(theForm.phone);
    reason += validateEmail(theForm.emaile);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
    } else {
        simpleCart.checkout();
    }
    return false;
}

Then in your form:

<form action="#" onsubmit="return validateFormOnSubmit(this);">

Get properties of a class

I am currently working on a Linq-like library for Typescript and wanted to implement something like GetProperties of C# in Typescript / Javascript. The more I work with Typescript and generics, the clearer picture I get of that you usually have to have an instantiated object with intialized properties to get any useful information out at runtime about properties of a class. But it would be nice to retrieve information anyways just from the constructor function object, or an array of objects and be flexible about this.

Here is what I ended up with for now.

First off, I define Array prototype method ('extension method' for you C# developers).

export { } //creating a module of below code
declare global {
  interface Array<T> {
    GetProperties<T>(TClass: Function, sortProps: boolean): string[];
} }

The GetProperties method then looks like this, inspired by madreason's answer.

if (!Array.prototype.GetProperties) {
  Array.prototype.GetProperties = function <T>(TClass: any = null, sortProps: boolean = false): string[] {
    if (TClass === null || TClass === undefined) {
      if (this === null || this === undefined || this.length === 0) {
        return []; //not possible to find out more information - return empty array
      }
    }
    // debugger
    if (TClass !== null && TClass !== undefined) {
      if (this !== null && this !== undefined) {
        if (this.length > 0) {
          let knownProps: string[] = Describer.describe(this[0]).Where(x => x !== null && x !== undefined);
          if (sortProps && knownProps !== null && knownProps !== undefined) {
            knownProps = knownProps.OrderBy(p => p);
          }
          return knownProps;
        }
        if (TClass !== null && TClass !== undefined) {
          let knownProps: string[] = Describer.describe(TClass).Where(x => x !== null && x !== undefined);
          if (sortProps && knownProps !== null && knownProps !== undefined) {
            knownProps = knownProps.OrderBy(p => p);
          }
          return knownProps;
        }
      }
    }
    return []; //give up..
  }
}

The describer method is about the same as madreason's answer. It can handle both class Function and if you get an object instead. It will then use Object.getOwnPropertyNames if no class Function is given (i.e. the class 'type' for C# developers).

class Describer {
  private static FRegEx = new RegExp(/(?:this\.)(.+?(?= ))/g);
  static describe(val: any, parent = false): string[] {
    let isFunction = Object.prototype.toString.call(val) == '[object Function]';
    if (isFunction) {
      let result = [];
      if (parent) {
        var proto = Object.getPrototypeOf(val.prototype);
        if (proto) {
          result = result.concat(this.describe(proto.constructor, parent));
        }
      }
      result = result.concat(val.toString().match(this.FRegEx));
      result = result.Where(r => r !== null && r !== undefined);
      return result;
    }
    else {
      if (typeof val == "object") {
        let knownProps: string[] = Object.getOwnPropertyNames(val);
        return knownProps;
      }
    }
    return val !== null ? [val.tostring()] : [];
  }
}

Here you see two specs for testing this out with Jasmine.

class Hero {
  name: string;
  gender: string;
  age: number;
  constructor(name: string = "", gender: string = "", age: number = 0) {
    this.name = name;
    this.gender = gender;
    this.age = age;
  }
}

class HeroWithAbility extends Hero {
  ability: string;
  constructor(ability: string = "") {
    super();
    this.ability = ability;
  }
}

describe('Array Extensions tests for TsExtensions Linq esque library', () => {

  it('can retrieve props for a class items of an array', () => {
    let heroes: Hero[] = [<Hero>{ name: "Han Solo", age: 44, gender: "M" }, <Hero>{ name: "Leia", age: 29, gender: "F" }, <Hero>{ name: "Luke", age: 24, gender: "M" }, <Hero>{ name: "Lando", age: 47, gender: "M" }];
    let foundProps = heroes.GetProperties(Hero, false);
    //debugger
    let expectedArrayOfProps = ["name", "age", "gender"];
    expect(foundProps).toEqual(expectedArrayOfProps);
    expect(heroes.GetProperties(Hero, true)).toEqual(["age", "gender", "name"]);
  });

  it('can retrieve props for a class only knowing its function', () => {
    let heroes: Hero[] = [];
    let foundProps = heroes.GetProperties(Hero, false);
    let expectedArrayOfProps = ["this.name", "this.gender", "this.age"];
    expect(foundProps).toEqual(expectedArrayOfProps);
    let foundPropsThroughClassFunction = heroes.GetProperties(Hero, true);
    //debugger
    expect(foundPropsThroughClassFunction.SequenceEqual(["this.age", "this.gender", "this.name"])).toBe(true);
  });

And as madreason mentioned, you have to initialize the props to get any information out from just the class Function itself, or else it is stripped away when Typescript code is turned into Javascript code.

Typescript 3.7 is very good with Generics, but coming from a C# and Reflection background, some fundamental parts of Typescript and generics still feels somewhat loose and unfinished business. Like my code here, but at least I got out the information I wanted - a list of property names for a given class or instance of objects.

SequenceEqual is this method btw:

    if (!Array.prototype.SequenceEqual) {
  Array.prototype.SequenceEqual = function <T>(compareArray: T): boolean {
    if (!Array.isArray(this) || !Array.isArray(compareArray) || this.length !== compareArray.length)
      return false;
    var arr1 = this.concat().sort();
    var arr2 = compareArray.concat().sort();
    for (var i = 0; i < arr1.length; i++) {
      if (arr1[i] !== arr2[i])
        return false;
    }
    return true;
  }
}

Moment.js - how do I get the number of years since a date, not rounded up?

This method is easy and powerful.

Value is a date and "DD-MM-YYYY" is the mask of the date.

moment().diff(moment(value, "DD-MM-YYYY"), 'years');

What is the difference between Python and IPython?

Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

You can install Ipython using pip - pip install ipython

You can run Ipython by typing ipython in your terminal window.

Android Spinner : Avoid onItemSelected calls during initialization

spinner.setOnItemSelectedListener(this); // Will call onItemSelected() Listener.

So first time handle this with any Integer value

Example: Initially Take int check = 0;

public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
   if(++check > 1) {
      TextView textView = (TextView) findViewById(R.id.textView1);
      String str = (String) parent.getItemAtPosition(pos);
      textView.setText(str);
   }
}

You can do it with boolean value and also by checking current and previous positions. See here

Spring Bean Scopes

Detailed explanation for each scope can be found here in Spring bean scopes. Below is the summary

Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype - Scopes a single bean definition to any number of object instances.

request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Is there any option to limit mongodb memory usage?

I don't think you can configure how much memory MongoDB uses, but that's OK (read below).

To quote from the official source:

Virtual memory size and resident size will appear to be very large for the mongod process. This is benign: virtual memory space will be just larger than the size of the datafiles open and mapped; resident size will vary depending on the amount of memory not used by other processes on the machine.

In other words, Mongo will let other programs use memory if they ask for it.

read.csv warning 'EOF within quoted string' prevents complete reading of file

I too had the similar problem. But in my case, the cause of the issue was due to the presence of apostrophes (i.e. single quotation marks) within some of the text values. This is especially frequent when working with data including texts in French, e.g. «L'autre jour».

So, the solution was simply to adjust the default setting of the quote argument to exclude the «'» symbol, and thus, using quote = "\"" (i.e. double quotation mark only), everything worked fine.

I hope that can help some of you. Cheers.

Is there a developers api for craigslist.org

Good news everybody! Craigslist has actually released a bulk posting api now!

Enjoy

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

C# elegant way to check if a property's property is null

It is not possible.
ObjectA.PropertyA.PropertyB will fail if ObjectA is null due to null dereferencing, which is an error.

if(ObjectA != null && ObjectA.PropertyA ... works due to short circuiting, ie ObjectA.PropertyA will never be checked if ObjectA is null.

The first way you propose is the best and most clear with intent. If anything you could try to redesign without having to rely on so many nulls.

Invalidating JSON Web Tokens

An approach I've been considering is to always have an iat (issued at) value in the JWT. Then when a user logs out, store that timestamp on the user record. When validating the JWT just compare the iat to the last logged out timestamp. If the iat is older, then it's not valid. Yes, you have to go to the DB, but I'll always be pulling the user record anyway if the JWT is otherwise valid.

The major downside I see to this is that it'd log them out of all their sessions if they're in multiple browsers, or have a mobile client too.

This could also be a nice mechanism for invalidating all JWTs in a system. Part of the check could be against a global timestamp of the last valid iat time.

How to set component default props on React component

use a static defaultProps like:

export default class AddAddressComponent extends Component {
    static defaultProps = {
        provinceList: [],
        cityList: []
    }

render() {
   let {provinceList,cityList} = this.props
    if(cityList === undefined || provinceList === undefined){
      console.log('undefined props')
    }
    ...
}

AddAddressComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
}

AddAddressComponent.defaultProps = {
  cityList: [],
  provinceList: [],
}

AddAddressComponent.propTypes = {
  userInfo: React.PropTypes.object,
  cityList: PropTypes.array.isRequired,
  provinceList: PropTypes.array.isRequired,
}

Taken from: https://github.com/facebook/react-native/issues/1772

If you wish to check the types, see how to use PropTypes in treyhakanson's or Ilan Hasanov's answer, or review the many answers in the above link.

How do I install PHP cURL on Linux Debian?

Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version and see the versions.

Here's what I did to get the latest curl version installed in Ubuntu:

  1. sudo add-apt-repository "deb http://mirrors.kernel.org/ubuntu wily main"
  2. sudo apt-get update
  3. sudo apt-get install curl

MySQL "between" clause not inclusive?

From the MySQL-manual:

This is equivalent to the expression (min <= expr AND expr <= max)

Where is debug.keystore in Android Studio

The default keystore file: debug.keystore is present in the folder .android which is usually located in the default home folder of your operating system of the user who installed that Android SDK.

In my Ubuntu PC, it's location is /home/dhananjay/.android

Whereas in the Windows PC it is located at C:\Users\dhananjay\.android