Programs & Examples On #Google style guide

The Google Style Guide project holds the style guidelines googlers use for Google code.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

jQuery selector to get form by name

For detecting if the form is present, I'm using

if($('form[name="frmSave"]').length > 0) {
    //do something
}

Web Reference vs. Service Reference

Add Web Reference is the old-style, deprecated ASP.NET webservices (ASMX) technology (using only the XmlSerializer for your stuff) - if you do this, you get an ASMX client for an ASMX web service. You can do this in just about any project (Web App, Web Site, Console App, Winforms - you name it).

Add Service Reference is the new way of doing it, adding a WCF service reference, which gives you a much more advanced, much more flexible service model than just plain old ASMX stuff.

Since you're not ready to move to WCF, you can also still add the old-style web reference, if you really must: when you do a "Add Service Reference", on the dialog that comes up, click on the [Advanced] button in the button left corner:

alt text

and on the next dialog that comes up, pick the [Add Web Reference] button at the bottom.

SQL subquery with COUNT help

Do you want to get the number of rows?

SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName

Remove Datepicker Function dynamically

what about using the official API?

According to the API doc:

DESTROY: Removes the datepicker functionality completely. This will return the element back to its pre-init state.

Use:

$("#txtSearch").datepicker("destroy");

to restore the input to its normal behaviour and

$("#txtSearch").datepicker(/*options*/);

again to show the datapicker again.

Using os.walk() to recursively traverse directories in Python

Recursive walk through a directory where you get ALL files from all dirs in the current directory and you get ALL dirs from the current directory - because codes above don't have a simplicity (imho):

for root, dirs, files in os.walk(rootFolderPath):
    for filename in files:
        doSomethingWithFile(os.path.join(root, filename))
    for dirname in dirs:
        doSomewthingWithDir(os.path.join(root, dirname))

How do I compile C++ with Clang?

The command clang is for C, and the command clang++ is for C++.

Scikit-learn train_test_split with indices

Here's the simplest solution (Jibwa made it seem complicated in another answer), without having to generate indices yourself - just using the ShuffleSplit object to generate 1 split.

import numpy as np 
from sklearn.model_selection import ShuffleSplit # or StratifiedShuffleSplit
sss = ShuffleSplit(n_splits=1, test_size=0.1)

data_size = 100
X = np.reshape(np.random.rand(data_size*2),(data_size,2))
y = np.random.randint(2, size=data_size)

sss.get_n_splits(X, y)
train_index, test_index = next(sss.split(X, y)) 

X_train, X_test = X[train_index], X[test_index] 
y_train, y_test = y[train_index], y[test_index]

What does it mean when an HTTP request returns status code 0?

Workaround: what we ended up doing

We figured it was to do with firewall issues, and so we came up with a workaround that did the trick. If anyone has this same issue, here's what we did:

  1. We still write the data to a text file on the local hard disk as we previously did, using an HTA.

  2. When the user clicks "send data back to server", the HTA reads in the data and writes out an HTML page that includes that data as an XML data island (actually using a SCRIPT LANGUAGE=XML script block).

  3. The HTA launches a link to the HTML page in the browser.

  4. The HTML page now contains the javascript that posts the data to the server (using Microsoft.XMLHTTP).

Hope this helps anyone with a similar requirement. In this case it was a Flash game used on a laptop at tradeshows. We never had access to the laptop and could only email it to the client as this tradeshow was happening in another country.

Laravel Mail::send() sending to multiple to or bcc addresses

You can loop over recipientce like:

foreach (['[email protected]', '[email protected]'] as $recipient) {
    Mail::to($recipient)->send(new OrderShipped($order));
}

See documentation here

Remove credentials from Git

You have to update it in your Credential Manager.

Go to Control Panel > User Accounts > Credential Manager > Windows Credentials. You will see Git credentials in the list (e.g. git:https://). Click on it, update the password, and execute git pull/push command from your Git bash and it won't throw any more error messages.

How do I disable TextBox using JavaScript?

You can use disabled attribute to disable the textbox.

document.getElementById('color').disabled = true;

A valid provisioning profile for this executable was not found... (again)

After wasting my half day I got this working.

Select Target > Edit Scheme > Select Run > Change Build Configuration to debug

how to enable sqlite3 for php?

For Debian distributions. Nothing worked for until I added the debian main repositories on the apt sources (I don't know how were they removed): sudo vi /etc/apt/sources.list

and added

deb  http://deb.debian.org/debian  stretch main
deb-src  http://deb.debian.org/debian  stretch main

after that sudo apt-get update (you can upgrade too) and finally sudo apt-get install php-sqlite3

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

Using /proc/tty/drivers only indicates which tty drivers are loaded. If you're looking for a list of the serial ports check out /dev/serial, it will have two subdirectories: by-id and by-path.

EX:

# find . -type l
./by-path/usb-0:1.1:1.0-port0
./by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0

Thanks to this post: https://superuser.com/questions/131044/how-do-i-know-which-dev-ttys-is-my-serial-port

MySQL Multiple Joins in one query?

I shared my experience of using two LEFT JOINS in a single SQL query.

I have 3 tables:

Table 1) Patient consists columns PatientID, PatientName

Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID

Table 3) Doctor consists columns DoctorID, DoctorName


Query:

SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname

FROM Appointment 

LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId  //have doctorId column common

LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId      //have patientid column common

WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE

AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates 

ORDER BY AppointmentDateTime ASC;  // getting data as ascending order

I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")

SmartGit Installation and Usage on Ubuntu

Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.

JPA entity without id

If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.

I do not want to inherit the child opacity from the parent in CSS

Instead of using opacity, set a background-color with rgba, where 'a' is the level of transparency.

So instead of:

background-color: rgb(0,0,255); opacity: 0.5;

use

background-color: rgba(0,0,255,0.5);

Set Background cell color in PHPExcel

$objPHPExcel
->getActiveSheet()
->getStyle('A1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setRGB('colorcode'); //i.e,colorcode=D3D3D3

Check if a variable is of function type

The below seems to work for me as well (tested from node.js):

var isFunction = function(o) {
     return Function.prototype.isPrototypeOf(o);
};

console.log(isFunction(function(){})); // true
console.log(isFunction({})); // false

Google Maps how to Show city or an Area outline

i was looking for the same and found the answer,

solution is to use the styled map, on below link you can create your custom styles through wizard and test is at the same time google map style wizard

you can check all available options : here

here is my sample code which creates boundary for states and hide all the road and there labels.

    var styles = [
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [
      { "visibility": "on" },
      { "weight": 2.5 },
      { "color": "#24b0e2" }
    ]
  },{
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [
      { "visibility": "off" }
    ]
  },{
    "featureType": "administrative.locality",
    "stylers": [
      { "visibility": "off" }
    ]
  },{
    "featureType": "road",
    "elementType": "labels",
    "stylers": [
      { "visibility": "off" }
    ]
  }
];

  var  geocoder = new google.maps.Geocoder();
   geocoder.geocode({
       'address': "rajasthan"
   }, (results, status)=> {
     var mapOpts = {
       mapTypeId: google.maps.MapTypeId.ROADMAP,
       scaleControl: true,
       scrollwheel: false,
       styles:styles,
       center: results[0].geometry.location,
       zoom:6
     }
     map = new google.maps.Map(document.getElementById("map"), mapOpts);
   });

How to outline text in HTML / CSS

There are some webkit css properties that should work on Chrome/Safari at least:

-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: black;

That's a 2px wide black text outline.

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

To drop duplicate indices, use df = df.loc[df.index.drop_duplicates()]. C.f. pandas.pydata.org/pandas-docs/stable/generated/… – BallpointBen Apr 18 at 15:25

This is wrong but I can't reply directly to BallpointBen's comment due to low reputation. The reason its wrong is that df.index.drop_duplicates() returns a list of unique indices, but when you index back into the dataframe using those the unique indices it still returns all records. I think this is likely because indexing using one of the duplicated indices will return all instances of the index.

Instead, use df.index.duplicated(), which returns a boolean list (add the ~ to get the not-duplicated records):

df = df.loc[~df.index.duplicated()]

writing to existing workbook using xlwt

Here's some sample code I used recently to do just that.

It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file.

from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils
from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd

START_ROW = 297 # 0 based (subtract 1 from excel row number)
col_age_november = 1
col_summer1 = 2
col_fall1 = 3

rb = open_workbook(file_path,formatting_info=True)
r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file
wb = copy(rb) # a writable copy (I can't read values out of this, only write to it)
w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy

for row_index in range(START_ROW, r_sheet.nrows):
    age_nov = r_sheet.cell(row_index, col_age_november).value
    if age_nov == 3:
        #If 3, then Combo I 3-4 year old  for both summer1 and fall1
        w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')
        w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')

wb.save(file_path + '.out' + os.path.splitext(file_path)[-1])

HTML text-overflow ellipsis detection

Adding to italo's answer, you can also do this using jQuery.

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.width() < $jQueryObject[0].scrollWidth);
}

Also, as Smoky pointed out, you may want to use jQuery outerWidth() instead of width().

function isEllipsisActive($jQueryObject) {
    return ($jQueryObject.outerWidth() < $jQueryObject[0].scrollWidth);
}

Bootstrap 3 Carousel Not Working

Recently I was helping a friend to find why their carousel was not working. Controls would not work and images were not transitioning. I had a working sample on a page I had used and we went through all the code including checking the items above in this post. We pasted the "good" carousel into the same page and it still worked. Now, all css and bootstrap files were the same for both. The code was now identical, so all we could try was the images.

So, we replaced the images with two that were working in my sample. It worked. We replaced the two images with the first two that were originally not working, and it worked. We added back each image (all jpegs) one-by-one, and when we got to the seventh image (of 18) and the carousel failed. Weird. We removed this one image and continued to add the remaining images until they were all added and the carousel worked.

for reference, we were using jquery-3.3.1.slim.min.js and bootstrap/4.3.1/js/bootstrap.min.js on this site.

I do not know why an image would or could cause a carousel to malfunction, but it did. I couldn't find a reference to this cause elsewhere either, so I'm posting here for posterity in the hope that it might help someone else when other solutions fail.

Test carousel with limited set of "known-to-be-good" images.

Rounded corner for textview in android

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dp" />
            <solid android:color="#ffffff"/>

        </shape>
    </item>
</layer-list>

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

this will work as you asked without CHAR(38):

update t set country = 'Trinidad and Tobago' where country = 'trinidad & '|| 'tobago';

create table table99(col1 varchar(40));
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
SELECT * FROM table99;

update table99 set col1 = 'Trinidad and Tobago' where col1 = 'Trinidad &'||'  Tobago';

How to resolve 'unrecognized selector sent to instance'?

Mine was something simple/stupid. Newbie mistake, for anyone that has converted their NSManagedObject to a normal NSObject.

I had:

@dynamic order_id;

when i should have had:

@synthesize order_id;

How to rename a file using svn?

This message will appear if you are using a case-insensitive file system (e.g. on a Mac) and you're trying to capitalize the name (or another change of case). In which case you need to rename to a third, dummy, name:

svn mv file-name file-name_
svn mv file-name_ FILE_Name
svn commit

AngularJS ng-if with multiple conditions

you can also try with && for mandatory constion if both condtion are true than work

//div ng-repeat="(k,v) in items"

<div ng-if="(k == 'a' &&  k == 'b')">
    <!-- SOME CONTENT -->
</div>

Java : Sort integer array without using Arrays.sort()

here is the Sorting Simple Example try it

public class SortingSimpleExample {

    public static void main(String[] args) {
        int[] a={10,20,1,5,4,20,6,4,2,5,4,6,8,-5,-1};
              a=sort(a);
        for(int i:a)
              System.out.println(i);
}
    public static int[] sort(int[] a){

        for(int i=0;i<a.length;i++){
            for(int j=0;j<a.length;j++){
                int temp=0;
                if(a[i]<a[j]){
                    temp=a[j];                  
                    a[j]=a[i];                  
                    a[i]=temp;      
                  }         
                }
        }
        return a;

    }
}

onSaveInstanceState () and onRestoreInstanceState ()

As a workaround, you could store a bundle with the data you want to maintain in the Intent you use to start activity A.

Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("bundle", theBundledData);
startActivity(intent);

Activity A would have to pass this back to Activity B. You would retrieve the intent in Activity B's onCreate method.

Intent intent = getIntent();
Bundle intentBundle;
if (intent != null)
    intentBundle = intent.getBundleExtra("bundle");
// Do something with the data.

Another idea is to create a repository class to store activity state and have each of your activities reference that class (possible using a singleton structure.) Though, doing so is probably more trouble than it's worth.

android - How to get view from context?

In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():

View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);

Now you can access your views via 'view' and cast them to your view type:

myImage = (ImageView) view.findViewById(R.id.my_image);

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

Is there a built-in function to print all the current properties and values of an object?

A metaprogramming example Dump object with magic:

$ cat dump.py
#!/usr/bin/python
import sys
if len(sys.argv) > 2:
    module, metaklass  = sys.argv[1:3]
    m = __import__(module, globals(), locals(), [metaklass])
    __metaclass__ = getattr(m, metaklass)

class Data:
    def __init__(self):
        self.num = 38
        self.lst = ['a','b','c']
        self.str = 'spam'
    dumps   = lambda self: repr(self)
    __str__ = lambda self: self.dumps()

data = Data()
print data

Without arguments:

$ python dump.py
<__main__.Data instance at 0x00A052D8>

With Gnosis Utils:

$ python dump.py gnosis.magic MetaXMLPickler
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Data" id="11038416">
<attr name="lst" type="list" id="11196136" >
  <item type="string" value="a" />
  <item type="string" value="b" />
  <item type="string" value="c" />
</attr>
<attr name="num" type="numeric" value="38" />
<attr name="str" type="string" value="spam" />
</PyObject>

It is a bit outdated but still working.

Why is this HTTP request not working on AWS Lambda?

Of course, I was misunderstanding the problem. As AWS themselves put it:

For those encountering nodejs for the first time in Lambda, a common error is forgetting that callbacks execute asynchronously and calling context.done() in the original handler when you really meant to wait for another callback (such as an S3.PUT operation) to complete, forcing the function to terminate with its work incomplete.

I was calling context.done way before any callbacks for the request fired, causing the termination of my function ahead of time.

The working code is this:

var http = require('http');

exports.handler = function(event, context) {
  console.log('start request to ' + event.url)
  http.get(event.url, function(res) {
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
    context.done(null, 'FAILURE');
  });

  console.log('end request to ' + event.url);
}

Update: starting 2017 AWS has deprecated the old Nodejs 0.10 and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.

function(event, context, callback)

Although you will still find the succeed, done and fail on the context parameter, AWS suggest to use the callback function instead or null is returned by default.

callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok

Complete documentation can be found at http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

Change Tomcat Server's timeout in Eclipse

  1. Go to server View
  2. Double click the server for which you want to change the time limit
  3. On the right hand side you have timeouts dropdown tab. Select that.
  4. You then have option to change the time limits.

enter image description here

Get GPS location via a service in Android

I don't understand what exactly is the problem with implementing location listening functionality in the Service. It looks pretty similar to what you do in Activity. Just define a location listener and register for location updates. You can refer to the following code as example:

Manifest file:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity android:label="@string/app_name" android:name=".LocationCheckerActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".MyService" android:process=":my_service" />
</application>

The service file:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 10f;

    private class LocationListener implements android.location.LocationListener {
        Location mLastLocation;

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }
}

Import Error: No module named numpy

solution for me - I installed numpy inside a virtual environment, but then running ipython was not inside virtual env:

(venv) ?  which python
/Users/alon/code/google_photos_project/venv/bin/python
(venv) ?  which ipython
/usr/bin/ipython

so I had to install ipython, and run ipython from the venv like this:

python -c 'import IPython; IPython.terminal.ipapp.launch_new_instance()'

Passing data from controller to view in Laravel

try with this code :

Controller:
-----------------------------
 $fromdate=date('Y-m-d',strtotime(Input::get('fromdate'))); 
        $todate=date('Y-m-d',strtotime(Input::get('todate'))); 

 $datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To 
        return view('inventoryreport/inventoryreportview', compact('datas'));

View Page : 
@foreach($datas as $student)
   {{$student}}

@endforeach
[Link here]

Margin on child element moves parent element

Using top instead of margin-top is another possible solution, if appropriate.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

How do I import an SQL file using the command line in MySQL?

If you are using xampp then go to xampp > mysql > bin and open cmd here and paste this.

mysql -u root -p dbname < dbfilename.sql

How to check if an email address exists without sending an email?

function EmailValidation($email)
{
    $email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits
    if (eregi('[a-z||0-9]@[a-z||0-9].[a-z]', $email)) {
        //checks to make sure the email address is in a valid format
        $domain = explode( "@", $email ); //get the domain name
        if (@fsockopen ($domain[1],80,$errno,$errstr,3)) {
            //if the connection can be established, the email address is probably valid
            echo "Domain Name is valid ";
            return true;
        } else {
            echo "Con not a email domian";
            return false; //if a connection cannot be established return false
        }
        return false; //if email address is an invalid format return false
    }
}

How do I pass parameters to a jar file at the time of execution?

Incase arguments have spaces in it, you can pass like shown below.

java -jar myjar.jar 'first argument' 'second argument'

What is the ultimate postal code and zip regex?

There is none.

Postal/zip codes around the world don't follow a common pattern. In some countries they are made up by numbers, in others they can be combinations of numbers an letters, some can contain spaces, others dots, the number of characters can vary from two to at least six...

What you could do (theoretically) is create a seperate regex for every country in the world, not recommendable IMO. But you would still be missing on the validation part: Zip code 12345 may exist, but 12346 not, maybe 12344 doesn't exist either. How do you check for that with a regex?

You can't.

Razor/CSHTML - Any Benefit over what we have?

Ex Microsoft Developer's Opinion

I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.

Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.

One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.

Reading e-mails from Outlook with Python through MAPI

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content

@Media min-width & max-width

The underlying issue is using max-device-width vs plain old max-width.

Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.

For example:

@media only screen and (max-device-width: 480px) {
    /* STYLES HERE for DEVICES with physical max-screen width of 480px */
}

Versus

@media only screen and (max-width: 480px) {
    /* STYLES HERE for BROWSER WINDOWS with a max-width of 480px. 
       This will work on desktops when the window is narrowed.  */
}

Best way to serialize/unserialize objects in JavaScript?

The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.

var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";

then you can call

eval("(" + person + ")") 

, and you will get back your function in the json object.

std::string to char*

Conversion in OOP style

converter.hpp

class StringConverter {
    public: static char * strToChar(std::string str);
};

converter.cpp

char * StringConverter::strToChar(std::string str)
{
    return (char*)str.c_str();
}

usage

StringConverter::strToChar("converted string")

Create thumbnail image

Here is a version based on the accepted answer. It fixes two problems...

  1. Improper disposing of the images.
  2. Maintaining the aspect ratio of the image.

I found this tool to be fast and effective for both JPG and PNG files.

private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
{
    const int thumbnailSize = 150;
    using (var image = Image.FromFile(imageFileName))
    {
        var imageHeight = image.Height;
        var imageWidth = image.Width;
        if (imageHeight > imageWidth)
        {
            imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
            imageHeight = thumbnailSize;
        }
        else
        {
            imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
            imageWidth = thumbnailSize;
        }

        using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
            //Save off the new thumbnail
            thumb.Save(thumbnailFileName);
    }

    return new FileInfo(thumbnailFileName);
}

Align div right in Bootstrap 3

i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right only push the div to the right, but not the content inside the div.

HTML:

<div class="row">
  <div class="container">
    <div class="col-md-4 someclass">
      left content
    </div>
    <div class="col-md-4 col-md-offset-4 someclass">
      <div class="yellow_background totheright">right content</div>
    </div>
  </div>
</div>

CSS:

.someclass{ /*this class for testing purpose only*/
    border:1px solid blue;
    line-height:2em;
}

.totheright{ /*this will align the text to the right*/
  text-align:right;
}

.yellow_background{
    background-color:yellow;
}

Another modification:

...
<div class="yellow_background totheright">
  <span>right content</span>
  <br/>image also align-right<br/>
  <img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...

hope it will clear your problem

Keylistener in Javascript

JSFIDDLE DEMO

If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 38) { //up key
        alert('up');
    } else if (code === 40) { //down key
        alert('down');
    }
};

How can I detect if this dictionary key exists in C#?

Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

using System;
using System.Collections.Generic;
using System.Collections;

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

How do I get the number of elements in a list?

The len() function can be used with several different types in Python - both built-in types and library types. For example:

>>> len([1, 2, 3])
3

Facebook Architecture

Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like

  1. Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.

  2. Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.

  3. Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.

  4. HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.

If we go into more detail, then answer to this question go longer. We can understand more from following posts:

  1. How Does Facebook Work?
  2. Data Management, Facebook-style
  3. Facebook database design?
  4. Facebook wall's database structure
  5. Facebook "like" data structure

How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

_x000D_
_x000D_
var numArray = [140000, 104, 99];_x000D_
numArray.sort(function(a, b) {_x000D_
  return a - b;_x000D_
});_x000D_
_x000D_
console.log(numArray);
_x000D_
_x000D_
_x000D_

In ES6, you can simplify this with arrow functions:

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort

Documentation:

Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Inf - Inf is NaN, not 0).

Also examples of sorting objects by key.

How do you properly use namespaces in C++?

Note that a namespace in C++ really is just a name space. They don't provide any of the encapsulation that packages do in Java, so you probably won't use them as much.

How do I get the current time zone of MySQL?

To get the current time according to your timezone, you can use the following (in my case its '+5:30')

select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%Y-%m-%d')

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

Reload activity in Android

in some cases it's the best practice in other it's not a good idea it's context driven if you chose to do so using the following is the best way to pass from an activity to her sons :

    Intent i = new Intent(myCurrentActivityName.this,activityIWishToRun.class);    
    startActivityForResult(i, GlobalDataStore.STATIC_INTEGER_VALUE);

the thing is whenever you finish() from activityIWishToRun you return to your a living activity

How to get the cell value by column name not by index in GridView in asp.net

Based on something found on Code Project

Once the data table is declared based on the grid's data source, lookup the column index by column name from the columns collection. At this point, use the index as needed to obtain information from or to format the cell.

protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = (DataTable)((GridView)sender).DataSource;
        int colIndex = dt.Columns["MyColumnName"].Ordinal;

        e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
    }
}

How to use OUTPUT parameter in Stored Procedure

You need to close the connection before you can use the output parameters. Something like this

con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());

Which UUID version to use?

There are two different ways of generating a UUID.

If you just need a unique ID, you want a version 1 or version 4.

  • Version 1: This generates a unique ID based on a network card MAC address and a timer. These IDs are easy to predict (given one, I might be able to guess another one) and can be traced back to your network card. It's not recommended to create these.

  • Version 4: These are generated from random (or pseudo-random) numbers. If you just need to generate a UUID, this is probably what you want.

If you need to always generate the same UUID from a given name, you want a version 3 or version 5.

  • Version 3: This generates a unique ID from an MD5 hash of a namespace and name. If you need backwards compatibility (with another system that generates UUIDs from names), use this.

  • Version 5: This generates a unique ID from an SHA-1 hash of a namespace and name. This is the preferred version.

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

Setting up PostgreSQL ODBC on Windows

Installing psqlODBC on 64bit Windows

Though you can install 32 bit ODBC drivers on Win X64 as usual, you can't configure 32-bit DSNs via ordinary control panel or ODBC datasource administrator.

How to configure 32 bit ODBC drivers on Win x64

Configure ODBC DSN from %SystemRoot%\syswow64\odbcad32.exe

  1. Start > Run
  2. Enter: %SystemRoot%\syswow64\odbcad32.exe
  3. Hit return.
  4. Open up ODBC and select under the System DSN tab.
  5. Select PostgreSQL Unicode

You may have to play with it and try different scenarios, think outside-the-box, remember this is open source.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

There are 2 calls that need to set the correct headers. Initially there is a preflight check so you need something like...

app.get('/item', item.list);
app.options('/item', item.preflight);

and then have the following functions...

exports.list = function (req, res) {
Items.allItems(function (err, items) {
    ...
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(items);
      }
   );
};

and for the pre-flight checks

exports.preflight = function (req, res) {
Items.allItems(function (err, items) {
        res.header('Access-Control-Allow-Origin', "*");     // TODO - Make this more secure!!
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST');
        res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept');
        res.send(200);
    }
  );
};

You can consolidate the res.header() code into a single function if you want.

Also as stated above, be careful of using res.header('Access-Control-Allow-Origin', "*") this means anyone can access your site!

preventDefault() on an <a> tag

You can make use of return false; from the event call to stop the event propagation, it acts like an event.preventDefault(); negating it. Or you can use javascript:void(0) in href attribute to evaluate the given expression and then return undefined to the element.

Returning the event when it's called:

<a href="" onclick="return false;"> ... </a>

Void case:

<a href="javascript:void(0);"> ... </a>

You can see more about in: What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?

How to merge two arrays of objects by ID using lodash?

If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.

var merge = _.merge(arr1, arr2);

Which is the short version of:

var merge = _.chain(arr1).zip(arr2).map(function(item) {
    return _.merge.apply(null, item);
}).value();

Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.

var merge = _.map(arr1, function(item) {
    return _.merge(item, _.find(arr2, { 'member' : item.member }));
});

You can easily convert this to a mixin. See the example below:

_x000D_
_x000D_
_.mixin({_x000D_
  'mergeByKey' : function(arr1, arr2, key) {_x000D_
    var criteria = {};_x000D_
    criteria[key] = null;_x000D_
    return _.map(arr1, function(item) {_x000D_
      criteria[key] = item[key];_x000D_
      return _.merge(item, _.find(arr2, criteria));_x000D_
    });_x000D_
  }_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "name": 'yyyyyyyyyy',_x000D_
  "age": 26_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "name": 'xxxxxx',_x000D_
  "age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Make cross-domain ajax JSONP request with jQuery

Concept explained

Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Summary

Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.

If you have reqested with query string

?callback=my_callback_method

then, your server must response data wrapped like this:

my_callback_method({your json serialized data});

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

I decided that most popular symbols recommended here (? and ?) are looking too bold, so on the site codepoints.net, recommended by user ADJenks, I found these symbols which are looking better for my taste: (U+1F780) (U+1F781) (U+1F782) (U+1F783)

vertical-align image in div

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to the <div> this css:

display:flex;
align-items:center;
justify-content:center;

JSFiddle demo

Live Example:

_x000D_
_x000D_
.img_thumb {_x000D_
    float: left;_x000D_
    height: 120px;_x000D_
    margin-bottom: 5px;_x000D_
    margin-left: 9px;_x000D_
    position: relative;_x000D_
    width: 147px;_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    border-radius: 3px;_x000D_
    display:flex;_x000D_
    align-items:center;_x000D_
    justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
    <a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
       <img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When do I use the PHP constant "PHP_EOL"?

No, PHP_EOL does not handle endline issues, because the system where you use that constant is not the same system where you send the output to.

I would not recommend using PHP_EOL at all. Unix/Linux use \n, MacOS / OS X changed from \r to \n too and on Windows many applications (especially browsers) can display it correctly too. On Windows, it is also easy change existing client-side code to use \n only and still maintain backward-compatibility: Just change the delimiter for line trimming from \r\n to \n and wrap it in a trim() like function.

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

This is the normal behavior and the reason is that your sqlCommandHandlerService.persist method needs a TX when being executed (because it is marked with @Transactional annotation). But when it is called inside processNextRegistrationMessage, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist method, it causes TX to be set to rollBackOnly (even if you catch the exception in the caller and ignore it).

To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.

Update; Read this!

Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.


EDIT Link to current version of the documentation

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

This can be caused when upstream rewrites history.

When this happens, I toss all affected repos, clone them fresh from upstream, and use 'git format-patch' / 'git am' to ferry any work in progress from old world to new.

How to copy folders to docker image from Dockerfile?

Like @Vonc said, there is no possibility to add a command like as of now. The only workaround is to mention the folder, to create it and add contents to it.

# add contents to folder
ADD src $HOME/src

Would create a folder called src in your directory and add contents of your folder src into this.

Open Source Javascript PDF viewer

Well it's not even close to the full spec, but there is a JavaScript and Canvas based PDF viewer out there.

How to change a TextView's style at runtime

Like Jonathan suggested, using textView.setTextTypeface works, I just used it in an app a few seconds ago.

textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.

Which method performs better: .Any() vs .Count() > 0?

If you are using the Entity Framework and have a huge table with many records Any() will be much faster. I remember one time I wanted to check to see if a table was empty and it had millions of rows. It took 20-30 seconds for Count() > 0 to complete. It was instant with Any().

Any() can be a performance enhancement because it may not have to iterate the collection to get the number of things. It just has to hit one of them. Or, for, say, LINQ-to-Entities, the generated SQL will be IF EXISTS(...) rather than SELECT COUNT ... or even SELECT * ....

How to assign colors to categorical variables in ggplot2 that have stable mapping?

For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are not all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.

One way to address this is to create a custom manual colour scale as follows:

#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
        grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)

#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)

and then add the color scale onto the plot as needed:

#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale

#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale

The first plot looks like this:

enter image description here

and the second plot looks like this:

enter image description here

This way you don't need to remember or check each data frame to see that they have the appropriate levels.

What is the purpose of class methods?

When a user logs in on my website, a User() object is instantiated from the username and password.

If I need a user object without the user being there to log in (e.g. an admin user might want to delete another users account, so i need to instantiate that user and call its delete method):

I have class methods to grab the user object.

class User():
    #lots of code
    #...
    # more code

    @classmethod
    def get_by_username(cls, username):
        return cls.query(cls.username == username).get()

    @classmethod
    def get_by_auth_id(cls, auth_id):
        return cls.query(cls.auth_id == auth_id).get()

Auto height of div

As stated earlier by Jamie Dixon, a floated <div> is taken out of normal flow. All content that is still within normal flow will ignore it completely and not make space for it.

Try putting a different colored border border:solid 1px orange; around each of your <div> elements to see what they're doing. You might start by removing the floats and putting some dummy text inside the div. Then style them one at a time to get the desired layout.

Error: request entity too large

After ?o many tries I got my solution

I have commented this line

app.use(bodyParser.json());

and I put

app.use(bodyParser.json({limit: '50mb'}))

Then it works

Why am I getting this redefinition of class error?

If you are having issues with templates or you are calling the class from another .cpp file

try using '#pragma once' in your header file.

How to join entries in a set into one string?

Set's do not have an order - so you may lose your order when you convert your list into a set, i.e.:

>>> orderedVars = ['0', '1', '2', '3']
>>> setVars = set(orderedVars)
>>> print setVars
('4', '2', '3', '1')

Generally the order will remain, but for large sets it almost certainly won't.

Finally, just incase people are wondering, you don't need a ', ' in the join.

Just: ''.join(set)

:)

How to find out the username and password for mysql database

If you forget your password for SQL plus 10g then follow the steps :

  1. START
  2. Type RUN in the search box
  3. Type 'cnc' in the box captioned as OPEN and a black box will appear 4.There will be some text already in the box. (C:\Users\admin>) Just beside that start typing 'sqlplus/nolog' press ENTER key
  4. On the next line type 'conn sys/change_on_install as sysdba' (press ENTER) 6.(in the next line after sql-> type) 'alter user scott account unlock' .
  5. Now open your slpplus and type user name as 'scott' and password as 'tiger'.

If it asks your old password then type the one you have given while installing.

Why is setState in reactjs Async instead of Sync?

You can call a function after the state value has updated:

this.setState({foo: 'bar'}, () => { 
    // Do something here. 
});

Also, if you have lots of states to update at once, group them all within the same setState:

Instead of:

this.setState({foo: "one"}, () => {
    this.setState({bar: "two"});
});

Just do this:

this.setState({
    foo: "one",
    bar: "two"
});

Using the star sign in grep

Try grep -E for extended regular expression support

Also take a look at:

The grep man page

How do you define a class of constants in Java?

Aren't enums best choice for these kinds of stuff?

how to run or install a *.jar file in windows?

Open up a command prompt and type java -jar jbpm-installer-3.2.7.jar

How to escape apostrophe (') in MySql?

The MySQL documentation you cite actually says a little bit more than you mention. It also says,

A “'” inside a string quoted with “'” may be written as “''”.

(Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)

I think the Postgres note on the backslash_quote (string) parameter is informative:

This controls whether a quote mark can be represented by \' in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but PostgreSQL has historically also accepted \'. However, use of \' creates security risks...

That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.

Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

For those of you experiencing this error on Windows using Task Manager end the instance of "mongod.exe" that is running. Once that is done permanently delete the mongo.lock file and run mongod.exe. It should work perfectly after that.

Detect Close windows event by jQuery

Combine the mousemove and window.onbeforeunload event :- I used for set TimeOut for Audit Table.

 $(document).ready(function () {
 var checkCloseX = 0;
        $(document).mousemove(function (e) {
            if (e.pageY <= 5) {
                checkCloseX = 1;
            }
            else { checkCloseX = 0; }
        });

        window.onbeforeunload = function (event) {
            if (event) {
                if (checkCloseX == 1) {

                    //alert('1111');
                    $.ajax({
                        type: "GET",
                        url: "Account/SetAuditHeaderTimeOut",
                        dataType: "json",
                        success: function (result) {
                            if (result != null) {
                            }
                        }
                    });
                }
            }
        };
  });

PHP: How to send HTTP response code?

I just found this question and thought it needs a more comprehensive answer:

As of PHP 5.4 there are three methods to accomplish this:

Assembling the response code on your own (PHP >= 4.0)

The header() function has a special use-case that detects a HTTP response line and lets you replace that with a custom one

header("HTTP/1.1 200 OK");

However, this requires special treatment for (Fast)CGI PHP:

$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi')
    header("Status: 404 Not Found");
else
    header("HTTP/1.1 404 Not Found");

Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.

Note: php_sapi_name() requires PHP 4.0.1

3rd argument to header function (PHP >= 4.3)

There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.

Since 4.3, the header function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:

header(':', true, 404);
header('X-PHP-Response-Code: 404', true, 404);

I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.

http_response_code function (PHP >= 5.4)

The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.

http_response_code(404);

That's all.

Compatibility

Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the "new" http_response_code function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know...

// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
    function http_response_code($newcode = NULL)
    {
        static $code = 200;
        if($newcode !== NULL)
        {
            header('X-PHP-Response-Code: '.$newcode, true, $newcode);
            if(!headers_sent())
                $code = $newcode;
        }       
        return $code;
    }
}

How do I specify different layouts for portrait and landscape orientations?

Create a layout-land directory and put the landscape version of your layout XML file in that directory.

How to display Toast in Android?

If you want to write a simple toast in your activity: Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_SHORT).show();

1.Showing TextView in Toast:---

TextView tv = new TextView(this); tv.setText("Hello!"); tv.setTextSize(30); tv.setTextColor(Color.RED); tv.setBackgroundColor(Color.YELLOW);

2.Showing Image as Toast:--

ImageView iv = new ImageView(this); iv.setImageResource(R.drawable.blonde); Toast t = new Toast(this); t.setView(iv); t.setDuration(Toast.LENGTH_LONG); t.show();

3.showing Layout as Toast:--

LayoutInflater li = getLayoutInflater(); View view = li.inflate(R.layout.my_toast_layout,null,false); Toast t = new Toast(this); t.setView(view); t.setDuration(Toast.LENGTH_LONG); t.show();

** If you want to write the toast in your Async then: private Activity activity; private android.content.Context context; this.activity = activity; this.context = context; Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show();

How to generate an MD5 file hash in JavaScript?

Simplified and minified version (about 3.5k) of this nice implementation http://pajhome.org.uk/crypt/md5/md5.html

will be (stripped utf-8 conversion, upper/lowercase change the array). This is the smallest size I could get, still perfect for embedded web servers.

function md5(d){return rstr2hex(binl2rstr(binl_md5(rstr2binl(d),8*d.length)))}function rstr2hex(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function rstr2binl(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function binl2rstr(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function binl_md5(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}

Remove non-ASCII characters from CSV

sed -i 's/[^[:print:]]//' FILENAME

Also, this acts like dos2unix

remove first element from array and return the array minus the first element

You can use array.slice(0,1) // First index is removed and array is returned.

How to use OpenFileDialog to select a folder?

As a note for future users who would like to avoid using FolderBrowserDialog, Microsoft once released an API called the WindowsAPICodePack that had a helpful dialog called CommonOpenFileDialog, that could be set into a IsFolderPicker mode. The API is available from Microsoft as a NuGet package.

This is all I needed to install and use the CommonOpenFileDialog. (NuGet handled the dependencies)

Install-Package Microsoft.WindowsAPICodePack-Shell

For the include line:

using Microsoft.WindowsAPICodePack.Dialogs;

Usage:

CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
    MessageBox.Show("You selected: " + dialog.FileName);
}

Connecting to local SQL Server database using C#

SqlConnection c = new SqlConnection(@"Data Source=localhost; 
                           Initial Catalog=Northwind; Integrated Security=True");

Add a row number to result set of a SQL query

SELECT
    t.A,
    t.B,
    t.C,
    ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS number
FROM tableZ AS t

See working example at SQLFiddle

Of course, you may want to define the row-numbering order – if so, just swap OVER (ORDER BY (SELECT 1)) for, e.g., OVER (ORDER BY t.C), like in a normal ORDER BY clause.

Single huge .css file vs. multiple smaller specific .css files?

Monolithic stylesheets do offer a lot of benefits (which are described in the other answers), however depending on the overall size of the stylesheet document you could run into problems in IE. IE has a limitation with how many selectors it will read from a single file. The limit is 4096 selectors. If you're monolithic stylesheet will have more than this you will want to split it. This limitation only rears it's ugly head in IE.

This is for all versions of IE.

See Ross Bruniges Blog and MSDN AddRule page.

Reading CSV file and storing values into an array

LINQ way:

var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
          select (from piece in line
                  select piece);

^^Wrong - Edit by Nick

It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.

var csv = from line in lines
          select (line.Split(',')).ToArray();

How can I read large text files in Python, line by line, without loading it into memory?

f=open('filename','r').read()
f1=f.split('\n')
for i in range (len(f1)):
    do_something_with(f1[i])

hope this helps.

How to grep Git commit diffs or contents for a certain word?

You can try the following command:

git log --patch --color=always | less +/searching_string

or using grep in the following way:

git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'

Run this command in the parent directory where you would like to search.

WHERE statement after a UNION in SQL?

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

SELECT * FROM (
    SELECT * FROM Table1 WHERE Field1 = Value1
    UNION
    SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3

Basically, the UNION is looking for two complete SELECT statements to combine, and the WHERE clause is part of the SELECT statement.

It may make more sense to apply the outer WHERE clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.

Create a GUID in Java

The other Answers are correct, especially this one by Stephen C.

Reaching Outside Java

Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.

If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:

  • Command-line utility
    Bundled with nearly every operating system.
    For example, uuidgen found in Mac OS X, BSD, and Linux.
  • Database server
    Use JDBC to retrieve a UUID generated on the database server.
    For example, the uuid-ossp extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations:
    • uuid_generate_v1mc() – generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer.
    • uuid_generate_v5(namespace uuid, name text) – generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method.
  • Web Service
    For example, UUID Generator creates Versions 1 & 3 as well as nil values and GUID.

What is the difference between user and kernel modes in operating systems?

Other answers already explained the difference between user and kernel mode. If you really want to get into detail you should get a copy of Windows Internals, an excellent book written by Mark Russinovich and David Solomon describing the architecture and inside details of the various Windows operating systems.

Find out which remote branch a local branch is tracking

Improving on this answer, I came up with these .gitconfig aliases:

branch-name = "symbolic-ref --short HEAD"
branch-remote-fetch = !"branch=$(git branch-name) && git config branch.\"$branch\".remote || echo origin #"
branch-remote-push  = !"branch=$(git branch-name) && git config branch.\"$branch\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #"
branch-url-fetch = !"remote=$(git branch-remote-fetch) && git remote get-url        \"$remote\" #"  # cognizant of insteadOf
branch-url-push  = !"remote=$(git branch-remote-push ) && git remote get-url --push \"$remote\" #"  # cognizant of pushInsteadOf

What is mutex and semaphore in Java ? What is the main difference?

You compare the incomparable, technically there is no difference between a Semaphore and mutex it doesn't make sense. Mutex is just a significant name like any name in your application logic, it means that you initialize a semaphore at "1", it's used generally to protect a resource or a protected variable to ensure the mutual exclusion.

Getting Excel to refresh data on sheet from within VBA

You might also try

Application.CalculateFull

or

Application.CalculateFullRebuild

if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild rebuilds dependencies as well.)

Check substring exists in a string in C

Use strstr for this.

http://www.cplusplus.com/reference/clibrary/cstring/strstr/

So, you'd write it like..

char *sent = "this is my sample example";
char *word = "sample";

char *pch = strstr(sent, word);

if(pch)
{
    ...
}

Is it possible to save HTML page as PDF using JavaScript or jquery?

There is another very obvious way to convert HTML to PDf using JavaScript: use an online API for that. This will work fine if you don't need to do the conversion when the user is offline.

PdfMage is one option that has a nice API and offers free accounts. I'm sure you can find many alternatives (for example, here)

For PdfMage API you'd have something like this:

 $.ajax({
    url: "https://pdfmage.org/pdf-api/v1/process",
    type: "POST",
    crossDomain: true,
    data: { Html:"<html><body>Hi there!</body></html>" },
    dataType: "json",
    headers: {
        "X-Api-Key": "your-key-here" // not very secure, but a valid option for non-public domains/intranet
    },
    success: function (response) {
        window.location = response.Data.DownloadUrl;
    },
    error: function (xhr, status) {
        alert("error");
    }
});

How to clear input buffer in C?

I encounter a problem trying to implement the solution

while ((c = getchar()) != '\n' && c != EOF) { }

I post a little adjustment 'Code B' for anyone who maybe have the same problem.

The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.

Code A

int y;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   continue;
}
printf("\n%c\n", toupper(y));

and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:

Code B

int y, x;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   x = y;
}
printf("\n%c\n", toupper(x));

The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.

If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.

hope it helps someone

How do you add a Dictionary of items into another Dictionary

Some even more streamlined overloads for Swift 4:

extension Dictionary {
    static func += (lhs: inout [Key:Value], rhs: [Key:Value]) {
        lhs.merge(rhs){$1}
    }
    static func + (lhs: [Key:Value], rhs: [Key:Value]) -> [Key:Value] {
        return lhs.merging(rhs){$1}
    }
}

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

The link below will demonstrate how I accomplished this. Not very hard - just have to use some clever front-end dev!!

<div style="position: fixed; bottom: 0%; top: 0%;">

    <div style="overflow-y: scroll; height: 100%;">

       Menu HTML goes in here

    </div>

</div>

http://jsfiddle.net/RyanBrackett/b44Zn/

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

How can I determine whether a specific file is open in Windows?

The equivalent of lsof -p pid is the combined output from sysinternals handle and listdlls, ie

handle -p pid
listdlls -p pid

you can find out pid with sysinternals pslist.

SDK Manager.exe doesn't work

The way I solved your last problem was by right clicking the android.bat file, and chose edit with notepad++. I then went down to the part of the program where it had this bit of code:

cd /d %~dp0

It was also some other lines of code, but I deleted them. After deleting these other lines I simply just wrote(under the cd /d %~dp0):

cd Program Files

cd java

cd jdk1.7.0_03

cd bin

I dont know here you java.exe file is located but mine was at lest located there.

Java: Simplest way to get last word in a string

Get the last word in Kotlin:

String.substringAfterLast(" ")

How to get week numbers from dates?

If you want to get the week number with the year, Grant Shannon's solution using strftime works, but you need to make some corrections for the dates around january 1st. For instance, 2016-01-03 (yyyy-mm-dd) is week 53 of year 2015, not 2016. And 2018-12-31 is week 1 of 2019, not of 2018. This codes provides some examples and a solution. In column "yearweek" the years are sometimes wrong, in "yearweek2" they are corrected (rows 2 and 5).

library(dplyr)
library(lubridate)

# create a testset
test <- data.frame(matrix(data = c("2015-12-31",
                                   "2016-01-03",
                                   "2016-01-04",
                                   "2018-12-30",
                                   "2018-12-31",
                                   "2019-01-01") , ncol=1, nrow = 6 ))
# add a colname
colnames(test) <- "date_txt"

# this codes provides correct year-week numbers
test <- test %>%
        mutate(date = as.Date(date_txt, format = "%Y-%m-%d")) %>%
        mutate(yearweek = as.integer(strftime(date, format = "%Y%V"))) %>%
        mutate(yearweek2 = ifelse(test = day(date) > 7 & substr(yearweek, 5, 6) == '01',
                                 yes  = yearweek + 100,
                                 no   = ifelse(test = month(date) == 1 & as.integer(substr(yearweek, 5, 6)) > 51,
                                               yes  = yearweek - 100,
                                               no   = yearweek)))
# print the result
print(test)

    date_txt       date yearweek yearweek2
1 2015-12-31 2015-12-31   201553    201553
2 2016-01-03 2016-01-03   201653    201553
3 2016-01-04 2016-01-04   201601    201601
4 2018-12-30 2018-12-30   201852    201852
5 2018-12-31 2018-12-31   201801    201901
6 2019-01-01 2019-01-01   201901    201901

pip or pip3 to install packages for Python 3?

Your pip is a soft link to the same executable file path with pip3. you can use the commands below to check where your pip and pip3 real paths are:

$ ls -l `which pip`
$ ls -l `which pip3`

You may also use the commands below to know more details:

$ pip show pip
$ pip3 show pip

When we install different versions of python, we may create such soft links to

  • set default pip to some version.
  • make different links for different versions.

It is the same situation with python, python2, python3

More information below if you're interested in how it happens in different cases:

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Convert PEM to PPK file format

I'm rather shocked that this has not been answered since the solution is very simple.

As mentioned in previous posts, you would not want to convert it using C#, but just once. This is easy to do with PuTTYGen.

  1. Download your .pem from AWS
  2. Open PuTTYgen
  3. Click "Load" on the right side about 3/4 down
  4. Set the file type to *.*
  5. Browse to, and Open your .pem file
  6. PuTTY will auto-detect everything it needs, and you just need to click "Save private key" and you can save your ppk key for use with PuTTY

Enjoy!

IE8 support for CSS Media Query

Media queries are not supported at all in IE8 and below.


A Javascript based workaround

To add support for IE8, you could use one of several JS solutions. For example, Respond can be added to add media query support for IE8 only with the following code :

<!--[if lt IE 9]>
<script 
   src="respond.min.js">
</script>
<![endif]-->

CSS Mediaqueries is another library that does the same thing. The code for adding that library to your HTML would be identical :

<!--[if lt IE 9]>
<script 
   src="css3-mediaqueries.js">
</script>
<![endif]-->

The alternative

If you don't like a JS based solution, you should also consider adding an IE<9 only stylesheet where you adjust your styling specific to IE<9. For that, you should add the following HTML to your code:

<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" media="all" href="style-ielt9.css"/>
<![endif]-->

Note :

Technically it's one more alternative: using CSS hacks to target IE<9. It has the same impact as an IE<9 only stylesheet, but you don't need a seperate stylesheet for that. I do not recommend this option, though, as they produce invalid CSS code (which is but one of several reasons why the use of CSS hacks is generally frowned upon today).

Unable to merge dex

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        targetSdkVersion 26
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

Regex number between 1 and 100

For integers from 1 to 100 with no preceding 0 try:

^[1-9]$|^[1-9][0-9]$|^(100)$

For integers from 0 to 100 with no preceding 0 try:

^[0-9]$|^[1-9][0-9]$|^(100)$

Regards

In PHP with PDO, how to check the final SQL parametrized query?

So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.

Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database. Only on the database side the full query exists.

Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)

Workaround
This is where I elaborate on Kailash Badu's answer. By logging all SQL queries, we can see what is really run on the server. With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:

log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]

Just do not run this in production!!!

Establish a VPN connection in cmd

I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.

****Note that you probably have to run cmd.exe as an administrator for this to work**

So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run

C:\Windows\System32>cd ras

Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.

So to create our temp file run:

C:\Windows\System32\ras>copy con temp.txt

Now it will let you type the contents of the file, which should look like this:

[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com

So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.

Make a new line and press Ctrl+Z to finish and save.

Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:

C:\Windows\System32\ras>type temp.txt >> rasphone.pbk

This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:

C:\Windows\System32\ras>del temp.txt

Now we can connect to our newly configured VPN server with the following command:

C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword

When we want to disconnect we can run:

C:\Windows\System32\ras>rasdial /DISCONNECT

That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:

Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.

C:\Windows\system32>cd ras

C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
        1 file(s) copied.

C:\Windows\System32\ras>type temp.txt >> rasphone.pbk

C:\Windows\System32\ras>del temp.txt

C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.

C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.

C:\Windows\System32\ras>

Hope this helps.

Log all queries in mysql

Top answer doesn't work in mysql 5.6+. Use this instead:

[mysqld]
general_log = on
general_log_file=/usr/log/general.log

in your my.cnf / my.ini file

Ubuntu/Debian: /etc/mysql/my.cnf
Windows: c:\ProgramData\MySQL\MySQL Server 5.x
wamp: c:\wamp\bin\mysql\mysqlx.y.z\my.ini
xampp: c:\xampp\mysql\bin\my.ini.

Increment a database field by 1

This is more a footnote to a number of the answers above which suggest the use of ON DUPLICATE KEY UPDATE, BEWARE that this is NOT always replication safe, so if you ever plan on growing beyond a single server, you'll want to avoid this and use two queries, one to verify the existence, and then a second to either UPDATE when a row exists, or INSERT when it does not.

How to pass a user / password in ansible command

As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.

read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"

How to show a confirm message before delete?

improving on user1697128 (because I cant yet comment on it)

<script>
    function ConfirmDelete()
    {
      var x = confirm("Are you sure you want to delete?");
      if (x)
          return true;
      else
        return false;
    }
</script>    

<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>

will cancel form submission if cancel is pressed

Convert Rows to columns using 'Pivot' in SQL Server

select * from (select name, ID from Empoyee) Visits
    pivot(sum(ID) for name
    in ([Emp1],
    [Emp2],
    [Emp3]
    ) ) as pivottable;

Provide static IP to docker containers via docker-compose

I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as

KAPACITOR_BASE_URL:  http://kapacitor:9092

In above http://[**kapacitor**]:9092 would not resolve to http://172.20.0.2:9092

I resolved the static IPs issues using subnetting configurations.

version: "3.3"

networks:
  frontend:
    ipam:
      config:
        - subnet: 172.20.0.0/24
services:
    db:
        image: postgres:9.4.4
        networks:
            frontend:
                ipv4_address: 172.20.0.5
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data

    redis:
        image: redis:latest
        networks:
            frontend:
                ipv4_address: 172.20.0.6
        ports:
            - "6379"

    influxdb:
        image: influxdb:latest
        ports:
            - "8086:8086"
            - "8083:8083"
        volumes:
            - ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
            - ../influxdb/inxdb:/var/lib/influxdb
        networks:
            frontend:
                ipv4_address: 172.20.0.4
        environment:
          INFLUXDB_HTTP_AUTH_ENABLED: "false"
          INFLUXDB_ADMIN_ENABLED: "true"
          INFLUXDB_USERNAME: "db_username"
          INFLUXDB_PASSWORD: "12345678"
          INFLUXDB_DB: db_customers

    kapacitor:
        image: kapacitor:latest
        ports: 
            - "9092:9092"
        networks:
            frontend:
                ipv4_address: 172.20.0.2
        depends_on:
            - influxdb
        volumes:
            - ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
            - ../kapacitor/kapdb:/var/lib/kapacitor
        environment:
          KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086

    web:
        build: .
        environment:
          RAILS_ENV: $RAILS_ENV
        command: bundle exec rails s -b 0.0.0.0
        ports:
            - "3000:3000"
        networks:
            frontend:
                ipv4_address: 172.20.0.3
        links:
            - db
            - kapacitor
        depends_on:
            - db
        volumes:
            - .:/var/app/current
        environment:
          DATABASE_URL: postgres://postgres@db
          DATABASE_USERNAME: postgres
          DATABASE_PASSWORD: postgres
          INFLUX_URL: http://influxdb:8086
          INFLUX_USER: db_username
          INFLUX_PWD: 12345678
          KAPACITOR_BASE_URL:  http://172.20.0.2:9092
          KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000

volumes:
  postgres_data:

How to scroll to an element?

The nicest way is to use element.scrollIntoView({ behavior: 'smooth' }). This scrolls the element into view with a nice animation.

When you combine it with React's useRef(), it can be done the following way.

import React, { useRef } from 'react'

const Article = () => {
  const titleRef = useRef()

  function handleBackClick() {
      titleRef.current.scrollIntoView({ behavior: 'smooth' })
  }

  return (
      <article>
            <h1 ref={titleRef}>
                A React article for Latin readers
            </h1>

            // Rest of the article's content...

            <button onClick={handleBackClick}>
                Back to the top
            </button>
        </article>
    )
}

When you would like to scroll to a React component, you need to forward the ref to the rendered element. This article will dive deeper into the problem.

Handling Dialogs in WPF with MVVM

I really struggled with this concept for a while when learning (still learning) MVVM. What I decided, and what I think others already decided but which wasn't clear to me is this:

My original thought was that a ViewModel should not be allowed to call a dialog box directly as it has no business deciding how a dialog should appear. Beacause of this I started thinking about how I could pass messages much like I would have in MVP (i.e. View.ShowSaveFileDialog()). However, I think this is the wrong approach.

It is OK for a ViewModel to call a dialog directly. However, when you are testing a ViewModel , that means that the dialog will either pop up during your test, or fail all together (never really tried this).

So, what needs to happen is while testing is to use a "test" version of your dialog. This means that for ever dialog you have, you need to create an Interface and either mock out the dialog response or create a testing mock that will have a default behaviour.

You should already be using some sort of Service Locator or IoC that you can configure to provide you the correct version depending on the context.

Using this approach, your ViewModel is still testable and depending on how you mock out your dialogs, you can control the behaviour.

Hope this helps.

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

Check if a String is in an ArrayList of Strings

The List interface already has this solved.

int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;

More can be found in the documentation about List.

How to select records without duplicate on just one field in SQL?

Having Clause is the easiest way to find duplicate entry in Oracle and using rowid we can remove duplicate data..

DELETE FROM products WHERE rowid IN (
  SELECT MAX(sl) FROM (
  SELECT itemcode, (rowid) sl FROM products WHERE itemcode IN (
  SELECT itemcode FROM products GROUP BY itemcode HAVING COUNT(itemcode)>1
)) GROUP BY itemcode);

Determine the type of an object?

There are two built-in functions that help you identify the type of an object. You can use type() if you need the exact type of an object, and isinstance() to check an object’s type against something. Usually, you want to use isinstance() most of the times since it is very robust and also supports type inheritance.


To get the actual type of an object, you use the built-in type() function. Passing an object as the only parameter will return the type object of that object:

>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True

This of course also works for custom types:

>>> class Test1 (object):
        pass
>>> class Test2 (Test1):
        pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True

Note that type() will only return the immediate type of the object, but won’t be able to tell you about type inheritance.

>>> type(b) is Test1
False

To cover that, you should use the isinstance function. This of course also works for built-in types:

>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True

isinstance() is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance() is preferred over type().

The second parameter of isinstance() also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance will then return true, if the object is of any of those types:

>>> isinstance([], (tuple, list, set))
True

ansible: lineinfile for several lines?

If you need to configure a set of unique property=value lines, I recommend a more concise loop. For example:

- name: Configure kernel parameters
  lineinfile:
    dest: /etc/sysctl.conf
    regexp: "^{{ item.property | regex_escape() }}="
    line: "{{ item.property }}={{ item.value }}"
  with_items:
    - { property: 'kernel.shmall', value: '2097152' }
    - { property: 'kernel.shmmax', value: '134217728' }
    - { property: 'fs.file-max', value: '65536' }

Using a dict as suggested by Alix Axel and adding automatic removing of matching commented out entries,

- name: Configure IPV4 Forwarding
  lineinfile:
    path: /etc/sysctl.conf
    regexp: "^#? *{{ item.key | regex_escape() }}="
    line: "{{ item.key }}={{ item.value }}"
  with_dict:
    'net.ipv4.ip_forward': 1

XPath test if node value is number

You could always use something like this:

string(//Sesscode) castable as xs:decimal

castable is documented by W3C here.

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

I tried some of your solutions. This one :

margin: 0px -100%;
padding: 0 100%;

is by far the best, since we don't need extra css for smaller screen. I made a codePen to show the results : I used a parent div with a background image, and a child divon div with inner content.

https://codepen.io/yuyazz/pen/BaoqBBq

Understanding .get() method in Python

Start here http://docs.python.org/tutorial/datastructures.html#dictionaries

Then here http://docs.python.org/library/stdtypes.html#mapping-types-dict

Then here http://docs.python.org/library/stdtypes.html#dict.get

characters.get( key, default )

key is a character

default is 0

If the character is in the dictionary, characters, you get the dictionary object.

If not, you get 0.


Syntax:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Installing R with Homebrew

As of 2017, it's just brew install r. See @Andrew's answer below.

As of 2014 (using an Yosemite), the method is the following:

brew tap homebrew/science
brew install Caskroom/cask/xquartz
brew install r

The gcc package (will be installed automatically as a required dependency) in the homebrew/science tap already contains the latest fortran compiler (gfortran), and most of all: the whole package is precompiled so it saves you a lot of compilation time.

This answer will also work for El Capitan and Mac OS Sierra.

In case you don't have XCode Command Line Tools (CLT), run from terminal:

xcode-select --install

How do I prevent DIV tag starting a new line?

The div tag is a block element, causing that behavior.

You should use a span element instead, which is inline.

If you really want to use div, add style="display: inline". (You can also put that in a CSS rule)

Multiline editing in Visual Studio Code

On Windows, you hold Ctrl+Alt while pressing the up ? or down ? arrow keys to add cursors.

Mac: ? Opt+? Cmd+?/?

Linux: Shift+Alt+?/?

Note that third-party software may interfere with these shortcuts, preventing them from working as intended (particularly Intel's HD Graphics software on Windows; see comments for more details).

If you experience this issue, you can either disable the Intel/other software hotkeys, or modify the VS Code shortcuts (described below).

Press Esc to reset to a single cursor.

Multiline cursors in Visual Studio Code

Or, as Isidor Nikolic points out, you can hold Alt and left click to place cursors arbitrarily.

Arbitrarily placed multiline cursors in Visual Studio Code

You can view and edit keyboard shortcuts via:

File ? Preferences ? Keyboard Shortcuts

Documentation:

https://code.visualstudio.com/docs/customization/keybindings

Official VS Code Keyboard shortcut cheat sheets:

https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf
https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf
https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf

Adding external library in Android studio

Turn any github project into a single line gradle implementation with this website

https://jitpack.io/

Example, I needed this project: https://github.com/mik3y/usb-serial-for-android

All I did was paste this into my gradle file:

implementation 'com.github.mik3y:usb-serial-for-android:master-SNAPSHOT'

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

Two main reasons:

1) mysql-server isn't installed! You have to install it (mysql-server and not mysql-client) and run it.

2) It's installed by default and running. So, it's not possible to run it again through Xampp or Lampp. You have to stop it: sudo service mysql stop

then you can start it through Xampp. It's possible to check if it's running or not with this code: sudo netstat -tap | grep mysql

If you see a result like this: tcp 0 0 localhost:mysql : LISTEN 1043/mysqld

It means that it's running properly.

CSS Classes & SubClasses

Just put a space between .area1 and .item, e.g:

.area1 .item
{
    color:red;
}

this style applies to elements with class item inside an element with class area1.

I can't install python-ldap

To correct the error due to dependencies to install the python-ldap : Windows 7/10

download the whl file

http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap.

python 3.6 suit with

python_ldap-3.2.0-cp36-cp36m-win_amd64.whl

Deploy the file in :

c:\python36\Scripts\

install it with

python -m pip install python_ldap-3.2.0-cp36-cp36m-win_amd64.whl

Javascript: set label text

InnerHTML should be innerHTML:

document.getElementById('LblAboutMeCount').innerHTML = charsleft;

You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:

$(document).ready(function() {
    $('textarea[name=text]').keypress(function(e) {
        checkLength($(this),512,$('#LblTextCount'));
    }).focus(function() {
        checkLength($(this),512,$('#LblTextCount'));
    });
});

You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:

function checkLength(obj, maxlength, label) {
    charsleft = (maxlength - obj.val().length);
    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        obj.val(obj.val().substring(0, maxlength-1));
    }
    // I'm trying to set the value of charsleft into the label
    label.text(charsleft);
    $('#LblAboutMeCount').html(charsleft);
}

So if you apply the above, you can change your markup to:

<textarea name="text"></textarea>

GROUP BY having MAX date

There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.

Convert Text to Uppercase while typing in Text box

There is a specific property for this. It is called CharacterCasing and you could set it to Upper

  TextBox1.CharacterCasing = CharacterCasing.Upper;

In ASP.NET you could try to add this to your textbox style

  style="text-transform:uppercase;"

You could find an example here: http://www.w3schools.com/cssref/pr_text_text-transform.asp

Jaxb, Class has two properties of the same name

It will work when you put your annotation before the getters, and remove it from the protected attributes:

protected String codingScheme;

@XmlAttribute(name = "codingScheme")
public String getCodingScheme() {
    return this.codingScheme;
}

Hiding the R code in Rmarkdown/knit and just showing the results

Might also be interesting for you to know that you can use:

{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)

to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)

replacing text in a file with Python

Faster way of writing it would be...

in = open('path/to/input/file').read()
out = open('path/to/input/file', 'w')
replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for i in replacements.keys():
    in = in.replace(i, replacements[i])
out.write(in)
out.close

This eliminated a lot of the iterations that the other answers suggest, and will speed up the process for longer files.

How to confirm RedHat Enterprise Linux version?

That's the RHEL release version.

You can see the kernel version by typing uname -r. It'll be 2.6.something.

How to find path of active app.config file?

Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration) support. In addition to the machine config: app.exe.config, user roaming, and user local.

To get the "global" configuration (exe.config):

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                    .FilePath

Use different ConfigurationUserLevel values for per-use roaming and non-roaming configuration files.


1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config can (depending on the setting) add to or override the parent's web.config.

How to extract the hostname portion of a URL in JavaScript

You could concatenate the location protocol and the host:

var root = location.protocol + '//' + location.host;

For a url, let say 'http://stackoverflow.com/questions', it will return 'http://stackoverflow.com'

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:

SELECT 
    name, author_id, count(*), t.total
FROM
    names as n1
    INNER JOIN LATERAL (
        SELECT 
            count(*) as total
        FROM 
            names as n2
        WHERE 
            n2.id = n1.id
            AND n2.author_id = n1.author_id
    ) as t ON 1=1
GROUP BY 
    n1.name, n1.author_id

How to call one shell script from another shell script?

Check this out.

#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."

Opening PDF String in new window with javascript

var byteCharacters = atob(response.data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
  byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var file = new Blob([byteArray], { type: 'application/pdf;base64' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);

You return a base64 string from the API or another source. You can also download it.

How To Save Canvas As An Image With canvas.toDataURL()?

You can try this; create a dummy HTML anchor, and download the image from there like...

// Convert canvas to image
document.getElementById('btn-download').addEventListener("click", function(e) {
    var canvas = document.querySelector('#my-canvas');

    var dataURL = canvas.toDataURL("image/jpeg", 1.0);

    downloadImage(dataURL, 'my-canvas.jpeg');
});

// Save | Download image
function downloadImage(data, filename = 'untitled.jpeg') {
    var a = document.createElement('a');
    a.href = data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}

Pretty-Printing JSON with PHP

I had the same issue.

Anyway I just used the json formatting code here:

http://recursive-design.com/blog/2008/03/11/format-json-with-php/

Works well for what I needed it for.

And a more maintained version: https://github.com/GerHobbelt/nicejson-php

SQL Server CASE .. WHEN .. IN statement

CASE AlarmEventTransactions.DeviceID should just be CASE.

You are mixing the 2 forms of the CASE expression.

How can I set the focus (and display the keyboard) on my EditText programmatically

use:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

How to add new column to MYSQL table?

Something like:

$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
    echo "It worked";
}

Haven't tested it but should work.

Measuring execution time of a function in C++

In Scott Meyers book I found an example of universal generic lambda expression that can be used to measure function execution time. (C++14)

auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = std::chrono::high_resolution_clock::now();
        // function invocation using perfect forwarding
        std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
        // get time after function invocation
        const auto& stop = std::chrono::high_resolution_clock::now();
        return stop - start;
     };

The problem is that you are measure only one execution so the results can be very differ. To get a reliable result you should measure a large number of execution. According to Andrei Alexandrescu lecture at code::dive 2015 conference - Writing Fast Code I:

Measured time: tm = t + tq + tn + to

where:

tm - measured (observed) time

t - the actual time of interest

tq - time added by quantization noise

tn - time added by various sources of noise

to - overhead time (measuring, looping, calling functions)

According to what he said later in the lecture, you should take a minimum of this large number of execution as your result. I encourage you to look at the lecture in which he explains why.

Also there is a very good library from google - https://github.com/google/benchmark. This library is very simple to use and powerful. You can checkout some lectures of Chandler Carruth on youtube where he is using this library in practice. For example CppCon 2017: Chandler Carruth “Going Nowhere Faster”;

Example usage:

#include <iostream>
#include <chrono>
#include <vector>
auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = high_resolution_clock::now();
        // function invocation using perfect forwarding
        for(auto i = 0; i < 100000/*largeNumber*/; ++i) {
            std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
        }
        // get time after function invocation
        const auto& stop = high_resolution_clock::now();
        return (stop - start)/100000/*largeNumber*/;
     };

void f(std::vector<int>& vec) {
    vec.push_back(1);
}

void f2(std::vector<int>& vec) {
    vec.emplace_back(1);
}
int main()
{
    std::vector<int> vec;
    std::vector<int> vec2;
    std::cout << timeFuncInvocation(f, vec).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec2).count() << std::endl;
    std::vector<int> vec3;
    vec3.reserve(100000);
    std::vector<int> vec4;
    vec4.reserve(100000);
    std::cout << timeFuncInvocation(f, vec3).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec4).count() << std::endl;
    return 0;
}

EDIT: Ofcourse you always need to remember that your compiler can optimize something out or not. Tools like perf can be useful in such cases.

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

This is considered as features in Gitlab.

Maintainer / Owner access is never able to force push again for default & protected branch, as stated in this docs enter image description here

Different class for the last element in ng-repeat

It's easier and cleaner to do it with CSS.

HTML:

<div ng-repeat="file in files" class="file">
  {{ file.name }}
</div>

CSS:

.file:last-of-type {
    color: #800;
}

The :last-of-type selector is currently supported by 98% of browsers

Convert Python ElementTree to string

If you just need this for debugging to see how the XML looks like, then instead of print(xml.etree.ElementTree.tostring(e)) you can use dump like this:

xml.etree.ElementTree.dump(e)

And this works both with Element and ElementTree objects as e, so there should be no need for getroot.

The documentation of dump says:

xml.etree.ElementTree.dump(elem)

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.

elem is an element tree or an individual element.

Changed in version 3.8: The dump() function now preserves the attribute order specified by the user.

"ImportError: no module named 'requests'" after installing with pip

One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.

Type python in the prompt, and press the tab key to see what versions of Python in your environment.

How to split a delimited string into an array in awk?

I do not like the echo "..." | awk ... solution as it calls unnecessary fork and execsystem calls.

I prefer a Dimitre's solution with a little twist

awk -F\| '{print $3 $2 $1}' <<<'12|23|11'

Or a bit shorter version:

awk -F\| '$0=$3 $2 $1' <<<'12|23|11'

In this case the output record put together which is a true condition, so it gets printed.

In this specific case the stdin redirection can be spared with setting an internal variable:

awk -v T='12|23|11' 'BEGIN{split(T,a,"|");print a[3] a[2] a[1]}'

I used quite a while, but in this could be managed by internal string manipulation. In the first case the original string is split by internal terminator. In the second case it is assumed that the string always contains digit pairs separated by a one character separator.

T='12|23|11';echo -n ${T##*|};T=${T%|*};echo ${T#*|}${T%|*}
T='12|23|11';echo ${T:6}${T:3:2}${T:0:2}

The result in all cases is

112312

Converting between strings and ArrayBuffers

After playing with mangini's solution for converting from ArrayBuffer to String - ab2str (which is the most elegant and useful one I have found - thanks!), I had some issues when handling large arrays. More specefivally, calling String.fromCharCode.apply(null, new Uint16Array(buf)); throws an error:

arguments array passed to Function.prototype.apply is too large.

In order to solve it (bypass) I have decided to handle the input ArrayBuffer in chunks. So the modified solution is:

function ab2str(buf) {
   var str = "";
   var ab = new Uint16Array(buf);
   var abLen = ab.length;
   var CHUNK_SIZE = Math.pow(2, 16);
   var offset, len, subab;
   for (offset = 0; offset < abLen; offset += CHUNK_SIZE) {
      len = Math.min(CHUNK_SIZE, abLen-offset);
      subab = ab.subarray(offset, offset+len);
      str += String.fromCharCode.apply(null, subab);
   }
   return str;
}

The chunk size is set to 2^16 because this was the size I have found to work in my development landscape. Setting a higher value caused the same error to reoccur. It can be altered by setting the CHUNK_SIZE variable to a different value. It is important to have an even number.

Note on performance - I did not make any performance tests for this solution. However, since it is based on the previous solution, and can handle large arrays, I see no reason why not to use it.

UTF-8 output from PowerShell

This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

Caching example:

102 [C:\Users\leeholm]
>> $r1 = [Console]::Out

103 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US



104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

105 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

I'd like to add one important aspect to other answers, which actually explained this topic to me in the best way:

If 2 joined tables contain M and N rows, then cross join will always produce (M x N) rows, but full outer join will produce from MAX(M,N) to (M + N) rows (depending on how many rows actually match "on" predicate).

EDIT:

From logical query processing perspective, CROSS JOIN does indeed always produce M x N rows. What happens with FULL OUTER JOIN is that both left and right tables are "preserved", as if both LEFT and RIGHT join happened. So rows, not satisfying ON predicate, from both left and right tables are added to the result set.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I had this problem with a fresh install of wamp and using only default settings without setting any passwords. I found an incorrect default setting and I solved it by the following steps:

  1. Go to C:\wamp\apps\phpmyadmin4.1.14 (Your phpmyadmin version# may differ)
  2. open the file config.inc in a text editor
  3. find the line: $cfg['Servers'][$i]['host'] = '127.0.0.1';
  4. change it to $cfg['Servers'][$i]['host'] = 'localhost';
  5. save the file
  6. restart all services in wamp

The problem seems to be that someone forgot to make the server and host match in the configuration files.

Check if a column contains text using SQL

Leaving database modeling issues aside. I think you can try

SELECT * FROM STUDENTS WHERE ISNUMERIC(STUDENTID) = 0

But ISNUMERIC returns 1 for any value that seems numeric including things like -1.0e5

If you want to exclude digit-only studentids, try something like

SELECT * FROM STUDENTS WHERE STUDENTID LIKE '%[^0-9]%'

Group array items using object

You can do something like this:

function convert(items) {
    var result = [];

    items.forEach(function (element) {
        var existingElement = result.filter(function (item) {
            return item.group === element.group;
        })[0];

        if (existingElement) {
            existingElement.color.push(element.color);
        } else {
            element.color = [element.color];
            result.push(element);
        }

    });

    return result;
}

String array initialization in Java

You mean like:

String names[] = {"Ankit","Bohra","Xyz"};

But you can only do this in the same statement when you declare it

Jquery, set value of td in a table?

From:

it could be:

.html()

In an HTML document, .html() can be used to get the contents of any element.

.text()

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements.

.val()

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

Int to Decimal Conversion - Insert decimal point at specified location

int i = 7122960;
decimal d = (decimal)i / 100;

Getting absolute URLs using ASP.NET Core

You don't need to create an extension method for this

@Url.Action("Action", "Controller", values: null);

  • Action - Name of the action
  • Controller - Name of the controller
  • values - Object containing route values: aka GET parameters

There are also lots of other overloads to Url.Action you can use to generate links.

Angular 4 setting selected option in Dropdown

Remove [selected] from option tag:

<option *ngFor="let opt of question.options" [value]="opt.key">
  {{opt.selected+opt.value}}
</option>

And in your form builder add:

key: this.question.options.filter(val => val.selected === true).map(data => data.key)

How to define Singleton in TypeScript

You can also make use of the function Object.Freeze(). Its simple and easy:

class Singleton {

  instance: any = null;
  data: any = {} // store data in here

  constructor() {
    if (!this.instance) {
      this.instance = this;
    }
    return this.instance
  }
}

const singleton: Singleton = new Singleton();
Object.freeze(singleton);

export default singleton;

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

ReactJS - How to use comments?

Besides the other answers, it's also possible to use single line comments just before and after the JSX begines or ends. Here is a complete summary:

Valid

(
  // this is a valid comment
  <div>
    ...
  </div>
  // this is also a valid comment
  /* this is also valid */
)

If we were to use comments inside the JSX rendering logic:

(
  <div>
    {/* <h1>Valid comment</h1> */}
  </div>
)

When declaring props single line comments can be used:

(
  <div
    className="content" /* valid comment */
    onClick={() => {}} // valid comment
  >
    ...
  </div>
)

Invalid

When using single line or multiline comments inside the JSX without wrapping them in { }, the comment will be rendered to the UI:

(
  <div>
    // invalid comment, renders in the UI
  </div>
)

Subtract two variables in Bash

Alternatively to the suggested 3 methods you can try let which carries out arithmetic operations on variables as follows:

let COUNT=$FIRSTV-$SECONDV

or

let COUNT=FIRSTV-SECONDV

Oracle SQL - DATE greater than statement

As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'

If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                           'NLS_DATE_LANGUAGE = American');