Programs & Examples On #Codebeside

Seconds CountDown Timer

You need a public class for Form1 to initialize.

See this code:

namespace TimerApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private int counter = 60;
        private void button1_Click(object sender, EventArgs e)
        {
            //Insert your code from before
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //Again insert your code
        }
    }
}

I've tried this and it all worked fine

If you need anymore help feel free to comment :)

How can I alter a primary key constraint using SQL syntax?

you can rename constraint objects using sp_rename (as described in this answer)

for example:

EXEC sp_rename N'schema.MyIOldConstraint', N'MyNewConstraint'

angular2: how to copy object into another object

let copy = Object.assign({}, myObject).  as mentioned above

but this wont work for nested objects. SO an alternative would be

let copy =JSON.parse(JSON.stringify(myObject))

How to change the text of a label?

ASP.Net automatically generates unique client IDs for server-side controls.

Change it to

 $('#<%= lblVessel.ClientID %>')

In ASP.Net 4.0, you could also set the ClientIDMode property to Static instead.

What is the max size of VARCHAR2 in PL/SQL and SQL?

Not sure what you meant with "Can I increase the size of this variable without worrying about the SQL limit?". As long you do not try to insert a more than 4000 VARCHAR2 into a VARCHAR2 SQL column there is nothing to worry about.

Here is the exact reference (this is 11g but true also for 10g)

http://docs.oracle.com/cd/E11882_01/appdev.112/e17126/datatypes.htm

VARCHAR2 Maximum Size in PL/SQL: 32,767 bytes Maximum Size in SQL 4,000 bytes

Select from multiple tables without a join?

The UNION ALL operator may be what you are looking for.

With this operator, you can concatenate the resultsets from multiple queries together, preserving all of the rows from each. Note that a UNION operator (without the ALL keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).

The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.

SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
UNION ALL
SELECT 'q3', '1', '2', buckle, my_shoe FROM t4

You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows.

SELECT t.a
     , SUM(t.b)
     , AVG(t.c)
  FROM (
         SELECT 'q1' AS source, a, b, c, d FROM t1
          UNION ALL
         SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
       ) t
 GROUP BY t.a
 ORDER BY t.a

How to clear an EditText on click?

Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        }
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        }
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setText("");
            et.setCompoundDrawables(null, null, null, null);
        }
        return false;
    }
});
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
});

java.net.SocketException: Software caused connection abort: recv failed

This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.

Difference between "\n" and Environment.NewLine

You might get into trouble when you try to display multi-line message separated with "\r\n".

It is always a good practice to do things in a standard way, and use Environment.NewLine

T-SQL Cast versus Convert

To expand on the above answercopied by Shakti, I have actually been able to measure a performance difference between the two functions.

I was testing performance of variations of the solution to this question and found that the standard deviation and maximum runtimes were larger when using CAST.

Runtimes in milliseconds *Times in milliseconds, rounded to nearest 1/300th of a second as per the precision of the DateTime type

How to parse JSON boolean value?

Try this:

{
    "ACCOUNT_EXIST": true,
    "MultipleContacts": false
}

boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()

JavaScript checking for null vs. undefined and difference between == and ===

undefined

It means the variable is not yet intialized .

Example :

var x;
if(x){ //you can check like this
   //code.
}

equals(==)

It only check value is equals not datatype .

Example :

var x = true;
var y = new Boolean(true);
x == y ; //returns true

Because it checks only value .

Strict Equals(===)

Checks the value and datatype should be same .

Example :

var x = true;
var y = new Boolean(true);
x===y; //returns false.

Because it checks the datatype x is a primitive type and y is a boolean object .

NOT IN vs NOT EXISTS

If the optimizer says they are the same then consider the human factor. I prefer to see NOT EXISTS :)

ASP.NET set hiddenfield a value in Javascript

I will suggest you to use ClientID of HiddenField. first Register its client Id in any Javascript Variable from codebehind, then use it in clientside script. as:

.cs file code:

ClientScript.RegisterStartupScript(this.GetType(), "clientids", "var hdntxtbxTaksit=" + hdntxtbxTaksit.ClientID, true);

and then use following code in JS:

document.getElementById(hdntxtbxTaksit).value= ""; 

How can I check if a user is logged-in in php?

Any page you want to perform session-checks on needs to start with:

session_start();

From there, you check your session array for a variable indicating they are logged in:

if (!$_SESSION["loggedIn"]) redirect_to_login();

Logging them in is nothing more than setting that value:

$_SESSION["loggedIn"] = true;

Android ListView Text Color

I needed to make a ListView with items of different colors. I modified Shardul's method a bit and result in this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorString) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setBackgroundColor(assignBackgroundColor(position));
                textView.setTextColor(assignTextColor(position));
                return textView;
            }
        };
        colorList.setAdapter(adapter);

assignBackgroundColor() and assignTextColor() are methods that assign color you want. They can be replaced with int[] arrays.

What are the specific differences between .msi and setup.exe file?

MSI is basically an installer from Microsoft that is built into windows. It associates components with features and contains installation control information. It is not necessary that this file contains actual user required files i.e the application programs which user expects. MSI can contain another setup.exe inside it which the MSI wraps, which actually contains the user required files.

Hope this clears you doubt.

Angular: conditional class with *ngClass

You can use [ngClass] or [class.classname], both will work the same.
[class.my-class]="step==='step1'"

   OR

[ngClass]="{'my-class': step=='step1'}"

Both will work the same!

How to drop SQL default constraint without knowing its name?

Expanding on Mitch Wheat's code, the following script will generate the command to drop the constraint and dynamically execute it.

declare @schema_name nvarchar(256)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
declare @Command  nvarchar(1000)

set @schema_name = N'MySchema'
set @table_name = N'Department'
set @col_name = N'ModifiedDate'

select @Command = 'ALTER TABLE ' + @schema_name + '.[' + @table_name + '] DROP CONSTRAINT ' + d.name
 from sys.tables t
  join sys.default_constraints d on d.parent_object_id = t.object_id
  join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id
 where t.name = @table_name
  and t.schema_id = schema_id(@schema_name)
  and c.name = @col_name

--print @Command

execute (@Command)

Show all current locks from get_lock

Reference taken from this post:

You can also use this script to find lock in MySQL.

SELECT 
    pl.id
    ,pl.user
    ,pl.state
    ,it.trx_id 
    ,it.trx_mysql_thread_id 
    ,it.trx_query AS query
    ,it.trx_id AS blocking_trx_id
    ,it.trx_mysql_thread_id AS blocking_thread
    ,it.trx_query AS blocking_query
FROM information_schema.processlist AS pl 
INNER JOIN information_schema.innodb_trx AS it
    ON pl.id = it.trx_mysql_thread_id
INNER JOIN information_schema.innodb_lock_waits AS ilw
    ON it.trx_id = ilw.requesting_trx_id 
        AND it.trx_id = ilw.blocking_trx_id

How to PUT a json object with an array using curl

Although the original post had other issues (i.e. the missing "-d"), the error message is more generic.

curl: (3) [globbing] nested braces not supported at pos X

This is because curly braces {} and square brackets [] are special globbing characters in curl. To turn this globbing off, use the "-g" option.

As an example, the following Solr facet query will fail without the "-g" to turn off curl globbing: curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'

Excel Macro : How can I get the timestamp in "yyyy-MM-dd hh:mm:ss" format?

DateTime.Now returns a value of data type Date. Date variables display dates according to the short date format and time format set on your computer.

They may be formatted as a string for display in any valid date format by the Format function as mentioned in aother answers

Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")

Escaping a forward slash in a regular expression

Here are a few options:

  • In Perl, you can choose alternate delimiters. You're not confined to m//. You could choose another, such as m{}. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{} is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, // and {} seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...), m[...], and m!...!.

  • In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/ for example (using an alternate delimiter that could become m{/[^/]+$}, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.

C++ cast to derived class

First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast or return NULL pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:

DerivedType m_derivedType = m_baseType;

Here there is no casting. You are creating a new object of type DerivedType and try to initialize it with value of m_baseType variable.

Next line is not much better:

DerivedType m_derivedType = (DerivedType)m_baseType;

Here you are creating a temporary of DerivedType type initialized with m_baseType value.

The last line

DerivedType * m_derivedType = (DerivedType*) & m_baseType;

should compile provided that BaseType is a direct or indirect public base class of DerivedType. It has two flaws anyway:

  1. You use deprecated C-style cast. The proper way for such casts is
    static_cast<DerivedType *>(&m_baseType)
  2. The actual type of casted object is not of DerivedType (as it was defined as BaseType m_baseType; so any use of m_derivedType pointer will result in undefined behaviour.

Apply global variable to Vuejs

Just Adding Instance Properties

For example, all components can access a global appName, you just write one line code:

Vue.prototype.$appName = 'My App'

$ isn't magic, it's a convention Vue uses for properties that are available to all instances.

Alternatively, you can write a plugin that includes all global methods or properties.

How to parse date string to Date?

I had this issue, and I set the Locale to US, then it work.

static DateFormat visitTimeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US);

for String "Sun Jul 08 00:06:30 UTC 2012"

Python os.path.join() on a list

It's just the method. You're not missing anything. The official documentation shows that you can use list unpacking to supply several paths:

s = "c:/,home,foo,bar,some.txt".split(",")
os.path.join(*s)

Note the *s intead of just s in os.path.join(*s). Using the asterisk will trigger the unpacking of the list, which means that each list argument will be supplied to the function as a separate argument.

PostgreSQL: how to convert from Unix epoch to date?

On Postgres 10:

SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)

How do you use bcrypt for hashing passwords in PHP?

You'll get a lot of information in Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes or Portable PHP password hashing framework.

The goal is to hash the password with something slow, so someone getting your password database will die trying to brute force it (a 10 ms delay to check a password is nothing for you, a lot for someone trying to brute force it). Bcrypt is slow and can be used with a parameter to choose how slow it is.

Microsoft Azure: How to create sub directory in a blob container

As @Egon mentioned above, there is no real folder management in BLOB storage.

You can achieve some features of a file system using '/' in the file name, but this has many limitations (for example, what happen if you need to rename a "folder"?).

As a general rule, I would keep my files as flat as possible in a container, and have my application manage whatever structure I want to expose to the end users (for example manage a nested folder structure in my database, have a record for each file, referencing the BLOB using container-name and file-name).

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

There can be lots of methods to solve this problem, but here is simplest one:

GO to XAMPP-control and...

Run as administrator

That's all..

This is the Golden Point for any such Abnormality.

Concept behind the work

Actually all the services in Xampp need Ports dependency. What happens is, When there is no special powers given to xampp, it only look for some predefined ports to run those services. And, if in case, those ports are somehow already busy... eek! the service couldn't be started.

But if we give superpower to our Xampp-control (by running as administrator), it will somehow manage and for certainly on earth will run the services on the ports. And triumph! You made it.

Permanent tip for my dear Brother and Sisters

To do the efforts one and for all, follow these steps:

  • right-click on xampp-control.exe file and go to properties.
  • Go to Compatibility Tab.
  • In the settings below, choose the checkbox Run this program as an administrator.
  • Apply the changes. And you are done.

Now, every time you run the application, it will run with the Administrator status and You don't need to take care about the ports at all.

Git merge is not possible because I have unmerged files

The error message:

merge: remote/master - not something we can merge

is saying that Git doesn't recognize remote/master. This is probably because you don't have a "remote" named "remote". You have a "remote" named "origin".

Think of "remotes" as an alias for the url to your Git server. master is your locally checked-out version of the branch. origin/master is the latest version of master from your Git server that you have fetched (downloaded). A fetch is always safe because it will only update the "origin/x" version of your branches.

So, to get your master branch back in sync, first download the latest content from the git server:

git fetch

Then, perform the merge:

git merge origin/master

...But, perhaps the better approach would be:

git pull origin master

The pull command will do the fetch and merge for you in one step.

Get TimeZone offset value from TimeZone without TimeZone name

ZoneId here = ZoneId.of("Europe/Kiev");
ZonedDateTime hereAndNow = Instant.now().atZone(here);
String.format("%tz", hereAndNow);

will give you a standardized string representation like "+0300"

List comprehension vs. lambda + filter

An important difference is that list comprehension will return a list while the filter returns a filter, which you cannot manipulate like a list (ie: call len on it, which does not work with the return of filter).

My own self-learning brought me to some similar issue.

That being said, if there is a way to have the resulting list from a filter, a bit like you would do in .NET when you do lst.Where(i => i.something()).ToList(), I am curious to know it.

EDIT: This is the case for Python 3, not 2 (see discussion in comments).

Load a Bootstrap popover content with AJAX. Is this possible?

$("a[rel=popover]").each(function(){
        var thisPopover=$(this);
                var thisPopoverContent ='';
                if('you want a data inside an html div tag') {
                thisPopoverContent = $(thisPopover.attr('data-content-id')).html();
                }elseif('you want ajax content') {
                    $.get(thisPopover.attr('href'),function(e){
                        thisPopoverContent = e;
                    });
            }
        $(this).attr(   'data-original-title',$(this).attr('title') );
        thisPopover.popover({
            content: thisPopoverContent
        })
        .click(function(e) {
            e.preventDefault()
        });

    });

note that I used the same href tag and made it so that it doesn't change pages when clicked, this is a good thing for SEO and also if user doesn't have javascript!

change text of button and disable button in iOS

Hey Namratha, If you're asking about changing the text and enabled/disabled state of a UIButton, it can be done pretty easily as follows;

[myButton setTitle:@"Normal State Title" forState:UIControlStateNormal]; // To set the title
[myButton setEnabled:NO]; // To toggle enabled / disabled

If you have created the buttons in the Interface Builder and want to access them in code, you can take advantage of the fact that they are passed in as an argument to the IBAction calls:

- (IBAction) triggerActionWithSender: (id) sender;

This can be bound to the button and you’ll get the button in the sender argument when the action is triggered. If that’s not enough (because you need to access the buttons somewhere else than in the actions), declare an outlet for the button:

@property(retain) IBOutlet UIButton *someButton;

Then it’s possible to bind the button in IB to the controller, the NIB loading code will set the property value when loading the interface.

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

Uploading Files in ASP.net without using the FileUpload server control

You'll have to set the enctype attribute of the form to multipart/form-data; then you can access the uploaded file using the HttpRequest.Files collection.

git: can't push (unpacker error) related to permission issues

I use gitosis for managing this kind of stuff. Gitosis has a single user (usually called "git") that owns all the repositories, and it uses public-key-based access control to each repo. It might not suit your setup but is probably worth checking out (no pun intended).

Can I catch multiple Java exceptions in the same catch clause?

Not exactly before Java 7 but, I would do something like this:

Java 6 and before

try {
  //.....
} catch (Exception exc) {
  if (exc instanceof IllegalArgumentException || exc instanceof SecurityException || 
     exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {

     someCode();

  } else if (exc instanceof RuntimeException) {
     throw (RuntimeException) exc;     

  } else {
    throw new RuntimeException(exc);
  }

}



Java 7

try {
  //.....
} catch ( IllegalArgumentException | SecurityException |
         IllegalAccessException |NoSuchFieldException exc) {
  someCode();
}

TypeScript and field initializers

Update

Since writing this answer, better ways have come up. Please see the other answers below that have more votes and a better answer. I cannot remove this answer since it's marked as accepted.


Old answer

There is an issue on the TypeScript codeplex that describes this: Support for object initializers.

As stated, you can already do this by using interfaces in TypeScript instead of classes:

interface Name {
    first: string;
    last: string;
}
class Person {
    name: Name;
    age: number;
}

var bob: Person = {
    name: {
        first: "Bob",
        last: "Smith",
    },
    age: 35,
};

return string with first match Regex

You can do:

x = re.findall('\d+', text)
result = x[0] if len(x) > 0 else ''

Note that your question isn't exactly related to regex. Rather, how do you safely find an element from an array, if it has none.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

Here is the real life example

@Html.Grid(Model).Columns(columns =>
    {
           columns.Add()
                   .Encoded(false)
                   .Sanitized(false)
                   .SetWidth(10)
                   .Titled(string.Empty)
                   .RenderValueAs(x => @Html.ActionLink("Edit", "UserDetails", "Membership", null, null, "discount", new { @id = @x.Id }, new { @target = "_blank" }));

  }).WithPaging(200).EmptyText("There Are No Items To Display")

And the target page has TABS

<ul id="myTab" class="nav nav-tabs" role="tablist">

        <li class="active"><a href="#discount" role="tab" data-toggle="tab">Discount</a></li>
    </ul>

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

In Addition to Ben's Answer, You can try Below Queries as per your need

USE {database-name};  
GO  
-- Truncate the log by changing the database recovery model to SIMPLE.  
ALTER DATABASE {database-name}
SET RECOVERY SIMPLE;  
GO  
-- Shrink the truncated log file to 1 MB.  
DBCC SHRINKFILE ({database-file-name}, 1);  
GO  
-- Reset the database recovery model.  
ALTER DATABASE {database-name}
SET RECOVERY FULL;  
GO 

Update Credit @cema-sp

To find database file names use below query

select * from sys.database_files;

Hello World in Python

In python 3.x. you use

print("Hello, World")

In Python 2.x. you use

print "Hello, World!"

Format a Go string without printing?

I've created go project for string formatting from template (it allow to format strings in C# or Python style, just first version for very simple cases), you could find it here https://github.com/Wissance/stringFormatter

it works in following manner:


func TestStrFormat(t *testing.T) {
    strFormatResult, err := Format("Hello i am {0}, my age is {1} and i am waiting for {2}, because i am {0}!",
                              "Michael Ushakov (Evillord666)", "34", "\"Great Success\"")
    assert.Nil(t, err)
    assert.Equal(t, "Hello i am Michael Ushakov (Evillord666), my age is 34 and i am waiting for \"Great Success\", because i am Michael Ushakov (Evillord666)!", strFormatResult)

    strFormatResult, err = Format("We are wondering if these values would be replaced : {5}, {4}, {0}", "one", "two", "three")
    assert.Nil(t, err)
    assert.Equal(t, "We are wondering if these values would be replaced : {5}, {4}, one", strFormatResult)

    strFormatResult, err = Format("No args ... : {0}, {1}, {2}")
    assert.Nil(t, err)
    assert.Equal(t, "No args ... : {0}, {1}, {2}", strFormatResult)
}

func TestStrFormatComplex(t *testing.T) {
    strFormatResult, err := FormatComplex("Hello {user} what are you doing here {app} ?", map[string]string{"user":"vpupkin", "app":"mn_console"})
    assert.Nil(t, err)
    assert.Equal(t, "Hello vpupkin what are you doing here mn_console ?", strFormatResult)
}

Installing pip packages to $HOME folder

I would use virtualenv at your HOME directory.

$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...

You could then also alter ~/.(login|profile|bash_profile), whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install would be the one used by default.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

This would be the "arrow function expression" introduced in ECMAScript 6.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions

For historical purposes (if the wiki page changes later), it is:

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous.

How do I get the path of a process in Unix / Linux

pwdx <process id>

This command will fetch the process path from where it is executing.

center aligning a fixed position div

If you know the width is 400px this would be the easiest way to do it I guess.

 left: calc(50% - 200px);

How to get back Lost phpMyAdmin Password, XAMPP

There is a batch file called resetroot.bat located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin passwords. Then all you need to do is start the MySQL service in xamp and click the admin button.

Java: unparseable date exception

From Oracle docs, Date.toString() method convert Date object to a String of the specific form - do not use toString method on Date object. Try to use:

String stringDate = new SimpleDateFormat(YOUR_STRING_PATTERN).format(yourDateObject);

Next step is parse stringDate to Date:

Date date = new SimpleDateFormat(OUTPUT_PATTERN).parse(stringDate);

Note that, parse method throws ParseException

Biggest differences of Thrift vs Protocol Buffers?

They both offer many of the same features; however, there are some differences:

  • Thrift supports 'exceptions'
  • Protocol Buffers have much better documentation/examples
  • Thrift has a builtin Set type
  • Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift
  • I find Protocol Buffers much easier to read

Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read).

Convert Bitmap to File

Converting Bitmap to File needs to be done in background (NOT IN THE MAIN THREAD) it hangs the UI specially if the bitmap was large

File file;

public class fileFromBitmap extends AsyncTask<Void, Integer, String> {

    Context context;
    Bitmap bitmap;
    String path_external = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";

    public fileFromBitmap(Bitmap bitmap, Context context) {
        this.bitmap = bitmap;
        this.context= context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // before executing doInBackground
        // update your UI
        // exp; make progressbar visible
    }

    @Override
    protected String doInBackground(Void... params) {

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
        try {
            FileOutputStream fo = new FileOutputStream(file);
            fo.write(bytes.toByteArray());
            fo.flush();
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        // back to main thread after finishing doInBackground
        // update your UI or take action after
        // exp; make progressbar gone

         sendFile(file);

    }
}

Calling it

new fileFromBitmap(my_bitmap, getApplicationContext()).execute();

you MUST use the file in onPostExecute .

To change directory of file to be stored in cache replace line :

 file = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");

with :

file  = new File(context.getCacheDir(), "temporary_file.jpg");

Full examples of using pySerial package

http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/

#!/usr/bin/python

import serial, time
#initialization and open the port

#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 1            #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():

    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                 #and discard all that is in buffer

        #write data
        ser.write("AT+CSQ")
        print("write data: AT+CSQ")

       time.sleep(0.5)  #give the serial port sometime to receive the data

       numOfLines = 0

       while True:
          response = ser.readline()
          print("read data: " + response)

        numOfLines = numOfLines + 1

        if (numOfLines >= 5):
            break

        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

Console.log not working at all

In my case I was developing a Polymer WebComponent, which is included using <link rel="import"> into the main HTML document. Turns out that the WebComponent HTML file was being cached for some reason, even though I had changed it since the cached version.

To solve it I opened the Developer Console (in Chrome), right clicked on the reload arrow next to the URL bar and selected "Empty cache and hard reload" - problem solved.

Clear dropdownlist with JQuery

<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>
</select>

<input type="submit" id="btn_submit" value="click me"/>



<script>
$('#btn_submit').on('click',function(){
      $('#ddlvalue').val(0);
});
</script>

Installing MySQL-python

this worked for me on python 3

pip install mysqlclient

How to convert integer to char in C?

To convert integer to char only 0 to 9 will be converted. As we know 0's ASCII value is 48 so we have to add its value to the integer value to convert in into the desired character hence

int i=5;
char c = i+'0';

How to print a two dimensional array?

You should loop by rows and then columns with a structure like

for ...row index...
  for ...column index...
    print

but I guess this is homework so just try it out yourself.

Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.

How to cat <<EOF >> a file containing code?

I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.

If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.

#!/bin/bash

FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""

cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}  
EOF

Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt

This can also be used to output blocks of text to the console with the same rules by omitting the file name

#!/bin/bash

VAR_EXAMPLE="\"string\""

cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console 
EOF

Will output "${VAR_EXAMPLE}="string" to console" to the console

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

How can I Convert HTML to Text in C#?

You could use this:

 public static string StripHTML(string HTMLText, bool decode = true)
        {
            Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
            var stripped = reg.Replace(HTMLText, "");
            return decode ? HttpUtility.HtmlDecode(stripped) : stripped;
        }

Updated

Thanks for the comments I have updated to improve this function

Oracle PL/SQL : remove "space characters" from a string

Since you're comfortable with regular expressions, you probably want to use the REGEXP_REPLACE function. If you want to eliminate anything that matches the [:space:] POSIX class

REGEXP_REPLACE( my_value, '[[:space:]]', '' )


SQL> ed
Wrote file afiedt.buf

  1  select '|' ||
  2         regexp_replace( 'foo ' || chr(9), '[[:space:]]', '' ) ||
  3         '|'
  4*   from dual
SQL> /

'|'||
-----
|foo|

If you want to leave one space in place for every set of continuous space characters, just add the + to the regular expression and use a space as the replacement character.

with x as (
  select 'abc 123  234     5' str
    from dual
)
select regexp_replace( str, '[[:space:]]+', ' ' )
  from x

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

Pandas: ValueError: cannot convert float NaN to integer

Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:

df['column_name'].astype(np.float).astype("Int32")

NB: You have to go through numpy float first and then to nullable Int32, for some reason.

The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.

Django, creating a custom 500/404 error page

Add these lines in urls.py

urls.py

from django.conf.urls import (
handler400, handler403, handler404, handler500
)

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

# ...

and implement our custom views in views.py.

views.py

from django.shortcuts import (
render_to_response
)
from django.template import RequestContext

# HTTP Error 400
def bad_request(request):
    response = render_to_response(
        '400.html',
        context_instance=RequestContext(request)
        )

        response.status_code = 400

        return response

# ...

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

I faced a similar issue when running SSH or Git Clone in Windows. Following findings helps to solve my problem:

  • When you run “rhc setup” or other ssh methods to generate ssh key, it will create the private key file id_rsa in .ssh folder in your home folder, default is C:\User\UserID
  • Git for windows has its own .ssh folder in its installation directory. When you run git/ssh, it will look for private key file id_rsa in this folder
  • Solved the problem by copying id_rsa from the home folder .ssh folder to the .ssh folder in the git installation directory

Also, I think there a way to “tell” git to use the default .ssh folder in home folder but still need to figure out how.

Imply bit with constant 1 or 0 in SQL Server

Enjoy this :) Without cast each value individually.

SELECT ...,
  IsCoursedBased = CAST(
      CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
    AS BIT
  )
FROM fc

Android Studio how to run gradle sync manually?

Android studio should have this button in the toolbar marked "Sync project with Gradle Files"

EDIT: I don't know when it was changed but it now looks like this:

enter image description here

EDIT: This is what it looks like on 3.3.1 enter image description here
OR by going to File -> Sync Project with Gradle Files from the menubar.

Does a valid XML file require an XML declaration?

Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.

Regular expression for exact match of a string

(?<![\w\d])abc(?![\w\d])

this makes sure that your match is not preceded by some character, number, or underscore and is not followed immediately by character or number, or underscore

so it will match "abc" in "abc", "abc.", "abc ", but not "4abc", nor "abcde"

Reference — What does this symbol mean in PHP?

== is used for check equality without considering variable data-type

=== is used for check equality for both the variable value and data-type

Example

$a = 5

  1. if ($a == 5) - will evaluate to true

  2. if ($a == '5') - will evaluate to true, because while comparing this both value PHP internally convert that string value into integer and then compare both values

  3. if ($a === 5) - will evaluate to true

  4. if ($a === '5') - will evaluate to false, because value is 5, but this value 5 is not an integer.

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

Running AMP (apache mysql php) on Android

On Google Play, PAW Server is the typical PHP server package ( contain Beanshell code ). You can put your webpages in the "html" folder. However, typical Beanshell code is not very familiar to be edited. On Android device, I recommend you to use SL4A and phpforandroid to build up Perl and PHP Server. Yet, they do not use MySQL as DATA base. You should be familiar with the Scripting Layer for Android (SL4A) platform. See this link for reference

How can I remove the search bar and footer added by the jQuery DataTables plugin?

I have done this by assigning footer an id and then styling using css :

    <table border="1" class="dataTable" id="dataTable_${dtoItem.key}" >
     <thead>
        <tr>
            <th></th>

        </tr>
    </thead>
 <tfoot>
    <tr>
            <th id="FooterHidden"></th>
    </tr>
</tfoot>
<tbody>

    <tr>

                <td class="copyableField"></td>

    </tr>
 </tbody>
</table>

then styling using css :

#FooterHidden{
   display: none;
}

As above mentioned ways aren't working for me.

JPA or JDBC, how are they different?

Main difference between JPA and JDBC is level of abstraction.

JDBC is a low level standard for interaction with databases. JPA is higher level standard for the same purpose. JPA allows you to use an object model in your application which can make your life much easier. JDBC allows you to do more things with the Database directly, but it requires more attention. Some tasks can not be solved efficiently using JPA, but may be solved more efficiently with JDBC.

how to fire event on file select

You could subscribe for the onchange event on the input field:

<input type="file" id="file" name="file" />

and then:

document.getElementById('file').onchange = function() {
    // fire the upload here
};

How do I get Maven to use the correct repositories?

Basically, all Maven is telling you is that certain dependencies in your project are not available in the central maven repository. The default is to look in your local .m2 folder (local repository), and then any configured repositories in your POM, and then the central maven repository. Look at the repositories section of the Maven reference.

The problem is that the project that was checked in didn't configure the POM in such a way that all the dependencies could be found and the project could be built from scratch.

How to convert string to binary?

a = list(input("Enter a string\t: "))
def fun(a):
    c =' '.join(['0'*(8-len(bin(ord(i))[2:]))+(bin(ord(i))[2:]) for i in a])
    return c
print(fun(a))

Scanner is skipping nextLine() after using next() or nextFoo()?

Use this code it will fix your problem.

System.out.println("Enter numerical value");    
int option;
option = input.nextInt(); // Read numerical value from input
input.nextLine();
System.out.println("Enter 1st string"); 
String string1 = input.nextLine(); // Read 1st string (this is skipped)
System.out.println("Enter 2nd string");
String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value)

Using NOT operator in IF conditions

As a general statement, its good to make your if conditionals as readable as possible. For your example, using ! is ok. the problem is when things look like

if ((a.b && c.d.e) || !f)

you might want to do something like

bool isOk = a.b;
bool isStillOk = c.d.e
bool alternateOk = !f

then your if statement is simplified to

if ( (isOk && isStillOk) || alternateOk)

It just makes the code more readable. And if you have to debug, you can debug the isOk set of vars instead of having to dig through the variables in scope. It is also helpful for dealing with NPEs -- breaking code out into simpler chunks is always good.

Adding elements to a C# array

The obvious suggestion would be to use a List<string> instead, which you will have already read from the other answers. This is definitely the best way in a real development scenario.

Of course, I want to make things more interesting (my day that is), so I will answer your question directly.

Here are a couple of functions that will Add and Remove elements from a string[]...

string[] Add(string[] array, string newValue){
    int newLength = array.Length + 1;

    string[] result = new string[newLength];

    for(int i = 0; i < array.Length; i++)
        result[i] = array[i];

    result[newLength -1] = newValue;

    return result;
}

string[] RemoveAt(string[] array, int index){
    int newLength = array.Length - 1;

    if(newLength < 1)
    {
        return array;//probably want to do some better logic for removing the last element
    }

    //this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way

    string[] result = new string[newLength];
    int newCounter = 0;
    for(int i = 0; i < array.Length; i++)
    {
        if(i == index)//it is assumed at this point i will match index once only
        {
            continue;
        }
        result[newCounter] = array[i];
        newCounter++;
    }  

    return result;
}

How to display loading message when an iFrame is loading?

You can use below code .

 iframe {background:url(../images/loader.gif) center center no-repeat; height: 100%;}

Android Studio - How to increase Allocated Heap Size

I looked at my Environment Variables and had a System Variable called _JAVA_OPTIONS with the value -Xms256m -Xmx512m, after changing this to -Xms256m -Xmx1024m the max heap size increased accordingly.

How do you get the current page number of a ViewPager for Android?

in the latest packages you can also use

vp.getCurrentItem()

or

vp is the viewPager ,

pageListener = new PageListener();
vp.setOnPageChangeListener(pageListener);

you have to put a page change listener for your viewPager. There is no method on viewPager to get the current page.

private int currentPage;

    private static class PageListener extends SimpleOnPageChangeListener{
            public void onPageSelected(int position) {
                Log.i(TAG, "page selected " + position);
                   currentPage = position;
        }
    }

The provider is not compatible with the version of Oracle client

Lots of theoretical answers here, but here comes a working example with code that you can copy and paste and test immediately:

  1. I installed the Oracle Express database OracleXE112 which already comes with some preinstalled demo tables.
  2. When you start the installer you are asked for a password. I entered "xxx" as password. (not used in production)
  3. My server runs on the machine 192.168.1.158
  4. On the server you must explicitely allow access for the process TNSLSNR.exe in the Windows Firewall. This process listens on port 1521. If you get a timeout error from the below code check your firewall.
  5. OPTION A: For C# (.NET2 or .NET4) you can download ODAC11, from which you have to add Oracle.DataAccess.dll to your project. Additionally this DLL depends on: OraOps11w.dll, oci.dll, oraociei11.dll (130MB!), msvcr80.dll. These DLLs must be in the same directory as the EXE or you must specify the DLL path in: HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.112.4.0\DllPath. On 64 bit machines write additionally to HKLM\SOFTWARE\Wow6432Node\Oracle\...
  6. OPTION B: If you have downloaded ODAC12 you need Oracle.DataAccess.dll, OraOps12w.dll, oci.dll, oraociei12.dll (160MB!), oraons.dll, msvcr100.dll. The Registry path is HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.121.2.0\DllPath
  7. OPTION C: If you don't want huge DLL's of more than 100 MB you should download ODP.NET_Managed12.x.x.x.xxxxx.zip in which you find Oracle.ManagedDataAccess.dll which is only 4 MB and is a pure managed DLL which works in 32 bit and 64 bit processes as well and depends on no other DLL and does not require any registry entries.
  8. The following C# code works for me without any configuration on the server side (just the default installation):
using Oracle.DataAccess.Client;
or
using Oracle.ManagedDataAccess.Client;

....

string oradb = "Data Source=(DESCRIPTION="
    + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.158)(PORT=1521)))"
    + "(CONNECT_DATA=(SERVER=DEDICATED)));"
    + "User Id=SYSTEM;Password=xxx;";

using (OracleConnection conn = new OracleConnection(oradb)) 
{
    conn.Open();
    using (OracleCommand cmd = new OracleCommand())
    {
        cmd.Connection  = conn;
        cmd.CommandText = "select TABLESPACE_NAME from DBA_DATA_FILES";

        using (OracleDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                listBox.Items.Add(dr["TABLESPACE_NAME"]);
            }
        }
    }
}

Giving multiple conditions in for loop in Java

You can also use "or" operator,

for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
  ...
}

Setting a WebRequest's body data

Update

See my other SO answer.


Original

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

You have to go to the sheet of db to get the first blank row, you could try this method.

Sub DesdeColombia ()    
  Dim LastRowFull As Long

  'Here we will define the first blank row in the column number 1 of sheet number 1:
  LastRowFull = Sheet1.Cells(Rows.Count,1).End(xlUp).Offset(1,0).Row

  'Now we are going to insert information
  Sheet1.Cells(LastRowFull, 1).Value = "We got it"    
End Sub

How do I convert an NSString value to NSData?

NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];

git - Server host key not cached

Solution with Plink

Save this python script to known_hosts.py:

#! /usr/bin/env python

# $Id$
# Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
# host keys.
#   usage:
#     kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg
#       Creates a Windows .REG file (double-click to install).
#     kh2reg.py --unix    known_hosts1 2 3 4 ... > sshhostkeys
#       Creates data suitable for storing in ~/.putty/sshhostkeys (Unix).
# Line endings are someone else's problem as is traditional.
# Developed for Python 1.5.2.

import fileinput
import base64
import struct
import string
import re
import sys
import getopt

def winmungestr(s):
    "Duplicate of PuTTY's mungestr() in winstore.c:1.10 for Registry keys"
    candot = 0
    r = ""
    for c in s:
        if c in ' \*?%~' or ord(c)<ord(' ') or (c == '.' and not candot):
            r = r + ("%%%02X" % ord(c))
        else:
            r = r + c
        candot = 1
    return r

def strtolong(s):
    "Convert arbitrary-length big-endian binary data to a Python long"
    bytes = struct.unpack(">%luB" % len(s), s)
    return reduce ((lambda a, b: (long(a) << 8) + long(b)), bytes)

def longtohex(n):
    """Convert long int to lower-case hex.

    Ick, Python (at least in 1.5.2) doesn't appear to have a way to
    turn a long int into an unadorned hex string -- % gets upset if the
    number is too big, and raw hex() uses uppercase (sometimes), and
    adds unwanted "0x...L" around it."""

    plain=string.lower(re.match(r"0x([0-9A-Fa-f]*)l?$", hex(n), re.I).group(1))
    return "0x" + plain

output_type = 'windows'

try:
    optlist, args = getopt.getopt(sys.argv[1:], '', [ 'win', 'unix' ])
    if filter(lambda x: x[0] == '--unix', optlist):
        output_type = 'unix'
except getopt.error, e:
    sys.stderr.write(str(e) + "\n")
    sys.exit(1)

if output_type == 'windows':
    # Output REG file header.
    sys.stdout.write("""REGEDIT4

[HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys]
""")

# Now process all known_hosts input.
for line in fileinput.input(args):

    try:
        # Remove leading/trailing whitespace (should zap CR and LF)
        line = string.strip (line)

        # Skip blanks and comments
        if line == '' or line[0] == '#':
            raise "Skipping input line"

        # Split line on spaces.
        fields = string.split (line, ' ')

        # Common fields
        hostpat = fields[0]
        magicnumbers = []   # placeholder
        keytype = ""        # placeholder

        # Grotty heuristic to distinguish known_hosts from known_hosts2:
        # is second field entirely decimal digits?
        if re.match (r"\d*$", fields[1]):

            # Treat as SSH-1-type host key.
            # Format: hostpat bits10 exp10 mod10 comment...
            # (PuTTY doesn't store the number of bits.)
            magicnumbers = map (long, fields[2:4])
            keytype = "rsa"

        else:

            # Treat as SSH-2-type host key.
            # Format: hostpat keytype keyblob64 comment...
            sshkeytype, blob = fields[1], base64.decodestring (fields[2])

            # 'blob' consists of a number of
            #   uint32    N (big-endian)
            #   uint8[N]  field_data
            subfields = []
            while blob:
                sizefmt = ">L"
                (size,) = struct.unpack (sizefmt, blob[0:4])
                size = int(size)   # req'd for slicage
                (data,) = struct.unpack (">%lus" % size, blob[4:size+4])
                subfields.append(data)
                blob = blob [struct.calcsize(sizefmt) + size : ]

            # The first field is keytype again, and the rest we can treat as
            # an opaque list of bignums (same numbers and order as stored
            # by PuTTY). (currently embedded keytype is ignored entirely)
            magicnumbers = map (strtolong, subfields[1:])

            # Translate key type into something PuTTY can use.
            if   sshkeytype == "ssh-rsa":   keytype = "rsa2"
            elif sshkeytype == "ssh-dss":   keytype = "dss"
            else:
                raise "Unknown SSH key type", sshkeytype

        # Now print out one line per host pattern, discarding wildcards.
        for host in string.split (hostpat, ','):
            if re.search (r"[*?!]", host):
                sys.stderr.write("Skipping wildcard host pattern '%s'\n"
                                 % host)
                continue
            elif re.match (r"\|", host):
                sys.stderr.write("Skipping hashed hostname '%s'\n" % host)
                continue
            else:
                m = re.match (r"\[([^]]*)\]:(\d*)$", host)
                if m:
                    (host, port) = m.group(1,2)
                    port = int(port)
                else:
                    port = 22
                # Slightly bizarre output key format: 'type@port:hostname'
                # XXX: does PuTTY do anything useful with literal IP[v4]s?
                key = keytype + ("@%d:%s" % (port, host))
                value = string.join (map (longtohex, magicnumbers), ',')
                if output_type == 'unix':
                    # Unix format.
                    sys.stdout.write('%s %s\n' % (key, value))
                else:
                    # Windows format.
                    # XXX: worry about double quotes?
                    sys.stdout.write("\"%s\"=\"%s\"\n"
                                     % (winmungestr(key), value))

    except "Unknown SSH key type", k:
        sys.stderr.write("Unknown SSH key type '%s', skipping\n" % k)
    except "Skipping input line":
        pass

Tested on Win7x64 and Python 2.7.

Then run:

ssh-keyscan -t rsa bitbucket.org >>~/.ssh/known_hosts
python --win known_hosts.py >known_hosts.reg
start known_hosts.reg

And choose to import into the registry. The keyscan will retrieve the public key for the domain (I had my problems with bitbucket), and then the python script will convert it to Plink format.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Lot's of great answer. I just want to add a small note about decoupling the stream.

cin.tie(NULL);

I have faced an issue while decoupling the stream with CodeChef platform. When I submitted my code, the platform response was "Wrong Answer" but after tying the stream and testing the submission. It worked.

So, If anyone wants to untie the stream, the output stream must be flushed.

Edit: I am not familiar with all the platform but this is what I have experienced.

What is a segmentation fault?

Segmentation fault occurs when a process (running instance of a program) is trying to access read-only memory address or memory range which is being used by other process or access the non-existent (invalid) memory address. Dangling Reference (pointer) problem means that trying to access an object or variable whose contents have already been deleted from memory, e.g:

int *arr = new int[20];
delete arr;
cout<<arr[1];  //dangling problem occurs here

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

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

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

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

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

How to send list of file in a folder to a txt file in Linux

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt

Laravel 5 route not defined, while it is?

Please note that the command

php artisan route:list

Or to get more filter down list

php artisan route:list | grep your_route|your_controller

the forth column tells you the names of routes that are registered (usually generated by Route::resource)

How to install mechanize for Python 2.7?

You need to follow the installation instructions and not just download the files into your Python27 directory. It has to be installed in the site-packages directory properly, which the directions tell you how to do.

ToList().ForEach in Linq

Try this:

foreach (var dept in employees.SelectMany(e => e.Departments))
{
   dept.SomeProperty = null;
   collection.Add(dept);
}

The view or its master was not found or no view engine supports the searched locations

In your LoginRegister action when returning the view, do below, i know this can be done in mvc 5, im not sure if in mvc 4 also.

 public ActionResult Index()
 {
     return View("~/Views/home/LoginRegister.cshtml");
 }

Will iOS launch my app into the background if it was force-quit by the user?

For iOS13

For background pushes in iOS13, you must set below parameters:

apns-priority = 5
apns-push-type = background
//Required for WatchOS
//Highly recommended for Other platforms 

Background PUSHES The video link: https://developer.apple.com/videos/play/wwdc2019/707/

Setting up a git remote origin

For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: https://help.github.com/articles/changing-a-remote-s-url/. Using git remote add to do this will result in "fatal: remote origin already exists."

Nutshell: git remote set-url origin https://github.com/username/repo

(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)

How to change background and text colors in Sublime Text 3

To view Theme files for ST3, install PackageResourceViewer via PackageControl.

Then, you can use the Ctrl + Shift + P >> PackageResourceViewer: Open Resource to view theme files.

To edit a specific background color, you need to create a new file in your user packages folder Packages/User/SublimeLinter with the same name as the theme currently applied to your sublime text file.

However, if your theme is a 3rd party theme package installed via package control, you can edit the hex value in that file directly, under background. For example:


<dict>
  <dict>
    <key>background</key>
    <string>#073642</string>
  </dict>
</dict>

Otherwise, if you are trying to modify a native sublime theme, add the following to the new file you create (named the same as the native theme, such as Monokai.sublime-color-scheme) with your color choice


{
  "globals":
  {
      "background": "rgb(5,5,5)"
  }
}

Then, you can open the file you wish the syntax / color to be applied to and then go to Syntax-Specific settings (under Preferences) and add the path of the file to the syntax specific settings file like so:


{
    "color_scheme": "Packages/User/SublimeLinter/Monokai.sublime-color-scheme"
}

Note that if you have installed a theme via package control, it probably has the .tmTheme file extension.

If you are wanting to edit the background color of the sidebar to be darker, go to Preferences > Theme > Adaptive.sublime-theme

This my answer based on my personal experience and info gleaned from the accepted answer on this page, if you'd like more information.

Iterate through 2 dimensional array

Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.

String string="";
for (int i = 0; i<array.length; i++){
    for (int j = 0; j<array[i].length; j++){
        string = string.concat(array[j][i]);
    } 
}
System.out.println(string)

Use jquery click to handle anchor onClick()

The HTML should look like:

<div class="solTitle"> <a href="#"  id="solution0">Solution0 </a></div>
<div class="solTitle"> <a href="#"  id="solution1">Solution1 </a></div>

<div id="summary_solution0" style="display:none" class="summary">Summary solution0</div>
<div id="summary_solution1" style="display:none" class="summary">Summary solution1</div>

And the javascript:

$(document).ready(function(){
    $(".solTitle a").live('click',function(e){
        var contentId = "summary_" + $(this).attr('id');
        $(".summary").hide();
        $("#" + contentId).show();
    });
});

See the Example: http://jsfiddle.net/kmendes/4G9UF/

Set a div width, align div center and text align left

All of these answers should suffice. However if you don't have a defined width, auto margins will not work.

I have found this nifty little trick to centre some of the more stubborn elements (Particularly images).

.div {
   position: absolute;
   left: 0;
   right: 0;
   margin-left: 0;
   margin-right: 0;
}

Contains method for a slice

I created a very simple benchmark with the solutions from these answers.

https://gist.github.com/NorbertFenk/7bed6760198800207e84f141c41d93c7

It isn't a real benchmark because initially, I haven't inserted too many elements but feel free to fork and change it.

How can I detect when the mouse leaves the window?

If you are using jQuery then how about this short and sweet code -

$(document).mouseleave(function () {
    console.log('out');
});

This event will trigger whenever the mouse is not in your page as you want. Just change the function to do whatever you want.

And you could also use:

$(document).mouseenter(function () {
    console.log('in');
});

To trigger when the mouse enters back to the page again.

Source: https://stackoverflow.com/a/16029966/895724

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Currently, Microsoft don't provide download option for '2007 Office System Driver: Data Connectivity Components' and click on first answer for '2007 Office System Driver: Data Connectivity Components' redirect to Cnet where getting download link creates confusion.

That's why who use SQL Server 2014 and latest version of SQL Server in Windows 10 click on below link for download this component which resolve your problem : - Microsoft Access Database Engine 2010

Happy Coding!

Using "If cell contains" in VBA excel

This does the same, enhanced with CONTAINS:

Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
     If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
        If xRet = "" Then
            xRet = LookupRange.Cells(I, ColumnNumber) & Char
        Else
            xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
        End If
    End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function

Load a WPF BitmapImage from a System.Drawing.Bitmap

Thanks to Hallgrim, here is the code I ended up with:

ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
   bmp.GetHbitmap(), 
   IntPtr.Zero, 
   System.Windows.Int32Rect.Empty, 
   BitmapSizeOptions.FromWidthAndHeight(width, height));

I also ended up binding to a BitmapSource instead of a BitmapImage as in my original question

Multi-dimensional arraylist or list in C#?

Not exactly. But you can create a list of lists:

var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
    var l = new List<int>();
    ll.Add(l);
}

What are access specifiers? Should I inherit with private, protected or public?

The explanation from Scott Meyers in Effective C++ might help understand when to use them:

Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

How do I mock a REST template exchange?

I used to get such an error. I found a more reliable solution. I have mentioned the import statements too which have worked for me. The below piece of code perfectly mocks restemplate.

import org.mockito.Matchers;
import static org.mockito.Matchers.any;

    HttpHeaders headers = new Headers();
    headers.setExpires(10000L);     
    ResponseEntity<String> responseEntity = new ResponseEntity<>("dummyString", headers, HttpStatus.OK);
    when(restTemplate.exchange( Matchers.anyString(), 
            Matchers.any(HttpMethod.class),
            Matchers.<HttpEntity<?>> any(), 
            Matchers.<Class<String>> any())).thenReturn(responseEntity);

How to remove jar file from local maven repository which was added with install:install-file?

Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/ directory if you are using a linux OS.

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

@brennanyoung's answer is great, but if you're wondering what to do in the failure case you could use an IP geolocation API such as https://ipinfo.io (which is my service). Here's an example:

function do_something(coords) {
    // Do something with the coords here
    // eg. show the user on a map, or customize
    // the site contents somehow
}

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

See https://ipinfo.io/developers/replacing-getcurrentposition for more details.

Android-java- How to sort a list of objects by a certain value within the object

You should use Comparable instead of a Comparator if a default sort is what your looking for.

See here, this may be of some help - When should a class be Comparable and/or Comparator?

Try this -

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestSort {

    public static void main(String args[]){

        ToSort toSort1 = new ToSort(new Float(3), "3");
        ToSort toSort2 = new ToSort(new Float(6), "6");
        ToSort toSort3 = new ToSort(new Float(9), "9");
        ToSort toSort4 = new ToSort(new Float(1), "1");
        ToSort toSort5 = new ToSort(new Float(5), "5");
        ToSort toSort6 = new ToSort(new Float(0), "0");
        ToSort toSort7 = new ToSort(new Float(3), "3");
        ToSort toSort8 = new ToSort(new Float(-3), "-3");

        List<ToSort> sortList = new ArrayList<ToSort>();
        sortList.add(toSort1);
        sortList.add(toSort2);
        sortList.add(toSort3);
        sortList.add(toSort4);
        sortList.add(toSort5);
        sortList.add(toSort6);
        sortList.add(toSort7);
        sortList.add(toSort8);

        Collections.sort(sortList);

        for(ToSort toSort : sortList){
            System.out.println(toSort.toString());
        }
    }

}

public class ToSort implements Comparable<ToSort> {

    private Float val;
    private String id;

    public ToSort(Float val, String id){
        this.val = val;
        this.id = id;
    }

    @Override
    public int compareTo(ToSort f) {

        if (val.floatValue() > f.val.floatValue()) {
            return 1;
        }
        else if (val.floatValue() <  f.val.floatValue()) {
            return -1;
        }
        else {
            return 0;
        }

    }

    @Override
    public String toString(){
        return this.id;
    }
}

How to know the git username and email saved during configuration?

If you want to check or set the user name and email you can use the below command

Check user name

git config user.name

Set user name

git config user.name "your_name"

Check your email

git config user.email

Set/change your email

git config user.email "[email protected]"

List/see all configuration

git config --list

Android: How to add R.raw to project?

Using IntelliJ Idea:

1) Invalidate Caches, and 2) right click on resources, New Resources directory, type = raw 3) build

note in step 2: I was concerned that simply adding a raw directory wouldn't be enough...

Java Set retain order?

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order.

Twitter Bootstrap - how to center elements horizontally or vertically

bootstrap 4 + Flex solve this

you can use

_x000D_
_x000D_
<div class="d-flex justify-content-center align-items-center">_x000D_
    <button type="submit" class="btn btn-primary">Create</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

it should center centent horizontaly and verticaly

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:

easy_install

aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 
BeautifulSoup-3.1.0.1/
BeautifulSoup-3.1.0.1/BeautifulSoup.py
BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff
BeautifulSoup-3.1.0.1/CHANGELOG
BeautifulSoup-3.1.0.1/README
BeautifulSoup-3.1.0.1/setup.py
BeautifulSoup-3.1.0.1/testall.sh
BeautifulSoup-3.1.0.1/to3.sh
BeautifulSoup-3.1.0.1/PKG-INFO
BeautifulSoup-3.1.0.1/BeautifulSoup.pyc
BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc

aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/

aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install
running install
<... snip ...>

How can I store and retrieve images from a MySQL database using PHP?

Instead of storing images in database store them in a folder in your disk and store their location in your data base.

Multiple line comment in Python

#Single line

'''
multi-line
comment
'''

"""
also, 
multi-line comment
"""

lambda expression for exists within list

var query = list.Where(r => listofIds.Any(id => id == r.Id));

Another approach, useful if the listOfIds array is large:

HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));

'console' is undefined error for Internet Explorer

You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.

if(!window.console || typeof console === "undefined") {
  var console = { log: function (logMsg) { } };
}

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

Get array of object's keys

I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)

var keys = (function(o){var ks=[]; for(var k in o) ks.push(k); return ks})(foo);

Install a module using pip for specific python version

If you have both 2.7 and 3.x versions of python installed, then just rename the python exe file of python 3.x version to something like - "python.exe" to "python3.exe". Now you can use pip for both versions individually. If you normally type "pip install " it will consider the 2.7 version by default. If you want to install it on the 3.x version you need to call the command as "python3 -m pip install ".

Is there a way to represent a directory tree in a Github README.md?

The best way to do this is to surround your tree in the triple backticks to denote a code block. For more info, see the markdown docs: http://daringfireball.net/projects/markdown/syntax#code

How to force page refreshes or reloads in jQuery?

You don't need jQuery to do this. Embrace the power of JavaScript.

window.location.reload()

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

My solution was to insert <packaging>pom</packaging> between artifactId and version

<groupId>com.onlinechat</groupId>
<artifactId>chat-online</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
    <module>server</module>
    <module>client</module>
    <module>network</module>
</modules>

NoClassDefFoundError - Eclipse and Android

I had this for MapActivity. Builds in Eclipse gets NoClassDefFound in debugger.

Forgot to add library to manifest, inside <Application>...</Application> element

<uses-library android:name="com.google.android.maps" />

AttributeError: 'module' object has no attribute 'model'

I also got the same error but I noticed that I had typed in Foreign*k*ey and not Foreign*K*ey,(capital K) if there is a newbie out there, check out spelling and caps.

open existing java project in eclipse

Eclipse does not have internal Subversion connectivity. After you've downloaded and unzipped Eclipse, you have to install a Subversion plug-in. Check with the other developers as to which Subversion plug-in you're using. Subclipse is one Subversion plug-in.

After you've installed the Subversion plug-in, you have to give Eclipse the repository information in the SVN Repositories view of the SVN Repositories perspective. One of the other developers should have that information.

Finally, you check out the project from Subversion, by left clicking on the Package Explorer, selecting New -> Project, and in the New Project wizard,left clicking on SVN -> Checkout projects from SVN.

Difference between Iterator and Listiterator?

There are two differences:

  1. We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.

    That is, we can get a Iterator object by using Set and List, see here:

    By using Iterator we can retrieve the elements from Collection Object in forward direction only.

    Methods in Iterator:

    1. hasNext()
    2. next()
    3. remove()
    Iterator iterator = Set.iterator();
    Iterator iterator = List.iterator();
  2. But we get ListIterator object only from the List interface, see here:

    where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like hasPrevious() and previous() other than those of Iterator. Also, we can get indexes of the next or previous elements (using nextIndex() and previousIndex() respectively )

    Methods in ListIterator:

    1. hasNext()
    2. next()
    3. previous()
    4. hasPrevious()
    5. remove()
    6. nextIndex()
    7. previousIndex()
    ListIterator listiterator = List.listIterator();

    i.e., we can't get ListIterator object from Set interface.

Reference : - What is the difference between Iterator and ListIterator ?

Change the bullet color of list

Example JS Fiddle

Bullets take the color property of the list:

.listStyle {
    color: red;
}

Note if you want your list text to be a different colour, you have to wrap it in say, a p, for example:

.listStyle p {
    color: black;
}

Example HTML:

<ul class="listStyle">
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
</ul>

Angular 2 Routing run in new tab

This seems a little confused.

Opening your application in another window or tab will require your entire application to be re-bootstrapped, and then for your router to... pick up that url, convert it into a route, and load the appropriate component.

This is exactly what will happen if you just use a link instead. In fact, that's all that's happening.

The point of the router is to swap components in and out of your router-outlet, which is something that's been bootstrapped and exists within the confines of your running application and isn't shared across multiple windows.

jquery toggle slide from left to right and back

There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.

HTML Code:

<div class="text">Lorem ipsum.</div>

JQuery Code:

  $(document).ready(function(){
    var DivWidth = $(".text").width();
    $(".left").click(function(){
      $(".text").animate({
        width: 0
      });
    });
    $(".right").click(function(){
      $(".text").animate({
        width: DivWidth
      });
    });
  });

You can see an example here: How to slide toggle a DIV from Left to Right?

Matplotlib connect scatterplot points with line - Python

I think @Evert has the right answer:

plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()

Which is pretty much the same as

plt.plot(dates, values, '-o')
plt.show()

or whatever linestyle you prefer.

AndroidStudio: Failed to sync Install build tools

There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.

  • sdk/build-tools/{TARGET_VERSION}

How do I dump an object's fields to the console?

Possibly:

puts variable.inspect

C# event with custom arguments

You declare a delegate for the parameters:

public enum MyEvents { Event1 }

public delegate void MyEventHandler(MyEvents e);

public static event MyEventHandler EventTriggered;

Although all events in the framework takes a parameter that is or derives from EventArgs, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

What is the difference between const and readonly in C#?

Variables marked const are little more than strongly typed #define macros, at compile time const variable references are replaced with inline literal values. As a consequence only certain built-in primitive value types can be used in this way. Variables marked readonly can be set, in a constructor, at run-time and their read-only-ness is enforced during run-time as well. There is some minor performance cost associated with this but it means you can use readonly with any type (even reference types).

Also, const variables are inherently static, whereas readonly variables can be instance specific if desired.

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

Format date with Moment.js

moment().format();                                // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA");                       // "Mon, 5PM"

calculating execution time in c++

Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.

For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings and set Build Timing option to 'yes'. After that the time of every build will be displayed in the Output window.

Breadth First Vs Depth First

These two terms differentiate between two different ways of walking a tree.

It is probably easiest just to exhibit the difference. Consider the tree:

    A
   / \
  B   C
 /   / \
D   E   F

A depth first traversal would visit the nodes in this order

A, B, D, C, E, F

Notice that you go all the way down one leg before moving on.

A breadth first traversal would visit the node in this order

A, B, C, D, E, F

Here we work all the way across each level before going down.

(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)


Both kinds of traversal can be achieved with the pseudocode:

Store the root node in Container
While (there are nodes in Container)
   N = Get the "next" node from Container
   Store all the children of N in Container
   Do some work on N

The difference between the two traversal orders lies in the choice of Container.

  • For depth first use a stack. (The recursive implementation uses the call-stack...)
  • For breadth-first use a queue.

The recursive implementation looks like

ProcessNode(Node)
   Work on the payload Node
   Foreach child of Node
      ProcessNode(child)
   /* Alternate time to work on the payload Node (see below) */

The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.


At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:

D, B, E, F, C, A

which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.

This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.

How to limit the number of selected checkboxes?

If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox

var queue = [];
function checking(id){
   queue.push(id)
   if (queue.length===3){
    queue[0].checked = false
    queue.shift()
   }
}

How to create a template function within a class? (C++)

Yes, template member functions are perfectly legal and useful on numerous occasions.

The only caveat is that template member functions cannot be virtual.

In C++ check if std::vector<string> contains a certain value

it's in <algorithm> and called std::find.

"Invalid form control" only in Google Chrome

I was getting this error, and determined it was actually on a field that was not hidden.

In this case, it was a type="number" field, that is required. When no value has ever been entered into this field, the error message is shown in the console, and the form is not submitted. Entering a value, and then removing it means that the validation error is shown as expected.

I believe this is a bug in Chrome: my workaround for now was to come up with an initial/default value.

Change a Django form field to a hidden field

an option that worked for me, define the field in the original form as:

forms.CharField(widget = forms.HiddenInput(), required = False)

then when you override it in the new Class it will keep it's place.

Make copy of an array

You can try using Arrays.copyOf() in Java

int[] a = new int[5]{1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);

python pandas convert index to datetime

I just give other option for this question - you need to use '.dt' in your code:

_x000D_
_x000D_
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
_x000D_
_x000D_

MVC 3 file upload and model binding

1st download jquery.form.js file from below url

http://plugins.jquery.com/form/

Write below code in cshtml

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmTemplateUpload" }))
{
    <div id="uploadTemplate">

        <input type="text" value="Asif" id="txtname" name="txtName" />


        <div id="dvAddTemplate">
            Add Template
            <br />
            <input type="file" name="file" id="file" tabindex="2" />
            <br />
            <input type="submit" value="Submit" />
            <input type="button" id="btnAttachFileCancel" tabindex="3" value="Cancel" />
        </div>

        <div id="TemplateTree" style="overflow-x: auto;"></div>
    </div>

    <div id="progressBarDiv" style="display: none;">
        <img id="loading-image" src="~/Images/progress-loader.gif" />
    </div>

}


<script type="text/javascript">

    $(document).ready(function () {
        debugger;
        alert('sample');
        var status = $('#status');
        $('#frmTemplateUpload').ajaxForm({
            beforeSend: function () {
                if ($("#file").val() != "") {
                    //$("#uploadTemplate").hide();
                    $("#btnAction").hide();
                    $("#progressBarDiv").show();
                    //progress_run_id = setInterval(progress, 300);
                }
                status.empty();
            },
            success: function () {
                showTemplateManager();
            },
            complete: function (xhr) {
                if ($("#file").val() != "") {
                    var millisecondsToWait = 500;
                    setTimeout(function () {
                        //clearInterval(progress_run_id);
                        $("#uploadTemplate").show();
                        $("#btnAction").show();
                        $("#progressBarDiv").hide();
                    }, millisecondsToWait);
                }
                status.html(xhr.responseText);
            }
        });

    });


</script>

Action method :-

 public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

 public void Upload(HttpPostedFileBase file, string txtname )
        {

            try
            {
                string attachmentFilePath = file.FileName;
                string fileName = attachmentFilePath.Substring(attachmentFilePath.LastIndexOf("\\") + 1);

           }
            catch (Exception ex)
            {

            }
        }

How do I detect "shift+enter" and generate a new line in Textarea?

using ng-keyup directive in angularJS, only send a message on pressing Enter key and Shift+Enter will just take a new line.

ng-keyup="($event.keyCode == 13&&!$event.shiftKey) ? sendMessage() : null"

how to save canvas as png image?

var canvasId = chart.id + '-canvas';
var canvasDownloadId = chart.id + '-download-canvas';
var canvasHtml = Ext.String.format('<canvas id="{0}" width="{1}" height="{2}"></canvas><a id="{3}"/>',
canvasId,
chart.getWidth(),
chart.getHeight(),
canvasDownloadId);
var canvasElement = reportBuilder.add({ html: canvasHtml });

var canvas = document.getElementById(canvasId);

var canvasDownload = document.getElementById(canvasDownloadId);
canvasDownload.href = chart.getImage().data;
canvasDownload.download = 'chart';

canvasDownload.click();

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

Check string for palindrome

Using stack, it can be done like this

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str=in.nextLine();
        str.replaceAll("\\s+","");
        //System.out.println(str);
        Stack<String> stack=new Stack<String>();
        stack.push(str);
        String str_rev=stack.pop();
        if(str.equals(str_rev)){
            System.out.println("Palindrome"); 
        }else{
             System.out.println("Not Palindrome");
        }
    }
}

How to set width of mat-table column in angular?

As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"

for example :

<mat-table #table [dataSource]="dataSource" matSortDisableClear>
    <ng-container matColumnDef="productId">
        <mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="productName">
        <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let product">
            <button (click)="view(product)">
                <mat-icon>visibility</mat-icon>
            </button>
        </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

here matColumnDef is productId, productName and action

now we apply width by matColumnDef

styling

.mat-column-productId {
    flex: 0 0 10%;
}
.mat-column-productName {
    flex: 0 0 50%;
}

and remaining width is equally allocated to other columns

Unix's 'ls' sort by name

Files being different only by a numerical string can be sorted on this number at the condition that it is preceded by a separator.

In this case, the following syntax can be used:

ls -x1 file | sort -t'<char>' -n -k2

Example:

ls -1 TRA*log | sort -t'_' -n -k2

TRACE_1.log
TRACE_2.log
TRACE_3.log
TRACE_4.log
TRACE_5.log
TRACE_6.log
TRACE_7.log
TRACE_8.log
TRACE_9.log
TRACE_10.log

Select elements by attribute

as in this post, using .is and the attribute selector [], you can easily add a function (or prototype):

function hasAttr($sel,attr) {
    return $sel.is('['+attr+']');
}

php error: Class 'Imagick' not found

Docker container installation for php:XXX Debian based images:

RUN apt-get update && apt-get install -y --no-install-recommends libmagickwand-dev
RUN pecl install imagick && docker-php-ext-enable imagick
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* || true

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

How to find all links / pages on a website

If this is a programming question, then I would suggest you write your own regular expression to parse all the retrieved contents. Target tags are IMG and A for standard HTML. For JAVA,

final String openingTags = "(<a [^>]*href=['\"]?|<img[^> ]* src=['\"]?)";

this along with Pattern and Matcher classes should detect the beginning of the tags. Add LINK tag if you also want CSS.

However, it is not as easy as you may have intially thought. Many web pages are not well-formed. Extracting all the links programmatically that human being can "recognize" is really difficult if you need to take into account all the irregular expressions.

Good luck!

Closing Twitter Bootstrap Modal From Angular Controller

You can do it with a simple jquery code.

$('#Mymodal').modal('hide');

"message failed to fetch from registry" while trying to install any module

I'm on Ubuntu. I used apt-get to install node. Npm was not included in that package, so it had to be installed separately. I assumed that would work, but apparently the npm version in the Ubuntu distribution was outdated.

The node wiki has this instruction:

Obtaining a recent version of Node or installing on older Ubuntu and other apt-based distributions may require a few extra steps. Example install:

sudo apt-get update
sudo apt-get install -y python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

After that, npm was already included and worked perfectly.

How do I append text to a file?

Other possible way is:

echo "text" | tee -a filename >/dev/null

The -a will append at the end of the file.

If needing sudo, use:

echo "text" | sudo tee -a filename >/dev/null

jQuery - how to write 'if not equal to' (opposite of ==)

The opposite of the == compare operator is !=.

connecting to MySQL from the command line

After you run MySQL Shell and you have seen following:

mysql-js>

Firstly, you should:

mysql-js>\sql

Secondly:

 mysql-sql>\connect username@servername (root@localhost)

And finally:

Enter password:*********

Drawing circles with System.Drawing

if you want to draw circle on button then this code might be use full. else if you want to draw a circle on other control just change the name of control and also event. like here event button is called. if you want to draw this circle in group box call the Groupbox event. regards

    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.button1.Location = new Point(108, 12);
       // this.Paint += new PaintEventHandler(Form1_Paint);
        this.button1.Paint += new PaintEventHandler(button1_Paint);
    }
    void button1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = this.button1.CreateGraphics();
        Pen pen = new Pen(Color.Red);
        g.DrawEllipse(pen, 10, 10, 20, 20);

    }





}

jQuery trigger file input

I have it working (=tested) in IE8+, recent FF and chrome:

$('#uploadInput').focus().trigger('click');

The key is focusing before firing the click (otherwise chrome ignores it).

Note: you do NEED to have your input displayed and visible (as in, not display:none and not visibility:hidden). I suggest (as many other have before) to absolutely position the input and throw it off screen.

#uploadInput {
    position: absolute;
    left: -9999px;
}

Java SecurityException: signer information does not match

In my case, I had duplicated JAR version of BouncyCastle in my library path :S

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

I solved the issue by configuring environment.rb as

YourApp::Application.default_url_options = YourApp::Application.config.action_mailer.default_url_options

You need to set default_url_options for action mailer against each environment like development, testing, staging and production etc.

Reference: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

Get last field using awk substr

Another option is to use bash parameter substitution.

$ foo="/home/parent/child/filename"
$ echo ${foo##*/}
filename
$ foo="/home/parent/child/child2/filename"
$ echo ${foo##*/}
filename

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

The right answer is, that some of your jar files does not compile. You should go into your build.gradle file in your project, and look in your dependencies.

If you're just importing some jar files, you could try to remove them and add them one at a time. This will help you determine which one of them causes the error.

In my case, I did just that, and when I was importing the last one, the app compiled. So I think the real problem was that I was importing too many at once. But now it all works.

Endless loop in C/C++

In an ultimate act of boredom, I actually wrote a few versions of these loops and compiled it with GCC on my mac mini.

the while(1){} and for(;;) {} produced same assembly results while the do{} while(1); produced similar but a different assembly code

heres the one for while/for loop

    .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    movl    $0, -4(%rbp)
LBB0_1:                                 ## =>This Inner Loop Header: Depth=1
    jmp LBB0_1
    .cfi_endproc

and the do while loop

        .section    __TEXT,__text,regular,pure_instructions
    .globl  _main
    .align  4, 0x90
_main:                                  ## @main
    .cfi_startproc
## BB#0:
    pushq   %rbp
Ltmp2:
    .cfi_def_cfa_offset 16
Ltmp3:
    .cfi_offset %rbp, -16
    movq    %rsp, %rbp
Ltmp4:
    .cfi_def_cfa_register %rbp
    movl    $0, -4(%rbp)
LBB0_1:                                 ## =>This Inner Loop Header: Depth=1
    jmp LBB0_2
LBB0_2:                                 ##   in Loop: Header=BB0_1 Depth=1
    movb    $1, %al
    testb   $1, %al
    jne LBB0_1
    jmp LBB0_3
LBB0_3:
    movl    $0, %eax
    popq    %rbp
    ret
    .cfi_endproc

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Since Spark 1.5 you can use a number of date processing functions:

import datetime
from pyspark.sql.functions import year, month, dayofmonth

elevDF = sc.parallelize([
    (datetime.datetime(1984, 1, 1, 0, 0), 1, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 2, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 3, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 4, 638.55),
    (datetime.datetime(1984, 1, 1, 0, 0), 5, 638.55)
]).toDF(["date", "hour", "value"])

elevDF.select(
    year("date").alias('year'), 
    month("date").alias('month'), 
    dayofmonth("date").alias('day')
).show()
# +----+-----+---+
# |year|month|day|
# +----+-----+---+
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# |1984|    1|  1|
# +----+-----+---+

You can use simple map as with any other RDD:

elevDF = sqlContext.createDataFrame(sc.parallelize([
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=1, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=2, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=3, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=4, value=638.55),
        Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=5, value=638.55)]))

(elevDF
 .map(lambda (date, hour, value): (date.year, date.month, date.day))
 .collect())

and the result is:

[(1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1)]

Btw: datetime.datetime stores an hour anyway so keeping it separately seems to be a waste of memory.

Android, landscape only orientation?

Just two steps needed:

  1. Apply setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); after setContentView().

  2. In the AndroidMainfest.xml, put this statement <activity android:name=".YOURCLASSNAME" android:screenOrientation="landscape" />

Hope it helps and happy coding :)

module.exports vs. export default in Node.js and ES6

The issue is with

  • how ES6 modules are emulated in CommonJS
  • how you import the module

ES6 to CommonJS

At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?

Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.

ES6 default exports are actually also named exports, except that default is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var foo = exports.foo = 42;
exports.default = 21; 

Here we can see that the default export becomes a property on the exports object, just like foo.

Import the module

We can import the module in two ways: Either using CommonJS or using ES6 import syntax.

Your issue: I believe you are doing something like:

var bar = require('./input');
new bar();

expecting that bar is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default property!

So in order to access the default export we actually have to do

var bar = require('./input').default;

If we use ES6 module syntax, namely

import bar from './input';
console.log(bar);

Babel will transform it to

'use strict';

var _input = require('./input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_input2.default);

You can see that every access to bar is converted to access .default.

How to set entire application in portrait mode only?

You can set this in your manifest file..

android:name=".your launching activity name"
android:screenOrientation="portrait"

and you can also achive the same by writing the code in your class file like:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

How to initialize a vector with fixed length in R

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

Only read selected columns

You could also use JDBC to achieve this. Let's create a sample csv file.

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

Download and save the the CSV JDBC driver from this link: http://sourceforge.net/projects/csvjdbc/files/latest/download

> library(RJDBC)

> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
   MPG GEAR
1   21    4
2   21    4
3 22.8    4

Insert, on duplicate update in PostgreSQL?

For merging small sets, using the above function is fine. However, if you are merging large amounts of data, I'd suggest looking into http://mbk.projects.postgresql.org

The current best practice that I'm aware of is:

  1. COPY new/updated data into temp table (sure, or you can do INSERT if the cost is ok)
  2. Acquire Lock [optional] (advisory is preferable to table locks, IMO)
  3. Merge. (the fun part)

Should I put input elements inside a label element?

Behavior difference: clicking in the space between label and input

If you click on the space between the label and the input it activates the input only if the label contains the input.

This makes sense since in this case the space is just another character of the label.

_x000D_
_x000D_
<p>Inside:</p>_x000D_
_x000D_
<label>_x000D_
  <input type="checkbox" />_x000D_
  |&lt;----- Label. Click between me and the checkbox._x000D_
</label>_x000D_
_x000D_
<p>Outside:</p>_x000D_
_x000D_
<input type="checkbox" id="check" />_x000D_
<label for="check">|&lt;----- Label. Click between me and the checkbox.</label>
_x000D_
_x000D_
_x000D_

Being able to click between label and box means that it is:

  • easier to click
  • less clear where things start and end

Bootstrap checkbox v3.3 examples use the input inside: http://getbootstrap.com/css/#forms Might be wise to follow them. But they changed their minds in v4.0 https://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios so I don't know what is wise anymore:

Checkboxes and radios use are built to support HTML-based form validation and provide concise, accessible labels. As such, our <input>s and <label>s are sibling elements as opposed to an <input> within a <label>. This is slightly more verbose as you must specify id and for attributes to relate the <input> and <label>.

UX question that discusses this point in detail: https://ux.stackexchange.com/questions/23552/should-the-space-between-the-checkbox-and-label-be-clickable

How to detect duplicate values in PHP array?

function array_not_unique( $a = array() )
{
  return array_diff_key( $a , array_unique( $a ) );
}

How to get a password from a shell script without echoing

A POSIX compliant answer. Notice the use of /bin/sh instead of /bin/bash. (It does work with bash, but it does not require bash.)

#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"

How to change line color in EditText

for API below 21, you can use theme attribute in EditText put below code into style file

<style name="MyEditTextTheme">
    <item name="colorControlNormal">#FFFFFF</item>
    <item name="colorControlActivated">#FFFFFF</item>
    <item name="colorControlHighlight">#FFFFFF</item>
</style>

use this style in EditText as

<EditText
    android:id="@+id/etPassword"
    android:layout_width="match_parent"
    android:layout_height="@dimen/user_input_field_height"
    android:layout_marginTop="40dp"
    android:hint="@string/password_hint"
    android:theme="@style/MyEditTextTheme"
    android:singleLine="true" />

Read next word in java

Using Scanners, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().

On the other hand, If you split by space (line.split(" ")), the code will fail if you try to read a file with a different whitespace delimiter. If split() expects you to write a regular expression, and it does matching anyway, use split("\\s") instead, that matches a "bit" more whitespace than just a space character.

P.S.: Sorry, I don't have right to comment on already given answers.