Programs & Examples On #Uniobjects

UniObjects refers to a family of database access API's from Rocket Software, enabling the .NET or Java developer native access to UniVerse and UniData data and functionality from within their IDE of choice.

Add 'x' number of hours to date

I use following function to convert normal date-time value to mysql datetime format.

private function ampmtosql($ampmdate) {
            if($ampmdate == '')
                return '';
            $ampm = substr(trim(($ampmdate)), -2);
            $datetimesql = substr(trim(($ampmdate)), 0, -3);
            if ($ampm == 'pm') {
                $hours = substr(trim($datetimesql), -5, 2);
                if($hours != '12')
                    $datetimesql = date('Y-m-d H:i',strtotime('+12 hour',strtotime($datetimesql)));
            }
            elseif ($ampm == 'am') {
                $hours = substr(trim($datetimesql), -5, 2);
                if($hours == '12')
                    $datetimesql = date('Y-m-d H:i',strtotime('-12 hour',strtotime($datetimesql)));
            }
            return $datetimesql;
        }

It converts datetime values like,

2015-06-04 09:55 AM -> 2015-06-04 09:55
2015-06-04 03:55 PM -> 2015-06-04 15:55
2015-06-04 12:30 AM -> 2015-06-04 00:55

Hope this will help someone.

How to split a string by spaces in a Windows batch file?

Here is a solution based on a "function" which processes each character until it finds the delimiter character.

It is relatively slow, but it is at least not a brain teaser (except for the function part).

:: Example #1:
set data=aa bb cc
echo Splitting off from "%data%":
call :split_once "%data%" " " "left" "right"
echo Split off: %left%
echo Remaining: %right%
echo.

:: Example #2:
echo List of paths in PATH env var:
set paths=%PATH%
:loop
    call :split_once "%paths%" ";" "left" "paths"
    if "%left%" equ "" goto loop_end
    echo %left%
goto loop
:loop_end



:: HERE BE FUNCTIONS
goto :eof

:: USAGE:
::   call :split_once "string to split once" "delimiter_char" "left_var" "right_var"
:split_once
    setlocal
    set right=%~1
    set delimiter_char=%~2
    set left=

    if "%right%" equ "" goto split_once_done

    :split_once_loop
        if "%right:~0,1%" equ "%delimiter_char%" set right=%right:~1%&& goto split_once_done
        if "%right:~0,1%" neq "%delimiter_char%" set left=%left%%right:~0,1%
        if "%right:~0,1%" neq "%delimiter_char%" set right=%right:~1%
        if "%right%" equ "" goto split_once_done
    goto split_once_loop

    :split_once_done
    endlocal & set %~3=%left%& set %~4=%right%
goto:eof

how can I connect to a remote mongo server from Mac OS terminal

Another way to do this is:

mongo mongodb://mongoDbIPorDomain:port

How to add onload event to a div element

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.

Java, Calculate the number of days between two dates

This function is good for me:

public static int getDaysCount(Date begin, Date end) {
    Calendar start = org.apache.commons.lang.time.DateUtils.toCalendar(begin);
    start.set(Calendar.MILLISECOND, 0);
    start.set(Calendar.SECOND, 0);
    start.set(Calendar.MINUTE, 0);
    start.set(Calendar.HOUR_OF_DAY, 0);

    Calendar finish = org.apache.commons.lang.time.DateUtils.toCalendar(end);
    finish.set(Calendar.MILLISECOND, 999);
    finish.set(Calendar.SECOND, 59);
    finish.set(Calendar.MINUTE, 59);
    finish.set(Calendar.HOUR_OF_DAY, 23);

    long delta = finish.getTimeInMillis() - start.getTimeInMillis();
    return (int) Math.ceil(delta / (1000.0 * 60 * 60 * 24));
}

OTP (token) should be automatically read from the message

I will recommend you not to use any third party libraries for auto fetch OTP from SMS Inbox. This can be done easily if you have basic understanding of Broadcast Receiver and how it works. Just Try following approach :

Step 1) Create single interface i.e SmsListner

package com.wnrcorp.reba;
public interface SmsListener{
public void messageReceived(String messageText);}

Step 2) Create single Broadcast Receiver i.e SmsReceiver

package com.wnrcorp.reba;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
private static SmsListener mListener;
Boolean b;
String abcd,xyz;
@Override
public void onReceive(Context context, Intent intent) {
Bundle data  = intent.getExtras();
Object[] pdus = (Object[]) data.get("pdus");
    for(int i=0;i<pdus.length;i++){
        SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
        String sender = smsMessage.getDisplayOriginatingAddress();
       // b=sender.endsWith("WNRCRP");  //Just to fetch otp sent from WNRCRP
        String messageBody = smsMessage.getMessageBody();
       abcd=messageBody.replaceAll("[^0-9]","");   // here abcd contains otp 
        which is in number format
        //Pass on the text to our listener.
        if(b==true) {
            mListener.messageReceived(abcd);  // attach value to interface 
  object
        }
        else
        {
        }
    }
}
public static void bindListener(SmsListener listener) {
    mListener = listener;
}
}

Step 3) Add Listener i.e broadcast receiver in android manifest file

<receiver android:name=".SmsReceiver">    
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
</receiver>

and add permission

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

Final Step 4) The activity where you going to auto fetch otp when it is received in inbox. In my case I'm fetching otp and setting on edittext field.

public class OtpVerificationActivity extends AppCompatActivity {
EditText ed;
TextView tv;
String otp_generated,contactNo,id1;
GlobalData gd = new GlobalData();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_otp_verification);
    ed=(EditText)findViewById(R.id.otp);
    tv=(TextView) findViewById(R.id.verify_otp); 
    /*This is important because this will be called every time you receive 
     any sms */            
 SmsReceiver.bindListener(new SmsListener() {
        @Override
        public void messageReceived(String messageText) {
            ed.setText(messageText);     
        }
    });
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try
            {
                InputMethodManager imm=
  (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);                    
  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
            }
            catch(Exception e)
            {}           
            if (ed.getText().toString().equals(otp_generated))
            {
                Toast.makeText(OtpVerificationActivity.this, "OTP Verified 
       Successfully !", Toast.LENGTH_SHORT).show();           
             }
    });
   }
}

Layout File for OtpVerificationActivity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_otp_verification"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wnrcorp.reba.OtpVerificationActivity">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/firstcard"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    card_view:cardCornerRadius="10dp"
    >
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@android:color/white">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OTP Confirmation"
            android:textSize="18sp"
            android:textStyle="bold"
            android:id="@+id/dialogTitle"
            android:layout_margin="5dp"
            android:layout_gravity="center"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/otp"
            android:layout_margin="5dp"
            android:hint="OTP Here"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Verify"
            android:textSize="18sp"
            android:id="@+id/verify_otp"
            android:gravity="center"
            android:padding="10dp"
            android:layout_gravity="center"
            android:visibility="visible"
            android:layout_margin="5dp"
            android:background="@color/colorPrimary"
            android:textColor="#ffffff"
            />
        </LinearLayout>
        </android.support.v7.widget.CardView>
        </RelativeLayout>

Screenshots for OTP Verification Activity where you fetch OTP as soons as messages received enter image description here

When to use an interface instead of an abstract class and vice versa?

Personally, I almost never have the need to write abstract classes.

Most times I see abstract classes being (mis)used, it's because the author of the abstract class is using the "Template method" pattern.

The problem with "Template method" is that it's nearly always somewhat re-entrant - the "derived" class knows about not just the "abstract" method of its base class that it is implementing, but also about the public methods of the base class, even though most times it does not need to call them.

(Overly simplified) example:

abstract class QuickSorter
{
    public void Sort(object[] items)
    {
        // implementation code that somewhere along the way calls:
        bool less = compare(x,y);
        // ... more implementation code
    }
    abstract bool compare(object lhs, object rhs);
}

So here, the author of this class has written a generic algorithm and intends for people to use it by "specializing" it by providing their own "hooks" - in this case, a "compare" method.

So the intended usage is something like this:

class NameSorter : QuickSorter
{
    public bool compare(object lhs, object rhs)
    {
        // etc.
    }
}

The problem with this is that you've unduly coupled together two concepts:

  1. A way of comparing two items (what item should go first)
  2. A method of sorting items (i.e. quicksort vs merge sort etc.)

In the above code, theoretically, the author of the "compare" method can re-entrantly call back into the superclass "Sort" method... even though in practise they will never want or need to do this.

The price you pay for this unneeded coupling is that it's hard to change the superclass, and in most OO languages, impossible to change it at runtime.

The alternative method is to use the "Strategy" design pattern instead:

interface IComparator
{
    bool compare(object lhs, object rhs);
}

class QuickSorter
{
    private readonly IComparator comparator;
    public QuickSorter(IComparator comparator)
    {
        this.comparator = comparator;
    }

    public void Sort(object[] items)
    {
        // usual code but call comparator.Compare();
    }
}

class NameComparator : IComparator
{
    bool compare(object lhs, object rhs)
    {
        // same code as before;
    }
}

So notice now: All we have are interfaces, and concrete implementations of those interfaces. In practise, you don't really need anything else to do a high level OO design.

To "hide" the fact that we've implemented "sorting of names" by using a "QuickSort" class and a "NameComparator", we might still write a factory method somewhere:

ISorter CreateNameSorter()
{
    return new QuickSorter(new NameComparator());
}

Any time you have an abstract class you can do this... even when there is a natural re-entrant relationship between the base and derived class, it usually pays to make them explicit.

One final thought: All we've done above is "compose" a "NameSorting" function by using a "QuickSort" function and a "NameComparison" function... in a functional programming language, this style of programming becomes even more natural, with less code.

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Manually put files to Android emulator SD card

If you are using Eclipse you can move files to and from the SD Card through the Android Perspective (it is called DDMS in Eclipse). Just select the Emulator in the left part of the screen and then choose the File Explorer tab. Above the list with your files should be two symbols, one with an arrow pointing at a phone, clicking this will allow you to choose a file to move to phone memory.

Multiple submit buttons on HTML form – designate one button as default

If you're using jQuery, this solution from a comment made here is pretty slick:

$(function(){
    $('form').each(function () {
        var thisform = $(this);
        thisform.prepend(thisform.find('button.default').clone().css({
            position: 'absolute',
            left: '-999px',
            top: '-999px',
            height: 0,
            width: 0
        }));
    });
});

Just add class="default" to the button you want to be the default. It puts a hidden copy of that button right at the beginning of the form.

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

No events get triggered when the element is having disabled attribute.

None of the below will get triggered.

$("[disabled]").click( function(){ console.log("clicked") });//No Impact
$("[disabled]").hover( function(){ console.log("hovered") });//No Impact
$("[disabled]").dblclick( function(){ console.log("double clicked") });//No Impact

While readonly will be triggered.

$("[readonly]").click( function(){ console.log("clicked") });//log - clicked
$("[readonly]").hover( function(){ console.log("hovered") });//log - hovered
$("[readonly]").dblclick( function(){ console.log("double clicked") });//log - double clicked

Python dictionary : TypeError: unhashable type: 'list'

You can also use defaultdict to address this situation. It goes something like this:

from collections import defaultdict

#initialises the dictionary with values as list
aTargetDictionary = defaultdict(list)

for aKey in aSourceDictionary:
    aTargetDictionary[aKey].append(aSourceDictionary[aKey])

Number of days between past date and current date in Google spreadsheet

DAYS360 does not calculate what you want, i.e. the number of days passed between the two dates. Use simple subtraction (-) or MINUS(). I made an updated copy of @DrCord’s sample spreadsheet to illustrate this.

Are you SURE you want DAYS360? That is a specialized function used in the financial sector to simplify calculations for bonds. It assumes a 360 day year, with 12 months of 30 days each. If you really want actual days, you'll lose 6 days each year. [source]

how to add button click event in android studio

public class EditProfile extends AppCompatActivity {

    Button searchBtn;
    EditText userName_editText;
    EditText password_editText;
    EditText dob_editText;
    RadioGroup genderRadioGroup;
    RadioButton genderRadioBtn;
    Button editBtn;
    Button deleteBtn;
    Intent intent;
    DBHandler dbHandler;

    public static final String USERID_EDITPROFILE = "userID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        searchBtn = (Button)findViewById(R.id.editprof_searchbtn);
        userName_editText = (EditText)findViewById(R.id.editprof_userName);
        password_editText = (EditText)findViewById(R.id.editprof_password);
        dob_editText = (EditText)findViewById(R.id.editprof_dob);
        genderRadioGroup = (RadioGroup)findViewById(R.id.editprof_radiogroup);
        editBtn = (Button)findViewById(R.id.editprof_editbtn);
        deleteBtn = (Button)findViewById(R.id.editprof_deletebtn);
        intent = getIntent();


        dbHandler = new DBHandler(EditProfile.this);

        setUserDetails();

        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = userName_editText.getText().toString();

                if(username == null){
                    Toast.makeText(EditProfile.this,"Please enter username to delete your profile",Toast.LENGTH_SHORT).show();
                }
                else{
                    UserProfile.Users users = dbHandler.readAllInfor(username);

                    if(users == null){
                        Toast.makeText(EditProfile.this,"No profile found from this username, please enter valid username",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        dbHandler.deleteInfo(username);
                        Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
                        startActivity(redirectintent_home);
                    }
                }
            }
        });

        editBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String userID_String = intent.getStringExtra(Home.USERID);
                if(userID_String == null){
                    Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
                    Intent redirectintent_home =  new Intent(getApplicationContext(),Home.class);
                    startActivity(redirectintent_home);
                }
                int userID = Integer.parseInt(userID_String);

                String username = userName_editText.getText().toString();
                String password = password_editText.getText().toString();
                String dob = dob_editText.getText().toString();
                int selectedGender = genderRadioGroup.getCheckedRadioButtonId();
                genderRadioBtn = (RadioButton)findViewById(selectedGender);
                String gender = genderRadioBtn.getText().toString();

                UserProfile.Users users = UserProfile.getProfile().getUser();
                users.setUsername(username);
                users.setPassword(password);
                users.setDob(dob);
                users.setGender(gender);
                users.setId(userID);

                dbHandler.updateInfor(users);
                Toast.makeText(EditProfile.this,"Updated Successfully",Toast.LENGTH_SHORT).show();
                Intent redirectintent_home = new Intent(getApplicationContext(),Home.class);
                startActivity(redirectintent_home);
            }
        });

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               String username = userName_editText.getText().toString();
               if (username == null){
                   Toast.makeText(EditProfile.this,"Please enter a username",Toast.LENGTH_SHORT).show();
               }
               else{
                   UserProfile.Users users_search = dbHandler.readAllInfor(username);


                   if(users_search == null){
                       Toast.makeText(EditProfile.this,"Please enter a valid username",Toast.LENGTH_SHORT).show();
                   }
                   else{
                       userName_editText.setText(users_search.getUsername());
                       password_editText.setText(users_search.getPassword());
                       dob_editText.setText(users_search.getDob());
                       int id = users_search.getId();
                       Intent redirectintent = new Intent("com.modelpaper.mad.it17121002.EditProfile");
                       redirectintent.putExtra(USERID_EDITPROFILE,Integer.toString(id));
                       startActivity(redirectintent);
                   }
               }
            }
        });


    }

    public void setUserDetails(){

        String userID_String = intent.getStringExtra(Home.USERID);
        if(userID_String == null){
            Toast.makeText(EditProfile.this,"Error!!",Toast.LENGTH_SHORT).show();
            Intent redirectintent_home = new Intent("com.modelpaper.mad.it17121002.Home");
            startActivity(redirectintent_home);
        }
        int userID = Integer.parseInt(userID_String);
        UserProfile.Users users = dbHandler.readAllInfor(userID);
        userName_editText.setText(users.getUsername());
        password_editText.setText(users.getPassword());
        dob_editText.setText(users.getDob());
    }
}

How to delete all instances of a character in a string in python?

I suggest split (not saying that the other answers are invalid, this is just another way to do it):

def findreplace(char, string):
   return ''.join(string.split(char))

Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below

In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'

And the speed...

In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204

Not as fast as replace or translate, but ok.

How to determine if Javascript array contains an object with an attribute that equals a given value?

Unless you want to restructure it like this:

vendors = {
    Magenic: {
      Name: 'Magenic',
      ID: 'ABC'
     },
    Microsoft: {
      Name: 'Microsoft',
      ID: 'DEF'
    } and so on... 
};

to which you can do if(vendors.Magnetic)

You will have to loop

What is 'Currying'?

There is an example of "Currying in ReasonML".

let run = () => {
    Js.log("Curryed function: ");
    let sum = (x, y) => x + y;
    Printf.printf("sum(2, 3) : %d\n", sum(2, 3));
    let per2 = sum(2);
    Printf.printf("per2(3) : %d\n", per2(3));
  };

How to position the Button exactly in CSS

I'd use absolute positioning:

#play_button {
    position:absolute;
transition: .5s ease;
    left: 202px;
    top: 198px;

}

Installing PDO driver on MySQL Linux server

At first install necessary PDO parts by running the command

`sudo apt-get install php*-mysql` 

where * is a version name of php like 5.6, 7.0, 7.1, 7.2

After installation you need to mention these two statements

extension=pdo.so
extension=pdo_mysql.so

in your .ini file (uncomment if it is already there) and restart server by command

sudo service apache2 restart

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB intended to retain character-based data.

Integer division: How do you produce a double?

What's wrong with casting primitives?

If you don't want to cast for some reason, you could do

double d = num * 1.0 / denom;

SSH library for Java

Update: The GSOC project and the code there isn't active, but this is: https://github.com/hierynomus/sshj

hierynomus took over as maintainer since early 2015. Here is the older, no longer maintained, Github link:

https://github.com/shikhar/sshj


There was a GSOC project:

http://code.google.com/p/commons-net-ssh/

Code quality seem to be better than JSch, which, while a complete and working implementation, lacks documentation. Project page spots an upcoming beta release, last commit to the repository was mid-august.

Compare the APIs:

http://code.google.com/p/commons-net-ssh/

    SSHClient ssh = new SSHClient();
    //ssh.useCompression(); 
    ssh.loadKnownHosts();
    ssh.connect("localhost");
    try {
        ssh.authPublickey(System.getProperty("user.name"));
        new SCPDownloadClient(ssh).copy("ten", "/tmp");
    } finally {
        ssh.disconnect();
    }

http://www.jcraft.com/jsch/

Session session = null;
Channel channel = null;

try {

JSch jsch = new JSch();
session = jsch.getSession(username, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();

// exec 'scp -f rfile' remotely
String command = "scp -f " + remoteFilename;
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);

// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();

channel.connect();

byte[] buf = new byte[1024];

// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();

while (true) {
    int c = checkAck(in);
    if (c != 'C') {
        break;
    }

    // read '0644 '
    in.read(buf, 0, 5);

    long filesize = 0L;
    while (true) {
        if (in.read(buf, 0, 1) < 0) {
            // error
            break;
        }
        if (buf[0] == ' ') {
            break;
        }
        filesize = filesize * 10L + (long) (buf[0] - '0');
    }

    String file = null;
    for (int i = 0;; i++) {
        in.read(buf, i, 1);
        if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
        }
    }

    // send '\0'
    buf[0] = 0;
    out.write(buf, 0, 1);
    out.flush();

    // read a content of lfile
    FileOutputStream fos = null;

    fos = new FileOutputStream(localFilename);
    int foo;
    while (true) {
        if (buf.length < filesize) {
            foo = buf.length;
        } else {
            foo = (int) filesize;
        }
        foo = in.read(buf, 0, foo);
        if (foo < 0) {
            // error
            break;
        }
        fos.write(buf, 0, foo);
        filesize -= foo;
        if (filesize == 0L) {
            break;
        }
    }
    fos.close();
    fos = null;

    if (checkAck(in) != 0) {
        System.exit(0);
    }

    // send '\0'
    buf[0] = 0;
    out.write(buf, 0, 1);
    out.flush();

    channel.disconnect();
    session.disconnect();
}

} catch (JSchException jsche) {
    System.err.println(jsche.getLocalizedMessage());
} catch (IOException ioe) {
    System.err.println(ioe.getLocalizedMessage());
} finally {
    channel.disconnect();
    session.disconnect();
}

}

Share link on Google+

New Google share link: http://plus.google.com/share?url=YOUR_URL

For secure connection:

https://plus.google.com/share?url=YOUR_URL

For Wordpress:

https://plus.google.com/share?url=<?php the_permalink(); ?>

no match for ‘operator<<’ in ‘std::operator

Obviously, the standard library provided operator does not know what to do with your user defined type mystruct. It only works for predefined data types. To be able to use it for your own data type, You need to overload operator << to take your user defined data type.

How do I output lists as a table in Jupyter notebook?

A general purpose set of functions to render any python data structure (dicts and lists nested together) as HTML.

from IPython.display import HTML, display

def _render_list_html(l):
    o = []
    for e in l:
        o.append('<li>%s</li>' % _render_as_html(e))
    return '<ol>%s</ol>' % ''.join(o)

def _render_dict_html(d):
    o = []
    for k, v in d.items():
        o.append('<tr><td>%s</td><td>%s</td></tr>' % (str(k), _render_as_html(v)))
    return '<table>%s</table>' % ''.join(o)

def _render_as_html(e):
    o = []
    if isinstance(e, list):
        o.append(_render_list_html(e))
    elif isinstance(e, dict):
        o.append(_render_dict_html(e))
    else:
        o.append(str(e))
    return '<html><body>%s</body></html>' % ''.join(o)

def render_as_html(e):
    display(HTML(_render_as_html(e)))

Change the Theme in Jupyter Notebook?

After I changed the theme it behaved strangely. The font size was small, cannot see the toolbar and I really didn't like the new look.

For those who want to restore the original theme, you can do it as follows:

jt -r

You need to restart Jupyter the first time you do it and later refresh is enough to enable the new theme.

or directly from inside the notebook

!jt -r

How to detect a textbox's content has changed

Something like this should work, mainly because focus and focusout would end up with two separate values. I'm using data here because it stores values in the element but doesn't touch the DOM. It is also an easy way to store the value connected to its element. You could just as easily use a higher-scoped variable.

var changed = false;

$('textbox').on('focus', function(e) {
    $(this).data('current-val', $(this).text();
});

$('textbox').on('focusout', function(e) {
    if ($(this).data('current-val') != $(this).text())
        changed = true;
    }
    console.log('Changed Result', changed);
}

Bootstrap datepicker disabling past dates without current date

In html

<input class="required form-control" id="d_start_date" name="d_start_date" type="text" value="">

In Js side

<script type="text/javascript">
        $(document).ready(function () {
        var dateToday = new Date();
        dateToday.setDate(dateToday.getDate());

        $('#d_start_date').datepicker({
            autoclose: true,
            startDate: dateToday
        })

    });

Set Response Status Code

PHP <=5.3

The header() function has a parameter for status code. If you specify it, the server will take care of it from there.

header('HTTP/1.1 401 Unauthorized', true, 401);

PHP >=5.4

See Gajus' answer: https://stackoverflow.com/a/14223222/362536

The application may be doing too much work on its main thread

I had the same problem. When I ran the code on another computer, it worked fine. On mine, however, it displayed "The application may be doing too much work on its main thread".

I solved my problem by restarting Android studio [File -> Invalidated caches / Restart -> click on "Invalidate and Restart"].

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}

#photos li:hover {
    opacity: 1;
}

Convert string to nullable type (int, double, etc...)

You could try using the below extension method:

public static T? GetValueOrNull<T>(this string valueAsString)
    where T : struct 
{
    if (string.IsNullOrEmpty(valueAsString))
        return null;
    return (T) Convert.ChangeType(valueAsString, typeof(T));
}

This way you can do this:

double? amount = strAmount.GetValueOrNull<double>();
int? amount = strAmount.GetValueOrNull<int>();
decimal? amount = strAmount.GetValueOrNull<decimal>();

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

Why does "return list.sort()" return None, not the list?

The problem is here:

answer = newList.sort()

sort does not return the sorted list; rather, it sorts the list in place.

Use:

answer = sorted(newList)

The correct way to read a data file into an array

Just reading the file into an array, one line per element, is trivial:

open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;

Now the lines of the file are in the array @lines.

If you want to make sure there is error handling for open and close, do something like this (in the snipped below, we open the file in UTF-8 mode, too):

my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
   print STDERR "Could not open file '$path_to_file': $!\n";
   # we return 'undefined', we could also 'die' or 'croak'
   return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
   # what does it mean if close yields an error and you are just reading?
   print STDERR "Don't care error while closing '$path_to_file': $!\n";
} 

How to get just one file from another branch

Or if you want all the files from another branch:

git checkout <branch name> -- .

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

what is the difference between json and xml

The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).

A markup language is a way of adding extra information to free-flowing plain text, e.g

Here is some text.

With XML (using a certain element vocabulary) you can put:

<Document>
    <Paragraph Align="Center">
        Here <Bold>is</Bold> some text.
    </Paragraph>
</Document>

This is what makes markup languages so useful for representing documents.

An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.

{
    "Paragraphs": [
        {
            "align": "center",
            "content": [
                "Here ", {
                    "style" : "bold",
                    "content": [ "is" ]
                },
                " some text."
            ]
        }
    ]
}

It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.

On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.

{
    "firstName": "Homer",
    "lastName": "Simpson",
    "relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
} 

Here's the logically equivalent XML:

<Person>
    <FirstName>Homer</FirstName>
    <LastName>Simpsons</LastName>
    <Relatives>
        <Relative>Grandpa</Relative>
        <Relative>Marge</Relative>
        <Relative>The Boy</Relative>
        <Relative>Lisa</Relative>
        <Relative>I think that's all of them</Relative>
    </Relatives>
</Person>

JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.

But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person> is a record and <Relatives> is a list, but they are not identified as such by the syntax.

Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>, because I shouldn't have to turn <Relatives> into a single string.

By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.

So JSON should be the first choice for object notation, where XML's sweet spot is document markup.

Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.

So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.

Select all DIV text with single mouse click

This snippet provides the functionality you require. What you need to do is add an event to that div that which activates fnSelect in it. A quick hack that you totally shouldn't do and possibly might not work, would look like this:

document.getElementById("selectable").onclick(function(){
    fnSelect("selectable");
});

Obviously assuming that the linked to snippet had been included.

Are the days of passing const std::string & as a parameter over?

This highly depends on the compiler's implementation.

However, it also depends on what you use.

Lets consider next functions :

bool foo1( const std::string v )
{
  return v.empty();
}
bool foo2( const std::string & v )
{
  return v.empty();
}

These functions are implemented in a separate compilation unit in order to avoid inlining. Then :
1. If you pass a literal to these two functions, you will not see much difference in performances. In both cases, a string object has to be created
2. If you pass another std::string object, foo2 will outperform foo1, because foo1 will do a deep copy.

On my PC, using g++ 4.6.1, I got these results :

  • variable by reference: 1000000000 iterations -> time elapsed: 2.25912 sec
  • variable by value: 1000000000 iterations -> time elapsed: 27.2259 sec
  • literal by reference: 100000000 iterations -> time elapsed: 9.10319 sec
  • literal by value: 100000000 iterations -> time elapsed: 8.62659 sec

Adding items to end of linked list

The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().

Node.java

package in.datastructure.java.LinkedList;

/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
    int data;
    Node next;

    Node (int data){
       this.data = data;
    }
    public String toString(){
      return this.data+"--"+ this.next;
    }
}

LinkedList.java

package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;

public class LinkedList {

    Node head;
    Node lastx;
    /**
     * @description To append node at end looping all nodes from head
     * @param data
     */
    public void addLast(int data){

        if(head == null){
            head = new Node(data);
            return;
        }
        Node last = head;
        while(last.next != null) {
            last = last.next;
        }
        last.next = new Node(data);
    }


    /**
     * @description This keep track on last node and append to it
     * @param data
     */
    public void addLastx(int data){

        if(head == null){
            head = new Node(data);
            lastx = head;
            return;
        }
        if(lastx.next == null){
            lastx.next = new Node(data);
            lastx = lastx.next;
        }

    }

    public String toString(){
        ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
        Node current = head;
        while(current.next != null) {
            arrayList.add(current.data);
            current = current.next;
        }
        if(current.next == null) {
            arrayList.add(current.data);
        }
        return arrayList.toString();
    }


    public static void main(String[] args) {
        LinkedList ll = new LinkedList();
        /**
         * @description Checking the code optimization of append code
         */
        Date startTime = new Date();
        for (int i = 0 ; i < 100000 ; i++){
            ll.addLastx(i);
        }
        Date endTime = new Date();
        System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
        System.out.println(ll.toString());
    }

}

Mapping a JDBC ResultSet to an object

Use Statement Fetch Size , if you are retrieving more number of records. like this.

Statement statement = connection.createStatement();
statement.setFetchSize(1000); 

Apart from that i dont see an issue with the way you are doing in terms of performance

In terms of Neat. Always use seperate method delegate to map the resultset to POJO object. which can be reused later in the same class

like

private User mapResultSet(ResultSet rs){
     User user = new User();
     // Map Results
     return user;
}

If you have the same name for both columnName and object's fieldName , you could also write reflection utility to load the records back to POJO. and use MetaData to read the columnNames . but for small scale projects using reflection is not an problem. but as i said before there is nothing wrong with the way you are doing.

How to create a HTTP server in Android?

Another server you can try http://tjws.sf.net, actually it already provides Android enabled version.

PHP: if !empty & empty

For several cases, or even just a few cases involving a lot of criteria, consider using a switch.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.

Note that the { } around the cases aren't required, but they are nice for readability and code folding.

More about switch: http://php.net/manual/en/control-structures.switch.php

What's the simplest way to extend a numpy array in 2 dimensions?

Another elegant solution to the first question may be the insert command:

p = np.array([[1,2],[3,4]])
p = np.insert(p, 2, values=0, axis=1) # insert values before column 2

Leads to:

array([[1, 2, 0],
       [3, 4, 0]])

insert may be slower than append but allows you to fill the whole row/column with one value easily.

As for the second question, delete has been suggested before:

p = np.delete(p, 2, axis=1)

Which restores the original array again:

array([[1, 2],
       [3, 4]])

Create a jTDS connection string

A shot in the dark, but From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port

How do you automatically set the focus to a textbox when a web page loads?

I had a slightly different problem. I wanted autofocus, but, wanted the placeholder text to remain, cross-browser. Some browsers would hide the placeholder text as soon as the field focused, some would keep it. I had to either get placeholders staying cross-browser, which has weird side effects, or stop using autofocus.

So I listened for the first key typed against the body tag, and redirected that key into the target input field. Then all the event handlers involved get killed off to keep things clean.

var urlInput = $('#Url');

function bodyFirstKey(ev) {
    $('body').off('keydown', bodyFirstKey);
    urlInput.off('focus', urlInputFirstFocus);

    if (ev.target == document.body) {
        urlInput.focus();
        if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {
            urlInput.val(ev.key);
            return false;
        }
    }
};
function urlInputFirstFocus() {
    $('body').off('keydown', bodyFirstKey);
    urlInput.off('focus', urlInputFirstFocus);
};

$('body').keydown(bodyFirstKey);
urlInput.focus(urlInputFirstFocus);

https://jsfiddle.net/b9chris/qLrrb93w/

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):

When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.

Note: the answer was edited on Jan 2016 to reflect most recent changes

Automatically create an Enum based on values in a database lookup table?

Let's say you have the following in your DB:

table enums
-----------------
| id | name     |
-----------------
| 0  | MyEnum   |
| 1  | YourEnum |
-----------------

table enum_values
----------------------------------
| id | enums_id | value | key    |
----------------------------------
| 0  | 0        | 0     | Apple  |
| 1  | 0        | 1     | Banana |
| 2  | 0        | 2     | Pear   |
| 3  | 0        | 3     | Cherry |
| 4  | 1        | 0     | Red    |
| 5  | 1        | 1     | Green  |
| 6  | 1        | 2     | Yellow |
----------------------------------

Construct a select to get the values you need:

select * from enums e inner join enum_values ev on ev.enums_id=e.id where e.id=0

Construct the source code for the enum and you'll get something like:

String enumSourceCode = "enum " + enumName + "{" + enumKey1 + "=" enumValue1 + "," + enumKey2 + ... + "}";

(obviously this is constructed in a loop of some kind.)

Then comes the fun part, Compiling your enum and using it:

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters cs = new CompilerParameters();
cp.GenerateInMemory = True;

CompilerResult result = provider.CompileAssemblyFromSource(cp, enumSourceCode);

Type enumType = result.CompiledAssembly.GetType(enumName);

Now you have the type compiled and ready for use.
To get a enum value stored in the DB you can use:

[Enum].Parse(enumType, value);

where value can be either the integer value (0, 1, etc.) or the enum text/key (Apple, Banana, etc.)

How to generate Javadoc HTML files in Eclipse?

You can also do it from command line much easily.

  1. Open command line from the folder/package.
  2. From command line run:

    javadoc YourClassName.java

  3. To batch generate docs for multiple Class:

    javadoc *.java

Drawing rotated text on a HTML5 canvas

Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.

I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:

When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:

 context.save();
 context.translate(newx, newy);
 context.rotate(-Math.PI/2);
 context.textAlign = "center";
 context.fillText("Your Label Here", labelXposition, 0);
 context.restore();

.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".


Find out if string ends with another string in C++

My two cents:

bool endsWith(std::string str, std::string suffix)
{
   return str.find(suffix, str.size() - suffix.size()) != string::npos;
}

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

Creating a list of pairs in java

Similar to what Mark E has proposed, but no need to recreate the wheel, if you don't mind relying on 3rd party libs.

Apache Commons has tuples already defined:

org.apache.commons.lang3.tuple.Pair<L,R>

Apache Commons is so pervasive, I typically already have it in my projects, anyway. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

Set CSS property in Javascript?

It is important to understand that the code bellow does not change the stylesheet, but instead changes the DOM:

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

The DOM stores a computed value of the stylesheet element properties, and when you dynamically change an elements style using Javascript you are changing the DOM. This is important to note, and understand because the way you write your code can affect your dynamics. If you try to obtain values that were not written directly into the element itself, like so...

let elem = document.getElementById('some-element');
let propertyValue = elem.style['some-property'];

...you will return an undefined value that will be stored in the code example's 'propertyValue' variable. If you are working with getting and setting properties that were written inside a CSS style-sheet and you want a SINGLE FUNCTION that gets, as well as sets style-property-values in this situation, which is a very common situation to be in, then you have got to use JQuery.

$(selector).css(property,value)

The only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery. If you want to get a CSS property that was computed from a style-sheet in pure JavaScript then you need to use.

function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

The downside to this method is that the getComputedValue method only gets, it does not set. Mozilla's Take on Computed Values This link goes more into depth about what I have addressed here. Hope This Helps Someone!!!

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

Combine Multiple child rows into one row MYSQL

The easiest way would be to make use of the GROUP_CONCAT group function here..

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  GROUP_CONCAT(Ordered_Options.Value) as `Options`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Which would output:

Id              ItemName       Options

1               Pizza          Pepperoni,Extra Cheese

2               Stromboli      Extra Cheese

That way you can have as many options as you want without having to modify your query.

Ah, if you see your results getting cropped, you can increase the size limit of GROUP_CONCAT like this:

SET SESSION group_concat_max_len = 8192;

submit a form in a new tab

This will also work great, u can do something else while a new tab handler the submit .

<form target="_blank">
    <a href="#">Submit</a>
</form>

<script>
    $('a').click(function () {
        // do something you want ...

        $('form').submit();
    });
</script>

Set Value of Input Using Javascript Function

Try

gadget_url.value=''

_x000D_
_x000D_
addGadgetUrl.addEventListener('click', () => {_x000D_
   gadget_url.value = '';_x000D_
});
_x000D_
<div>_x000D_
  <p>URL</p>_x000D_
  <input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />_x000D_
  <input type="button" id="addGadgetUrl" value="add gadget" />_x000D_
  <br>_x000D_
  <span id="error"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Update

I don't know why so many downovotes (and no comments) - however (for future readers) don't think that this solution not work - It works with html provided in OP question and this is SHORTEST working solution - you can try it by yourself HERE

How to import csv file in PHP?

PHP > 5.3 use fgetcsv() or str_getcsv(). Couldn't be simpler.

Difference between $(this) and event.target?

There are cross browser issues here.

A typical non-jQuery event handler would be something like this :

function doSomething(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

jQuery normalises evt and makes the target available as this in event handlers, so a typical jQuery event handler would be something like this :

function doSomething(evt) {
    var $target = $(this);
    //do stuff here
}

A hybrid event handler which uses jQuery's normalised evt and a POJS target would be something like this :

function doSomething(evt) {
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

How to connect Robomongo to MongoDB

Currently, Robomongo 0.8.x doesn't work with MongoDB 3.0:

For now, don't use Robomongo. For me, the best solution is to use MongoChef.

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

basic authorization command for curl

Use the -H header again before the Authorization:Basic things. So it will be

curl -i \
    -H 'Accept:application/json' \
    -H 'Authorization:Basic BASE64_string' \
    http://example.com

Here, BASE64_string = Base64 of username:password

How do you remove a Cookie in a Java Servlet

One special case: a cookie has no path.

In this case set path as cookie.setPath(request.getRequestURI())

The javascript sets cookie without path so the browser shows it as cookie for the current page only. If I try to send the expired cookie with path == / the browser shows two cookies: one expired with path == / and another one with path == current page.

Reloading submodules in IPython

I hate to add yet another answer to a long thread, but I found a solution that enables recursive reloading of submodules on %run() that others might find useful (I have anyway)

del the submodule you wish to reload on run from sys.modules in iPython:

In[1]: from sys import modules
In[2]: del modules["mymodule.mysubmodule"] # tab completion can be used like mymodule.<tab>!

Now your script will recursively reload this submodule:

In[3]: %run myscript.py

How can I center an image in Bootstrap?

Three ways to align img in the center of its parent.

  1. img is an inline element, text-center aligns inline elements in the center of its container should the container be a block element.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col text-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. mx-auto centers block elements. In order to so, change display of the img from inline to block with d-block class.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  1. Use d-flex and justify-content-center on its parent.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
  <div class="row">_x000D_
    <div class="col d-flex justify-content-center">_x000D_
      <img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Directly from the Windows.h header file:

#ifndef WIN32_LEAN_AND_MEAN
    #include <cderr.h>
    #include <dde.h>
    #include <ddeml.h>
    #include <dlgs.h>
    #ifndef _MAC
        #include <lzexpand.h>
        #include <mmsystem.h>
        #include <nb30.h>
        #include <rpc.h>
    #endif
    #include <shellapi.h>
    #ifndef _MAC
        #include <winperf.h>
        #include <winsock.h>
    #endif
    #ifndef NOCRYPT
        #include <wincrypt.h>
        #include <winefs.h>
        #include <winscard.h>
    #endif

    #ifndef NOGDI
        #ifndef _MAC
            #include <winspool.h>
            #ifdef INC_OLE1
                #include <ole.h>
            #else
                #include <ole2.h>
            #endif /* !INC_OLE1 */
        #endif /* !MAC */
        #include <commdlg.h>
    #endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */

if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.

Also, from Microsoft's support page:

To speed the build process, Visual C++ and the Windows Headers provide the following new defines:

VC_EXTRALEAN
WIN32_LEAN_AND_MEAN

You can use them to reduce the size of the Win32 header files.

Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.

Capturing window.onbeforeunload

To pop a message when the user is leaving the page to confirm leaving, you just do:

<script>
    window.onbeforeunload = function(e) {
      return 'Are you sure you want to leave this page?  You will lose any unsaved data.';
    };
</script>

To call a function:

<script>
    window.onbeforeunload = function(e) {
       callSomeFunction();
       return null;
    };
</script>

Get Locale Short Date Format using javascript

Can't be done.

Cross-browser JavaScript has no way to use the actual short date format selected by the user on platforms that offer such regional customization. Besides, JavaScript has huge holes where any sort of formatting is concerned. Look how much hassle zero-padding is!

You can go to great lengths to obtain the language setting, and get the typical format for that locale. That's a lot of work when you don't even know if it's the correct locale (I'd bet that international language headers are often incorrect or not specific enough), or if the user has customized the format to something else.

You can try using client VBScript (which has functions for all of these regional formatting permutations), but that's not a good idea because it's a dying (dead?) IE-specific technology.

You can also try using Java/Flash/Silverlight to dig up the format. This is also a great deal of extra work, but may have the best chance for success. You'd want to cache it for the session to minimize the overhead.

Hopefully the HTML5 <time> element will provide some relief for i18n date/time display.

How to pass multiple parameters in thread in VB

First of all: AddressOf just gets the delegate to a function - you cannot specify anything else (i.e. capture any variables).

Now, you can start up a thread in two possible ways.

  • Pass an Action in the constructor and just Start() the thread.
  • Pass a ParameterizedThreadStart and forward one extra object argument to the method pointed to when calling .Start(parameter)

I consider the latter option an anachronism from pre-generic, pre-lambda times - which have ended at the latest with VB10.

You could use that crude method and create a list or structure which you pass to your threading code as this single object parameter, but since we now have closures, you can just create the thread on an anonymous Sub that knows all necessary variables by itself (which is work performed for you by the compiler).

Soo ...

Dim Evaluator = New Thread(Sub() Me.TestThread(goodList, 1))

It's really just that ;)

How can I make a button have a rounded border in Swift?

@IBOutlet weak var button: UIButton!

...

I think for radius just enough this parameter:

button.layer.cornerRadius = 5

Change the background color of CardView programmatically

Cardview is a bit coy. I had list of colors in my structure and Model is like

class ModelColor : Serializable {

var id: Int? = 0
var title: String? = ""
var color: Int? = 0// HERE IS THE COLOR FIELD WE WILL USE

constructor(id: Int?, title: String?, color: Int?) {
    this.id = id
    this.title = title
    this.color = color
}

}

load the model with color, last item on constructure taking from R.color

 list.add(ModelColor(2, getString(R.string.orange), R.color.orange_500))

and finaly you can setBackgriundResource

 cv_add_goal_choose_color.setBackgroundResource(color)

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);

$this->db->where('id', $_POST['id']);

$this->db->update('tbl_user', $data);

Clearing content of text file using C#

Another short version:

System.IO.File.WriteAllBytes(path, new byte[0]);

How do I run a program with commandline arguments using GDB within a Bash script?

Another way to do this, which I personally find slightly more convenient and intuitive (without having to remember the --args parameter), is to compile normally, and use r arg1 arg2 arg3 directly from within gdb, like so:

$ gcc -g *.c *.h
$ gdb ./a.out
(gdb) r arg1 arg2 arg3

Commit history on remote repository

NB. "origin" below use to represent the upstream of a cloned repository, replace "origin" with a descriptive name for the remote repo. "remote reference" can use the same format used in clone command.

git remote add origin <remote reference>
git fetch
git log origin/master

when do you need .ascx files and how would you use them?

ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:

Initializing multiple variables to the same value in Java

You can declare multiple variables, and initialize multiple variables, but not both at the same time:

 String one,two,three;
 one = two = three = "";

However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".

Float right and position absolute doesn't work together

Perhaps you should divide your content like such using floats:

<div style="overflow: auto;">
    <div style="float: left; width: 600px;">
        Here is my content!
    </div>
    <div style="float: right; width: 300px;">
        Here is my sidebar!
    </div>
</div>

Notice the overflow: auto;, this is to ensure that you have some height to your container. Floating things takes them out of the DOM, to ensure that your elements below don't overlap your wandering floats, set a container div to have an overflow: auto (or overflow: hidden) to ensure that floats are accounted for when drawing your height. Check out more information on floats and how to use them here.

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

If it is a maven project

  1. right click on the pom.xml
  2. Add As Maven Project

Thanks

How to clear gradle cache?

As @Bradford20000 pointed out in the comments, there might be a gradle.properties file as well as global gradle scripts located under $HOME/.gradle. In such case special attention must be paid when deleting the content of this directory.

The .gradle/caches directory holds the Gradle build cache. So if you have any error about build cache, you can delete it.

The --no-build-cache option will run gradle without the build cache.

Convert json to a C# array?

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

Using Mysql in the command line in osx - command not found?

You can just modified the .bash_profile by adding the MySQL $PATH as the following:
export PATH=$PATH:/usr/local/mysql/bin.

I did the following:

1- Open Terminal then $ nano .bash_profile or $ vim .bash_profile

2- Add the following PATH code to the .bash_profile

# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc 

3- Save the file.

4- Refresh Terminal using $ source ~/.bash_profile

5- To verify, type in Terminal $ mysql --version

6- It should print the output something like this:

$ mysql Ver 14.14 Distrib 5.7.17, for macos10.12 (x86_64)

The Terminal is now configured to read the MySQL commands from $PATH which is placed in the .bash_profile .

What is the fastest/most efficient way to find the highest set bit (msb) in an integer in C?

Assuming you're on x86 and game for a bit of inline assembler, Intel provides a BSR instruction ("bit scan reverse"). It's fast on some x86s (microcoded on others). From the manual:

Searches the source operand for the most significant set bit (1 bit). If a most significant 1 bit is found, its bit index is stored in the destination operand. The source operand can be a register or a memory location; the destination operand is a register. The bit index is an unsigned offset from bit 0 of the source operand. If the content source operand is 0, the content of the destination operand is undefined.

(If you're on PowerPC there's a similar cntlz ("count leading zeros") instruction.)

Example code for gcc:

#include <iostream>

int main (int,char**)
{
  int n=1;
  for (;;++n) {
    int msb;
    asm("bsrl %1,%0" : "=r"(msb) : "r"(n));
    std::cout << n << " : " << msb << std::endl;
  }
  return 0;
}

See also this inline assembler tutorial, which shows (section 9.4) it being considerably faster than looping code.

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

Check if Nullable Guid is empty in c#

If you want be sure you need to check both

SomeProperty == null || SomeProperty == Guid.Empty

Because it can be null 'Nullable' and it can be an empty GUID something like this {00000000-0000-0000-0000-000000000000}

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

M.K. offered a great plugin in his answer. Plugin can be found here. However, for the sake of completion, I thought it'd be a good idea to put it together in one answer for AngularJS.

  1. Start by injecting the bower or npm (whichever is preferred)

    bower install jquery-scrollLock --save
    npm install jquery-scroll-lock --save
    
  2. Add the following directive. I am choosing to add it as an attribute

    (function() {
       'use strict';
    
        angular
           .module('app')
           .directive('isolateScrolling', isolateScrolling);
    
           function isolateScrolling() {
               return {
                   restrict: 'A',
                   link: function(sc, elem, attrs) {
                      $('.scroll-container').scrollLock();
                   }
               }
           }
    })();
    
  3. And the important piece the plugin fails to document in their website is the HTML structure that it must follow.

    <div class="scroll-container locked">
        <div class="scrollable" isolate-scrolling>
             ... whatever ...
        </div>
    </div>
    

The attribute isolate-scrolling must contain the scrollable class and it all needs to be inside the scroll-container class or whatever class you choose and the locked class must be cascaded.

How to get names of classes inside a jar file?

Description OF Solution : Eclipse IDE can be used for this by creating a sample java project and add all jars in the Project Build path

STEPS below:

  1. Create a sample Eclipse Java project.

  2. All all the jars you have in its Build Path

  3. CTRL+SHIFT+T and Type the full class name .

  4. Results will be displayed in the window with all the jars having that class. See attached picture . enter image description here

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

According to your package.json, you're using Angular 8.3, but you've imported angular/cdk v9. You can downgrade your angular/cdk version or you can upgrade your Angular version to v9 by running:

ng update @angular/core @angular/cli

That will update your local angular version to 9. Then, just to sync material, run: ng update @angular/material

How to use '-prune' option of 'find' in sh?

Adding to the advice given in other answers (I have no rep to create replies)...

When combining -prune with other expressions, there is a subtle difference in behavior depending on which other expressions are used.

@Laurence Gonsalves' example will find the "*.foo" files that aren't under ".snapshot" directories:-

find . -name .snapshot -prune -o -name '*.foo' -print

However, this slightly different short-hand will, perhaps inadvertently, also list the .snapshot directory (and any nested .snapshot directories):-

find . -name .snapshot -prune -o -name '*.foo'

The reason is (according to the manpage on my system):-

If the given expression does not contain any of the primaries -exec, -ls, -ok, or -print, the given expression is effectively replaced by:

( given_expression ) -print

That is, the second example is the equivalent of entering the following, thereby modifying the grouping of terms:-

find . \( -name .snapshot -prune -o -name '*.foo' \) -print

This has at least been seen on Solaris 5.10. Having used various flavors of *nix for approx 10 years, I've only recently searched for a reason why this occurs.

How to set the opacity/alpha of a UIImage?

I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:

- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

    CGContextSetAlpha(ctx, alpha);

    CGContextDrawImage(ctx, area, self.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

jQuery add class .active on menu

Setting the active menu, they have the many ways to do that. Now, I share you a way to set active menu by CSS.

    <a href="index.php?id=home">Home</a>
    <a href="index.php?id=news">News</a>
    <a href="index.php?id=about">About</a>

Now, you only set $_request["id"] == "home" thì echo "class='active'" , then we can do same with others.

<a href="index.php?id=home" <?php if($_REQUEST["id"]=="home"){echo "class='active'";}?>>Home</a>
<a href="index.php?id=news" <?php if($_REQUEST["id"]=="news"){echo "class='active'";}?>>News</a>
<a href="index.php?id=about" <?php if($_REQUEST["id"]=="about"){echo "class='active'";}?>>About</a>

I think it is useful with you.

Using mysql concat() in WHERE clause?

SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'

...is probably what you want.

Java error: Only a type can be imported. XYZ resolves to a package

My bet is that you have a package called org.ivec.eresearch.knowledgeportal.model.category (small c) and are running on a non-case sensitive filesystem like Windows or Mac. It seems that the compiler gets confused when a class and package exist.

You can either renamed the class "Category" or the package "category" and this error will go away. Unfortunately I'm not sure if this is a Tomcat or ECJ bug.

ASP.NET MVC - Getting QueryString values

I think what you are looking for is

Request.QueryString["QueryStringName"]

and you can access it on views by adding @

now look at my example,,, I generated a Url with QueryString

 var listURL = '@Url.RouteUrl(new { controller = "Sector", action = "List" , name = Request.QueryString["name"]})';

the listURL value is /Sector/List?name=value'

and when queryString is empty

listURL value is /Sector/List

How do you reindex an array in PHP but with indexes starting from 1?

A more elegant solution:

$list = array_combine(range(1, count($list)), array_values($list));

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

angularjs: allows only numbers to be typed into a text box

I just used ng-keypress in the directive for my input.

HTML:

<input type="text" ng-keypress="filterValue($event)"/>

JS:

$scope.filterValue = function($event){
        if(isNaN(String.fromCharCode($event.keyCode))){
            $event.preventDefault();
        }
};

Redirect parent window from an iframe action

It is possible to redirect from an iframe, but not to get information from the parent.

Remove all whitespace in a string

import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)

How do I parse a string with a decimal point to a double?

Instead of having to specify a locale in all parses, I prefer to set an application wide locale, although if string formats are not consistent across the app, this might not work.

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-PT");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("pt-PT");

Defining this at the begining of your application will make all double parses expect a comma as the decimal delimiter. You can set an appropriate locale so that the decimal and thousands separator fits the strings you are parsing.

Display calendar to pick a date in java

I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;

public class DatePickerExample extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JXPicker Example");
        JPanel panel = new JPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 400, 250, 100);

        JXDatePicker picker = new JXDatePicker();
        picker.setDate(Calendar.getInstance().getTime());
        picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));

        panel.add(picker);
        frame.getContentPane().add(panel);

        frame.setVisible(true);
    }
}

How do I calculate the date in JavaScript three months prior to today?

_x000D_
_x000D_
   _x000D_
_x000D_
 var date=document.getElementById("date");_x000D_
    var d = new Date();_x000D_
   document.write(d + "<br/>");_x000D_
    d.setMonth(d.getMonth() - 6);_x000D_
    document.write(d);_x000D_
_x000D_
 if(d<date)_x000D_
  document.write("lesser then 6 months");_x000D_
else_x000D_
  document.write("greater then 6 months");
_x000D_
_x000D_
_x000D_

What's the difference between console.dir and console.log?

Following Felix Klings advice I tried it out in my chrome browser.

console.dir([1,2]) gives the following output:

Array[2]
 0: 1
 1: 2
 length: 2
 __proto__: Array[0]

While console.log([1,2]) gives the following output:

[1, 2]

So I believe console.dir() should be used to get more information like prototype etc in arrays and objects.

getResourceAsStream() vs FileInputStream

The java.io.File and consorts acts on the local disk file system. The root cause of your problem is that relative paths in java.io are dependent on the current working directory. I.e. the directory from which the JVM (in your case: the webserver's one) is started. This may for example be C:\Tomcat\bin or something entirely different, but thus not C:\Tomcat\webapps\contextname or whatever you'd expect it to be. In a normal Eclipse project, that would be C:\Eclipse\workspace\projectname. You can learn about the current working directory the following way:

System.out.println(new File(".").getAbsolutePath());

However, the working directory is in no way programmatically controllable. You should really prefer using absolute paths in the File API instead of relative paths. E.g. C:\full\path\to\file.ext.

You don't want to hardcode or guess the absolute path in Java (web)applications. That's only portability trouble (i.e. it runs in system X, but not in system Y). The normal practice is to place those kind of resources in the classpath, or to add its full path to the classpath (in an IDE like Eclipse that's the src folder and the "build path" respectively). This way you can grab them with help of the ClassLoader by ClassLoader#getResource() or ClassLoader#getResourceAsStream(). It is able to locate files relative to the "root" of the classpath, as you by coincidence figured out. In webapplications (or any other application which uses multiple classloaders) it's recommend to use the ClassLoader as returned by Thread.currentThread().getContextClassLoader() for this so you can look "outside" the webapp context as well.

Another alternative in webapps is the ServletContext#getResource() and its counterpart ServletContext#getResourceAsStream(). It is able to access files located in the public web folder of the webapp project, including the /WEB-INF folder. The ServletContext is available in servlets by the inherited getServletContext() method, you can call it as-is.

See also:

Sleep function in ORACLE

There is a good article on this topic: PL/SQL: Sleep without using DBMS_LOCK that helped me out. I used Option 2 wrapped in a custom package. Proposed solutions are:

Option 1: APEX_UTIL.sleep

If APEX is installed you can use the procedure “PAUSE” from the publicly available package APEX_UTIL.

Example – “Wait 5 seconds”:

SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    APEX_UTIL.PAUSE(5);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/

Option 2: java.lang.Thread.sleep

An other option is the use of the method “sleep” from the Java class “Thread”, which you can easily use through providing a simple PL/SQL wrapper procedure:

Note: Please remember, that “Thread.sleep” uses milliseconds!

--- create ---
CREATE OR REPLACE PROCEDURE SLEEP (P_MILLI_SECONDS IN NUMBER) 
AS LANGUAGE JAVA NAME 'java.lang.Thread.sleep(long)';

--- use ---
SET SERVEROUTPUT ON ;
BEGIN
    DBMS_OUTPUT.PUT_LINE('Start ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
    SLEEP(5 * 1000);
    DBMS_OUTPUT.PUT_LINE('End   ' || to_char(SYSDATE, 'YYYY-MM-DD HH24:MI:SS'));
END;
/

SSRS expression to format two decimal places does not show zeros

If you want it as a string use:

=Format(Fields!CUL1.Value, "F2")

As a number use:

=FormatNumber(Fields!CUL1.Value, 2)

This will ensure it exports out to excel correctly as a number.

Arduino COM port doesn't work

Installing Drivers for Arduino in Windows 8 / 7.

( I tried it for Uno r3, but i believe it will work for all Arduino Boards )

Plugin your Arduino Board

Go to Control Panel ---> System and Security ---> System ---> On the left pane Device Manger

Expand Other Devices.

Under Other Devices you will notice a icon with a small yellow error graphic. (Unplug all your other devices attached to any Serial Port)

Right Click on that device ---> Update Driver Software

Select Browse my computer for Driver Software

Click on Browse ---> Browse for the folder of Arduino Environment which you have downloaded from Arduino website. If not downloaded then http://arduino.cc/en/Main/Software

After Browsing mark include subfolder.

Click next ---> Your driver will be installed.

Collapse Other Devices ---> Expand Port ( its in device manager only under other devices )

You will see Arduino Written ---> Look for its COM PORT (close device manager)

Go to Arduino Environment ---> Tools ---> Serial Port ---> Select the COM PORT as mentioned in PORT in device manager. (If you are using any other Arduino Board instead of UNO then select the same in boards )

Upload your killer programmes and see them work . . .

I hope this helps. . .

Welcome

Download and open PDF file using Ajax

What worked for me is the following code, as the server function is retrieving File(memoryStream.GetBuffer(), "application/pdf", "fileName.pdf");:

$http.get( fullUrl, { responseType: 'arraybuffer' })
            .success(function (response) {
                var blob = new Blob([response], { type: 'application/pdf' });

                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob); // for IE
                }
                else {
                    var fileURL = URL.createObjectURL(blob);
                    var newWin = window.open(fileURL);
                    newWin.focus();
                    newWin.reload();
                }
});

The opposite of Intersect()

string left = "411329_SOFT_MAC_GREEN";
string right= "SOFT_MAC_GREEN";

string[] l = left.Split('_');
string[] r = right.Split('_');

string[] distinctLeft = l.Distinct().ToArray();
string[] distinctRight = r.Distinct().ToArray();

var commonWord = l.Except(r, StringComparer.OrdinalIgnoreCase)
string result = String.Join("_",commonWord);
result = "411329"

Split an integer into digits to compute an ISBN checksum

Answer: 165

Method: brute-force! Here is a tiny bit of Python (version 2.7) code to count'em all.

from math import sqrt, floor
is_ps = lambda x: floor(sqrt(x)) ** 2 == x
count = 0
for n in range(1002, 10000, 3):
    if n % 11 and is_ps(sum(map(int, str(n)))):
        count += 1
        print "#%i: %s" % (count, n)

Why is my Git Submodule HEAD detached from master?

I am also still figuring out the internals of git, and have figured out this so far:

  1. HEAD is a file in your .git/ directory that normally looks something like this:
% cat .git/HEAD
ref: refs/heads/master
  1. refs/heads/master is itself a file that normally has the hash value of the latest commit:
% cat .git/refs/heads/master 
cbf01a8e629e8d884888f19ac203fa037acd901f
  1. If you git checkout a remote branch that is ahead of your master, this may cause your HEAD file to be updated to contain the hash of the latest commit in the remote master:
% cat .git/HEAD
8e2c815f83231f85f067f19ed49723fd1dc023b7

This is called a detached HEAD. The remote master is ahead of your local master. When you do git submodule --remote myrepo to get the latest commit of your submodule, it will by default do a checkout, which will update HEAD. Since your current branch master is behind, HEAD becomes 'detached' from your current branch, so to speak.

Append text with .bat

You need to use ECHO. Also, put the quotes around the entire file path if it contains spaces.

One other note, use > to overwrite a file if it exists or create if it does not exist. Use >> to append to an existing file or create if it does not exist.

Overwrite the file with a blank line:

ECHO.>"C:\My folder\Myfile.log"

Append a blank line to a file:

ECHO.>>"C:\My folder\Myfile.log"

Append text to a file:

ECHO Some text>>"C:\My folder\Myfile.log"

Append a variable to a file:

ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"

Repeat a task with a time delay?

Timer is another way to do your work but be quiet sure to add runOnUiThread if you are working with UI.

    import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

 CheckBox optSingleShot;
 Button btnStart, btnCancel;
 TextView textCounter;

 Timer timer;
 MyTimerTask myTimerTask;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  optSingleShot = (CheckBox)findViewById(R.id.singleshot);
  btnStart = (Button)findViewById(R.id.start);
  btnCancel = (Button)findViewById(R.id.cancel);
  textCounter = (TextView)findViewById(R.id.counter);

  btnStart.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {

    if(timer != null){
     timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
     //singleshot delay 1000 ms
     timer.schedule(myTimerTask, 1000);
    }else{
     //delay 1000ms, repeat in 5000ms
     timer.schedule(myTimerTask, 1000, 5000);
    }
   }});

  btnCancel.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    if (timer!=null){
     timer.cancel();
     timer = null;
    }
   }
  });

 }

 class MyTimerTask extends TimerTask {

  @Override
  public void run() {
   Calendar calendar = Calendar.getInstance();
   SimpleDateFormat simpleDateFormat = 
     new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
   final String strDate = simpleDateFormat.format(calendar.getTime());

   runOnUiThread(new Runnable(){

    @Override
    public void run() {
     textCounter.setText(strDate);
    }});
  }

 }

}

and xml is...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:autoLink="web"
    android:text="http://android-er.blogspot.com/"
    android:textStyle="bold" />
<CheckBox 
    android:id="@+id/singleshot"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Single Shot"/>

Another Way to use CountDownTimer

new CountDownTimer(30000, 1000) {

     public void onTick(long millisUntilFinished) {
         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:

For Details

SELECT list is not in GROUP BY clause and contains nonaggregated column

As @Brian Riley already said you should either remove 1 column in your select

select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;

or add it to your grouping

select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;

Why does Vim save files with a ~ extension?

I think the better solution is to place these lines in your vimrc file

set backupdir=~/vimtmp//,.
set directory=~/vimtmp//,.

The first line is for backup files, the second line for swap files. The double slash at the end ensures that there is no conflict in case of two files having the same name, see comments (at the time of this edit this option is only honored for swap files, not yet for backup files). The ,. allow vim to use the current directory if the former doesn't exist.

You have to create a directory in your home directory called vimtmp for this to work. Also, check that backups are enabled in your config (add set backup if not).

That way you get the benefit of both worlds, you don't have to see the files, but if something does get futzed you can go get your backup file from vimtmp. Don't forget to clean the directory out every now and then.

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

Found this in google groups and this worked for me..

Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRect(0, 0, width, height, clearPaint); 

This removes drawings rectangles etc. while keeping set bitmap..

How to set HTML5 required attribute in Javascript?

And the jquery version:

$('input').attr('required', true)
$('input').attr('required', false)

I know it's beyond the question, but maybe someone will find this helpful :)

Transfer data between databases with PostgreSQL

Just like leonbloy suggested, using two schemas in a database is the way to go. Suppose a source schema (old DB) and a target schema (new DB), you can try something like this (you should consider column names, types, etc.):

INSERT INTO target.Awards SELECT * FROM source.Nominations;

javascript: detect scroll end

Since innerHeight doesn't work in some old IE versions, clientHeight can be used:

$(window).scroll(function (e){
    var body = document.body;    
    //alert (body.clientHeight);
    var scrollTop = this.pageYOffset || body.scrollTop;
    if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) {
        loadMoreNews();
    }
});

How to Change Font Size in drawString Java

Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...

Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);

You can also use TextAttribute.

Map<TextAttribute, Object> attributes = new HashMap<>();

attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);

g.setFont(myFont);

The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.

One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.

HTTP headers in Websockets client API

You can pass the headers as a key-value in the third parameter (options) inside an object. Example with Authorization token. Left the protocol (second parameter) as null


ws = new WebSocket(‘ws://localhost’, null, { headers: { Authorization: token }})

Edit: Seems that this approach only works with nodejs library not with standard browser implementation. Leaving it because it might be useful to some people.

How to remove multiple deleted files in Git repository

The best solution if you don't care about staging modified files is to use git add -u as said by mshameers and/or pb2q.

If you just want to remove deleted files, but not stage any modified ones, I think you should use the ls-files argument with the --deleted option (no need to use regex or other complex args/options) :

git ls-files --deleted | xargs git rm

'nuget' is not recognized but other nuget commands working

  • Right-click on your project in solution explorer.
  • Select Manage NuGet Packages for Solution.
  • Search NuGet.CommandLine by Microsoft and Install it. Search Nuget.CommandLine
  • On complete installation, you will find a folder named packages in your project. Go to solution explorer and look for it. packages
  • Inside packages look for a folder named NuGet.CommandLine.3.5.0, here 3.5.0 is just version name your folder name will change accordingly. nuGet COmmand Line
  • Inside NuGet.CommandLine.3.5.0 look for a folder named tools. tools
  • Inside tools you will get your nuget.exe nuget.exe

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Works for generator-aspnetcore-spa and bootstrap 4.

// ===== file: webpack.config.vendor.js =====    
module.exports = (env) => {
...
    plugins: [
        new webpack.ProvidePlugin({ $: 'jquery', 
                                    jQuery: 'jquery',
                                    'window.jQuery': 'jquery',
                                    'window.Tether': 'tether',
                                    tether: 'tether', 
                                    Tether: 'tether' }), 
// Maps these identifiers to the jQuery package 
// (because Bootstrap expects it to be a global variable)
            ...
        ]
};

Nesting queries in SQL

You need to join the two tables and then filter the result in where clause:

SELECT country.name as country, country.headofstate 
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'

Angular 2 - innerHTML styling

We pull in content frequently from our CMS as [innerHTML]="content.title". We place the necessary classes in the application's root styles.scss file rather than in the component's scss file. Our CMS purposely strips out in-line styles so we must have prepared classes that the author can use in their content. Remember using {{content.title}} in the template will not render html from the content.

Which HTML elements can receive focus?

The ally.js accessibility library provides an unofficial, test-based list here:

https://allyjs.io/data-tables/focusable.html

(NB: Their page doesn't say how often tests were performed.)

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

Turn off iPhone/Safari input element rounding

On iOS 5 and later:

input {
  border-radius: 0;
}

input[type="search"] {
  -webkit-appearance: none;
}

If you must only remove the rounded corners on iOS or otherwise for some reason cannot normalize rounded corners across platforms, use input { -webkit-border-radius: 0; } property instead, which is still supported. Of course do note that Apple can choose to drop support for the prefixed property at any time, but considering their other platform-specific CSS features chances are they'll keep it around.

On legacy versions you had to set -webkit-appearance: none instead:

input {
    -webkit-appearance: none;
}

What exactly is Spring Framework for?

Spring is a good alternative to Enterprise JavaBeans (EJB) technology. It also has web framework and web services framework component.

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

You need to place google-services.json into app/ dir. And for each build type, there should be accordant director in app/src folder.

For example, if you have release and debug:

app/google-services.json
app/src/debug/google-services.json

In all google-services.json files you should specify correct package_name according to build type.

For example, inside debug dir it should be like {com.myapp}.debug

Fitting polynomial model to data in R

The easiest way to find the best fit in R is to code the model as:

lm.1 <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + ...)

After using step down AIC regression

lm.s <- step(lm.1)

Reading CSV files using C#

CSV can get complicated real fast.

Use something robust and well-tested:
FileHelpers: www.filehelpers.net

The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.

Is JavaScript's "new" keyword considered harmful?

Javascript being dynamic language there a zillion ways to mess up where another language would stop you.

Avoiding a fundamental language feature such as new on the basis that you might mess up is a bit like removing your shiny new shoes before walking through a minefield just in case you might get your shoes muddy.

I use a convention where function names begin with a lower case letter and 'functions' that are actually class definitions begin with a upper case letter. The result is a really quite compelling visual clue that the 'syntax' is wrong:-

var o = MyClass();  // this is clearly wrong.

On top of this good naming habits help. After all functions do things and therefore there should be a verb in its name whereas classes represent objects and are nouns and adjectives with no verb.

var o = chair() // Executing chair is daft.
var o = createChair() // makes sense.

Its interesting how SO's syntax colouring has interpretted the code above.

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

A C# version of Miroslav Zadravec's code

for (int i = 0; i < dataGridView1.Columns.Count-1; i++)
{
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
dataGridView1.Columns[dataGridView1.Columns.Count - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    int colw = dataGridView1.Columns[i].Width;
    dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dataGridView1.Columns[i].Width = colw;
}

Posted as Community Wiki so as to not mooch off of the reputation of others

Address validation using Google Maps API

A great blog describing 14 address finders: https://www.conversion-uplift.co.uk/free-address-lookup-tools/

Many address autocomplete services, including Google's Places API, appears to offer international address support but it has limited accuracy.

For example, New Zealand address and geolocation data are free to download from Land Information New Zealand (LINZ). When a user search for an address such as 76 Francis St Hauraki from Google or Address Doctor, a positive match is returned. The land parcel was matched but not the postal/delivery address, which is either 76A or 76B. The problem is amplified with apartments and units on a single land parcel.

For 100% accuracy, use a country-specific address finder instead such as https://www.addy.co.nz for NZ address autocomplete.

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

ascending/descending in LINQ - can one change the order via parameter?

What about ordering desc by the desired property,

   blah = blah.OrderByDescending(x => x.Property);

And then doing something like

  if (!descending)
  {
       blah = blah.Reverse()
  }
  else
  {
      // Already sorted desc ;)
  }

Is it Reverse() too slow?

How can I use delay() with show() and hide() in Jquery

Why don't you try the fadeIn() instead of using a show() with delay(). I think what you are trying to do can be done with this. Here is the jQuery code for fadeIn and FadeOut() which also has inbuilt method for delaying the process.

$(document).ready(function(){
   $('element').click(function(){
      //effects take place in 3000ms
      $('element_to_hide').fadeOut(3000);
      $('element_to_show').fadeIn(3000);
   });
}

Graph visualization library in JavaScript

JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.

prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.

Save PHP variables to a text file

Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)

How to solve SyntaxError on autogenerated manage.py?

The error is generated by using a later version of Django with an old python, probably of version 2.x.

To fix this I had to delete the .venv folder and recreate it with virtualenv -p python3 .venv && source .venv/bin/activate

how to compare the Java Byte[] array?

There's a faster way to do that:

Arrays.hashCode(arr1) == Arrays.hashCode(arr2)

npm can't find package.json

If Googling "no such file or directory package.json" sent you here, then you might be using a very old version of Node.js

The following page has good instructions of how to easily install the latest stable on many Operating systems and distros:

https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager

What does (function($) {})(jQuery); mean?

Type 3, in order to work would have to look like this:

(function($){
    //Attach this new method to jQuery
    $.fn.extend({     
        //This is where you write your plugin's name
        'pluginname': function(_options) {
            // Put defaults inline, no need for another variable...
            var options =  $.extend({
                'defaults': "go here..."
            }, _options);

            //Iterate over the current set of matched elements
            return this.each(function() {

                //code to be inserted here

            });
        }
    }); 
})(jQuery);

I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.

Get product id and product type in magento?

IN MAGENTO query in the database and fetch the result like. product id, product name and manufracturer with out using the product flat table use the eav catalog_product_entity and its attribute table product_id product_name manufacturer 1 | PRODUCTA | NOKIA 2 | PRODUCTB | SAMSUNG

What is difference between Errors and Exceptions?

In general error is which nobody can control or guess when it occurs.Exception can be guessed and can be handled. In Java Exception and Error are sub class of Throwable.It is differentiated based on the program control.Error such as OutOfMemory Error which no programmer can guess and can handle it.It depends on dynamically based on architectire,OS and server configuration.Where as Exception programmer can handle it and can avoid application's misbehavior.For example if your code is looking for a file which is not available then IOException is thrown.Such instances programmer can guess and can handle it.

How to replace multiple white spaces with one white space

There is no way built in to do this. You can try this:

private static readonly char[] whitespace = new char[] { ' ', '\n', '\t', '\r', '\f', '\v' };
public static string Normalize(string source)
{
   return String.Join(" ", source.Split(whitespace, StringSplitOptions.RemoveEmptyEntries));
}

This will remove leading and trailing whitespce as well as collapse any internal whitespace to a single whitespace character. If you really only want to collapse spaces, then the solutions using a regular expression are better; otherwise this solution is better. (See the analysis done by Jon Skeet.)

Adding one day to a date

The modify() method that can be used to add increments to an existing DateTime value.

Create a new DateTime object with the current date and time:

$due_dt = new DateTime();

Once you have the DateTime object, you can manipulate its value by adding or subtracting time periods:

$due_dt->modify('+1 day');

You can read more on the PHP Manual.

Illegal character in path at index 16

I ran into the same thing with the Bing Map API. URLEncoder just made things worse, but a replaceAll(" ","%20"); did the trick.

There is no argument given that corresponds to the required formal parameter - .NET Error

I got the same error but it was due to me not creating a default constructor. If you haven't already tried that, create the default constructor like this:

public TestClass() {

}

tmux set -g mouse-mode on doesn't work

Just a quick heads-up to anyone else who is losing their mind right now:

https://github.com/tmux/tmux/blob/310f0a960ca64fa3809545badc629c0c166c6cd2/CHANGES#L12

so that's just

 :setw -g mouse

Convert sqlalchemy row object to python dict

I couldn't get a good answer so I use this:

def row2dict(row):
    d = {}
    for column in row.__table__.columns:
        d[column.name] = str(getattr(row, column.name))

    return d

Edit: if above function is too long and not suited for some tastes here is a one liner (python 2.7+)

row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns}

How to scroll to top of a div using jQuery?

Use the following function

window.scrollTo(xpos, ypos)

Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels

ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

Difference between two lists

I think important to emphasize - using Except method will return you items who are in the first without the items in the second one only. It does not return those elements in second that do not appear in first.

var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };

var list3 = list1.Except(list2).ToList(); //list3 contains only 1, 2

But if you want get real difference between two lists:

Items who are in the first without the items in the second one and items who are in the second without the items in the first one.

You need using Except twice:

var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };

var list3 = list1.Except(list2); //list3 contains only 1, 2
var list4 = list2.Except(list1); //list4 contains only 6, 7
var resultList = list3.Concat(list4).ToList(); //resultList contains 1, 2, 6, 7

Or you can use SymmetricExceptWith method of HashSet. But it changes the set on which called:

var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };

var list1Set = list1.ToHashSet(); //.net framework 4.7.2 and .net core 2.0 and above otherwise new HashSet(list1)
list1Set.SymmetricExceptWith(list2);
var resultList = list1Set.ToList(); //resultList contains 1, 2, 6, 7

Can I call a base class's virtual function if I'm overriding it?

Just in case you do this for a lot of functions in your class:

class Foo {
public:
  virtual void f1() {
    // ...
  }
  virtual void f2() {
    // ...
  }
  //...
};

class Bar : public Foo {
private:
  typedef Foo super;
public:
  void f1() {
    super::f1();
  }
};

This might save a bit of writing if you want to rename Foo.

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

How to obtain the chat_id of a private Telegram channel?

I found the way to write in private channels.

  1. You should convert it to public with some @channelName
  2. Send message to this channel through Bot API

    https://api.telegram.org/bot111:222/sendMessage?chat_id=@channelName&text=123

  3. As response you will get info with chat_id of your channel.

    { "ok" : true, "result" : { "chat" : { "id" : -1001005582487, "title" : "Test Private Channel", "type" : "channel" }, "date" : 1448245538, "message_id" : 7, "text" : "123ds" } }

  4. Now you can convert Channel back to private (by deleting channel's link) and send message directly to this chat_id "-1001005582487"

    https://api.telegram.org/bot111:222/sendMessage?chat_id=-1001005582487&text=123

Catch checked change event of a checkbox

Use the :checked selector to determine the checkbox's state:

$('input[type=checkbox]').click(function() {
    if($(this).is(':checked')) {
        ...
    } else {
        ...
    }
});

Access HTTP response as string in Go

string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.

remove double quotes from Json return data using Jquery

Use replace:

var test = "\"House\"";
console.log(test);
console.log(test.replace(/\"/g, ""));  

// "House"
// House

Note the g on the end means "global" (replace all).

jQuery get values of checked checkboxes into array

Call .get() at the very end to turn the resulting jQuery object into a true array.

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
      return $(this).val();
    }).get(); // <----
    console.log(searchIDs);
});

Per the documentation:

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.

WebService Client Generation Error with JDK8

When using Maven with IntelliJ IDE you can add -Djavax.xml.accessExternalSchema=all to Maven setting under JVM Options for Maven Build Tools Runner configuration

Oracle query to fetch column names

the point is that in toad u have to write table name capital, like this:

select *
FROM all_tab_columns
where table_name like 'IDECLARATION';

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

Redirect stderr and stdout in Bash

LOG_FACILITY="local7.notice"
LOG_TOPIC="my-prog-name"
LOG_TOPIC_OUT="$LOG_TOPIC-out[$$]"
LOG_TOPIC_ERR="$LOG_TOPIC-err[$$]"

exec 3>&1 > >(tee -a /dev/fd/3 | logger -p "$LOG_FACILITY" -t "$LOG_TOPIC_OUT" )
exec 2> >(logger -p "$LOG_FACILITY" -t "$LOG_TOPIC_ERR" )

It is related: Writing stdOut & stderr to syslog.

It almost work, but not from xinted ;(

How to display a json array in table format?

using jquery $.each you can access all data and also set in table like this

<table style="width: 100%">
     <thead>
          <tr>
               <th>Id</th>
               <th>Name</th>
               <th>Category</th>
               <th>Color</th>
           </tr>
     </thead>
     <tbody id="tbody">
     </tbody>
</table>

$.each(data, function (index, item) {
     var eachrow = "<tr>"
                 + "<td>" + item[1] + "</td>"
                 + "<td>" + item[2] + "</td>"
                 + "<td>" + item[3] + "</td>"
                 + "<td>" + item[4] + "</td>"
                 + "</tr>";
     $('#tbody').append(eachrow);
});

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How does the Python's range function work?

A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.

This code:

for i in range(5):
    print i

can be thought of working like this:

i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.

I assume that when you say "call a, it gives only 5", you mean like this:

for i in range(5):
    a=i+1
print a

this will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.

Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.

I hope this answered your question.

Disable building workspace process in Eclipse

For anyone running into a problem where build automatically is unchecked but the project is still building. Make sure your project isn't deployed to the server in the server tab and told to stay synchronous.

How to have multiple CSS transitions on an element?

Something like the following will allow for multiple transitions simultaneously:

-webkit-transition: color .2s linear, text-shadow .2s linear;
   -moz-transition: color .2s linear, text-shadow .2s linear;
     -o-transition: color .2s linear, text-shadow .2s linear;
        transition: color .2s linear, text-shadow .2s linear;

Example: http://jsbin.com/omogaf/2

Convert xlsx to csv in Linux with command line

You can do this with LibreOffice:

libreoffice --headless --convert-to csv $filename --outdir $outdir

For reasons not clear to me, you might need to run this with sudo. You can make LibreOffice work with sudo without requiring a password by adding this line to you sudoers file:

users ALL=(ALL) NOPASSWD: libreoffice

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Swift 3 Bonus: Why didn't anyone mention the short form?

CGRect(origin: .zero, size: size)

.zero instead of CGPoint.zero

When the type is defined, you can safely omit it.

How to check syslog in Bash on Linux?

How about less /var/log/syslog?

How can I specify a branch/tag when adding a Git submodule?

In my experience switching branches in the superproject or future checkouts will still cause detached HEADs of submodules regardless if the submodule is properly added and tracked (i.e. @djacobs7 and @Johnny Z answers).

And instead of manually checking out the correct branch manually or through a script git submodule foreach can be used.

This will check the submodule config file for the branch property and checkout the set branch.

git submodule foreach -q --recursive 'branch="$(git config -f <path>.gitmodules submodule.$name.branch)"; git checkout $branch'

Set background color in PHP?

You can use php in the style sheet. Just remember to set header("Content-type: text/css") in the style.php (or whatever then name is) file

Testing socket connection in Python

It seems that you catch not the exception you wanna catch out there :)

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you're catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.

SyntaxError: missing ) after argument list

For me, once there was a mistake in spelling of function

For e.g. instead of

$(document).ready(function(){

});

I wrote

$(document).ready(funciton(){

});

So keep that also in check

PHP max_input_vars

You need to uncomment max_input_vars value in php.ini file and increase it (exp. 2000), also dont forget to restart your server this will help for 99,99%.

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

Remove characters from a String in Java

This will safely remove only if token is at end of string.

StringUtils.removeEnd(string, ".xml");

Apache StringUtils functions are null-, empty-, and no match- safe

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

How to get the position of a character in Python?

A character might appear multiple times in a string. For example in a string sentence, position of e is 1, 4, 7 (because indexing usually starts from zero). but what I find is both of the functions find() and index() returns first position of a character. So, this can be solved doing this:

def charposition(string, char):
    pos = [] #list to store positions for each 'char' in 'string'
    for n in range(len(string)):
        if string[n] == char:
            pos.append(n)
    return pos

s = "sentence"
print(charposition(s, 'e')) 

#Output: [1, 4, 7]

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Bootstrap table striped: How do I change the stripe background colour?

I found this checkerboard pattern (as a subset of the zebra stripe) to be a pleasant way to display a two-column table. This is written using LESS CSS, and keys all colors off the base color.

@base-color: #0000ff;
@row-color: lighten(@base-color, 40%);    
@other-row: darken(@row-color, 10%);

tbody {
    td:nth-child(odd) { width: 45%; }
    tr:nth-child(odd) > td:nth-child(odd) {
        background: darken(@row-color, 0%); }
    tr:nth-child(odd) > td:nth-child(even) {
        background: darken(@row-color, 7%); }
    tr:nth-child(even) > td:nth-child(odd) {
        background: darken(@other-row, 0%); }
    tr:nth-child(even) > td:nth-child(even) {
        background: darken(@other-row, 7%); }
}

Note I've dropped the .table-striped, but doesn't seem to matter.

Looks like: enter image description here

How can I do an OrderBy with a dynamic string parameter?

In one answer above:

The simplest & the best solution:

mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));

There is an syntax error, ,null must be added:

mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s,null));

How to use filter, map, and reduce in Python 3

The functionality of map and filter was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in functools.reduce.

So, for filter and map, you can wrap them with list() to see the results like you did before.

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> import functools
>>> def add(x,y): return x+y
...
>>> functools.reduce(add, range(1, 11))
55
>>>

The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions. Example:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> [i for i in range(2, 25) if f(i)]
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> [cube(i) for i in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>

They say that for loops are 99 percent of the time easier to read than reduce, but I'd just stick with functools.reduce.

Edit: The 99 percent figure is pulled directly from the What’s New In Python 3.0 page authored by Guido van Rossum.

Creating hard and soft links using PowerShell

I wrote a PowerShell module that has native wrappers for MKLINK. https://gist.github.com/2891103

Includes functions for:

  • New-Symlink
  • New-HardLink
  • New-Junction

Captures the MKLINK output and throws proper PowerShell errors when necessary.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx

There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803

SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:

SELECT CAST(N'±' as varbinary(10)) AS Result

This will return 0xB100 which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.

If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.

You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY instead of VARCHAR so the SQL Server transformation is not invalidated by the client before it is presented:

SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName

This will get you 0xF1 or 0xB1 respectively if columnName contains just the character '±'

You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.

Please double check the actual internal representation of your character by casting the query to VARBINARY on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2

SELECT CAST(columnName as varbinary(10)) from tableName

Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.

All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.

I/O error(socket error): [Errno 111] Connection refused

Its seems that server is not running properly so ensure that with terminal by

telnet ip port

example

telnet localhost 8069

It will return connected to localhost so it indicates that there is no problem with the connection Else it will return Connection refused it indicates that there is problem with the connection

What is the best workaround for the WCF client `using` block issue?

I used Castle dynamic proxy to solve the Dispose() issue, and also implemented auto-refreshing the channel when it is in an unusable state. To use this you must create a new interface that inherits your service contract and IDisposable. The dynamic proxy implements this interface and wraps a WCF channel:

Func<object> createChannel = () =>
    ChannelFactory<IHelloWorldService>
        .CreateChannel(new NetTcpBinding(), new EndpointAddress(uri));
var factory = new WcfProxyFactory();
var proxy = factory.Create<IDisposableHelloWorldService>(createChannel);
proxy.HelloWorld();

I like this since you can inject WCF services without consumers needing to worry about any details of WCF. And there's no added cruft like the other solutions.

Have a look at the code, it's actually pretty simple: WCF Dynamic Proxy

SQL - Update multiple records in one query

INSERT INTO tablename
    (name, salary)
    VALUES 
        ('Bob', 1125),
        ('Jane', 1200),
        ('Frank', 1100),
        ('Susan', 1175),
        ('John', 1150)
        ON DUPLICATE KEY UPDATE salary = VALUES(salary);