Programs & Examples On #Headphones

Python: Making a beep noise

I was searching for the same but for Linux shell.

The topic brought me to an answer, -thanks-

Maybe more pythonic manner :

import os
beep = lambda x: os.system("echo -n '\a';sleep 0.2;" * x)
beep(3)

Notes :

  • the sleep value (here 0.2), depends on the length (seconds) of your default beep sound
  • I choosed to use os.system rather then subprocess.Popen for simplicity (it could be bad)
  • the '-n' for echo is to have no more display
  • the last ';' after sleep is necessary for the resulting text sequence (*x)
  • also tested through ssh on an X term

Share Text on Facebook from Android App via ACTION_SEND

First you need query Intent to handler sharing option. Then use package name to filter Intent then we will have only one Intent that handler sharing option!

Share via Facebook

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
    if ((app.activityInfo.name).contains("facebook")) {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shareIntent.setComponent(name);
        v.getContext().startActivity(shareIntent);
        break;
   }
}

Bonus - Share via Twitter

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Content to share");
PackageManager pm = v.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
    if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
        final ActivityInfo activity = app.activityInfo;
        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
        shareIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        shareIntent.setComponent(name);
        v.getContext().startActivity(shareIntent);
        break;
   }
}

And if you want to find how to share via another sharing application, find it there Tép Blog - Advance share via Android

Angular2 Material Dialog css, dialog size

You can inspect the dialog element with dev tools and see what classes are applied on mdDialog.

For example, .md-dialog-container is the main classe of the MDDialog and has padding: 24px

you can create a custom CSS to overwrite whatever you want

.md-dialog-container {
      background-color: #000;
      width: 250px;
      height: 250px
}

In my opinion this is not a good option and probably goes against Material guide but since it doesn't have all features it has in it's previous version, you should do what you think is best for you.

How do I set up NSZombieEnabled in Xcode 4?

In Xcode 4.2

  • Project Name/Edit Scheme/Diagnostics/
  • Enable Zombie Objects check box
  • You're done

Why use prefixes on member variables in C++ classes

I use it because VC++'s Intellisense can't tell when to show private members when accessing out of the class. The only indication is a little "lock" symbol on the field icon in the Intellisense list. It just makes it easier to identify private members(fields) easier. Also a habit from C# to be honest.

class Person {
   std::string m_Name;
public:
   std::string Name() { return m_Name; }
   void SetName(std::string name) { m_Name = name; }
};

int main() {
  Person *p = new Person();
  p->Name(); // valid
  p->m_Name; // invalid, compiler throws error. but intellisense doesn't know this..
  return 1;
}

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

  1. Copy config.sample.inc.php to config.inc.php.

    In most cases you will find the config file

    • on linux: /etc/phpmyadmin/config.inc.php
    • on mac: /Library/WebServer/Documents/phpmyadmin/config.inc.php
  2. If you are trying to log in as root, you should have the following lines in your config:

    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

Text in Border CSS HTML

_x000D_
_x000D_
<fieldset>_x000D_
  <legend> YOUR TITLE </legend>_x000D_
  _x000D_
  _x000D_
  <p>_x000D_
  Lorem ipsum dolor sit amet, est et illum reformidans, at lorem propriae mei. Qui legere commodo mediocritatem no. Diam consetetur._x000D_
  </p>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

SQLite UPSERT / UPDATE OR INSERT

Here's an approach that doesn't require the brute-force 'ignore' which would only work if there was a key violation. This way works based on any conditions you specify in the update.

Try this...

-- Try to update any existing row
UPDATE players
SET age=32
WHERE user_name='steven';

-- If no update happened (i.e. the row didn't exist) then insert one
INSERT INTO players (user_name, age)
SELECT 'steven', 32
WHERE (Select Changes() = 0);

How It Works

The 'magic sauce' here is using Changes() in the Where clause. Changes() represents the number of rows affected by the last operation, which in this case is the update.

In the above example, if there are no changes from the update (i.e. the record doesn't exist) then Changes() = 0 so the Where clause in the Insert statement evaluates to true and a new row is inserted with the specified data.

If the Update did update an existing row, then Changes() = 1 (or more accurately, not zero if more than one row was updated), so the 'Where' clause in the Insert now evaluates to false and thus no insert will take place.

The beauty of this is there's no brute-force needed, nor unnecessarily deleting, then re-inserting data which may result in messing up downstream keys in foreign-key relationships.

Additionally, since it's just a standard Where clause, it can be based on anything you define, not just key violations. Likewise, you can use Changes() in combination with anything else you want/need anywhere expressions are allowed.

How do I know which version of Javascript I'm using?

All of todays browsers use at least version 1.5:
http://en.wikipedia.org/wiki/ECMAScript#Dialect

Concerning your tutorial site, the information there seems to be extremely outdated, I beg you to head over to MDC and read their Guide:
https://developer.mozilla.org/en/JavaScript/Guide

You may still want to watch out for features which require version 1.6 or above, as this might give Internet Explorer some troubles.

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

It worked for me, just leave it to the jQuery.

$("html,body").animate({ scrollTop: 0 }, 1);

Basically you should know the browser and write the code considering browser differences. Since jQuery is cross-browser it should handle the first step. And finally you fake the js-engine of the browser by animating the scrolling in 1 millisecond.

Why is Git better than Subversion?

David Richards WANdisco Blog on Subversion / GIT

The emergence of GIT has brought with it a breed of DVCS fundamentalists – the ‘Gitterons’ – that think anything other than GIT is crap. The Gitterons seem to think software engineering happens on their own island and often forget that most organizations don’t employ senior software engineers exclusively. That’s ok but it’s not how the rest of the market thinks, and I am happy to prove it: GIT, at the last look had less than three per cent of the market while Subversion has in the region of five million users and about half of the overall market.

The problem we saw was that the Gitterons were firing (cheap) shots at Subversion. Tweets like “Subversion is so [slow/crappy/restrictive/doesn't smell good/looks at me in a funny way] and now I have GIT and [everything works in my life/my wife got pregnant/I got a girlfriend after 30 years of trying/I won six times running on the blackjack table]. You get the picture.

How to add buttons dynamically to my form?

You can't add a Button to an empty list without creating a new instance of that Button. You are missing the

Button newButton = new Button();  

in your code plus get rid of the .Capacity

Simplest way to form a union of two lists

If it is two IEnumerable lists you can't use AddRange, but you can use Concat.

IEnumerable<int> first = new List<int>{1,1,2,3,5};
IEnumerable<int> second = new List<int>{8,13,21,34,55};

var allItems = first.Concat(second);
// 1,1,2,3,5,8,13,21,34,55

Get all photos from Instagram which have a specific hashtag with PHP

Here's another example I wrote a while ago:

<?php       
    // Get class for Instagram
    // More examples here: https://github.com/cosenary/Instagram-PHP-API
    require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('CLIENT_ID_HERE');

    // Set keyword for #hashtag
    $tag = 'KEYWORD HERE';

    // Get latest photos according to #hashtag keyword
    $media = $instagram->getTagMedia($tag);

    // Set number of photos to show
    $limit = 5;

    // Set height and width for photos
    $size = '100';

    // Show results
    // Using for loop will cause error if there are less photos than the limit
    foreach(array_slice($media->data, 0, $limit) as $data)
    {
        // Show photo
        echo '<p><img src="'.$data->images->thumbnail->url.'" height="'.$size.'" width="'.$size.'" alt="SOME TEXT HERE"></p>';
    }
?>

Adding an image to a project in Visual Studio

Click on the Project in Visual Studio and then click on the button titled "Show all files" on the Solution Explorer toolbar. That will show files that aren't in the project. Now you'll see that image, right click in it, and select "Include in project" and that will add the image to the project!

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

Java Inheritance - calling superclass method

You can do:

super.alphaMethod1();

Note, that super is a reference to the parent, but super() is it's constructor.

How to select all records from one table that do not exist in another table?

Here's what worked best for me.

SELECT *
FROM @T1
EXCEPT
SELECT a.*
FROM @T1 a
JOIN @T2 b ON a.ID = b.ID

This was more than twice as fast as any other method I tried.

How to prevent Google Colab from disconnecting?

the following LATEST solution works for me:

function ClickConnect(){
  colab.config
  console.log("Connnect Clicked - Start"); 
  document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect").click();
  console.log("Connnect Clicked - End");
};
setInterval(ClickConnect, 60000)

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.

The solution for me, partly from here was:

  1. uninstall SQL Server
  2. in Regional Settings / Management / System Locale, "Beta: UTF-8 support" should be OFF
  3. re-install SQL Server
  4. Let Windows install the patch.

And all was well.

More on this here.

Changing password with Oracle SQL Developer

I realise that there are many answers, but I found a solution that may be helpful to some. I ran into the same problem, I am running oracle sql develop on my local computer and I have a bunch of users. I happen to remember the password for one of my users and I used it to reset the password of other users.

Steps:

  1. connect to a database using a valid user and password, in my case all my users expired except "system" and I remember that password

  2. find the "Other_users" node within the tree as the image below displays

enter image description here

3.within the "Other_users" tree find your users that you would like to reset password of and right click the note and select "Edit Users"

enter image description here

4.fill out the new password in edit user dialog and click "Apply". Make sure that you have unchecked "Password expired (user must change next login)".

enter image description here

And that worked for me, It is not as good as other solution because you need to be able to login to at least one account but it does work.

How can I load Partial view inside the view?

If you want to load the partial view directly inside the main view you could use the Html.Action helper:

@Html.Action("Load", "Home")

or if you don't want to go through the Load action use the HtmlPartialAsync helper:

@await Html.PartialAsync("_LoadView")

If you want to use Ajax.ActionLink, replace your Html.ActionLink with:

@Ajax.ActionLink(
    "load partial view", 
    "Load", 
    "Home", 
    new AjaxOptions { UpdateTargetId = "result" }
)

and of course you need to include a holder in your page where the partial will be displayed:

<div id="result"></div>

Also don't forget to include:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

in your main view in order to enable Ajax.* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

How to post data to specific URL using WebClient in C#

//Making a POST request using WebClient.
Function()
{    
  WebClient wc = new WebClient();

  var URI = new Uri("http://your_uri_goes_here");

  //If any encoding is needed.
  wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
  //Or any other encoding type.

  //If any key needed

  wc.Headers["KEY"] = "Your_Key_Goes_Here";

  wc.UploadStringCompleted += 
      new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

  wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
}

void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)    
{  
  try            
  {          
     MessageBox.Show(e.Result); 
     //e.result fetches you the response against your POST request.         
  }
  catch(Exception exc)         
  {             
     MessageBox.Show(exc.ToString());            
  }
}

How to search and replace text in a file?

I modified Jayram Singh's post slightly in order to replace every instance of a '!' character to a number which I wanted to increment with each instance. Thought it might be helpful to someone who wanted to modify a character that occurred more than once per line and wanted to iterate. Hope that helps someone. PS- I'm very new at coding so apologies if my post is inappropriate in any way, but this worked for me.

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
n = 1  

# if word=='!'replace w/ [n] & increment n; else append same word to     
# file2

for line in f1:
    for word in line:
        if word == '!':
            f2.write(word.replace('!', f'[{n}]'))
            n += 1
        else:
            f2.write(word)
f1.close()
f2.close()

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

List to array conversion to use ravel() function

If all you want is calling ravel on your (nested, I s'pose?) list, you can do that directly, numpy will do the casting for you:

L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)

Also worth mentioning that you needn't go through numpy at all.

How can I increase the cursor speed in terminal?

System Preferences => Keyboard => Key Repeat Rate

How to open local file on Jupyter?

Here's a possibile solution (in Python):

Let's say you have a notebook with a file name, call it Notebook.ipynb. You are currently working in that notebook, and want to access other folders and files around it. Here's it's path:

import os
notebook_path = os.path.abspath("Notebook.ipynb")

In other words, just use the os module, and get the absolute path of your notebook (it's a file, too!). From there, use the os module and your path to navigate.

For example, if your train.csv is in a folder called 'Datasets', and the notebook is sitting right next to that folder, you could get the data like this:

train_csv = os.path.join(os.path.dirname(notebook_path), "Datasets/train.csv")
with open(train_csv) as file:
    #....etc

The takeaway is that the notebook has a file name, and as long as your language supports pathname manipulations (e.g. the os module in Python) you can likely use the notebook filename.

Lastly, the reason your code fails is probably because you're either trying to access local files (like your Mac's 'Downloads' folder) when you're working in an online Notebook (like Kaggle, which hosts your environment for you, online and away from your Mac), or you moved or deleted something in that path. This is what the os module in Python is meant to do; it will find the file's path whether it's on your Mac or in a Kaggle server.

How does bitshifting work in Java?

Shift Operators

The binary 32 bits for 00101011 is

00000000 00000000 00000000 00101011, and the result is:

  00000000 00000000 00000000 00101011   >> 2(times)
 \\                                 \\
  00000000 00000000 00000000 00001010

Shifts the bits of 43 to right by distance 2; fills with highest(sign) bit on the left side.

Result is 00001010 with decimal value 10.

00001010
    8+2 = 10

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

If WorkSheet("wsName") Exists

Another version of the function without error handling. This time it is not case sensitive and a little bit more efficient.

Function WorksheetExists(wsName As String) As Boolean
    Dim ws As Worksheet
    Dim ret As Boolean        
    wsName = UCase(wsName)
    For Each ws In ThisWorkbook.Sheets
        If UCase(ws.Name) = wsName Then
            ret = True
            Exit For
        End If
    Next
    WorksheetExists = ret
End Function

Update UI from Thread in Android

As recommended by official documentation, you can use AsyncTask to handle work items shorter than 5ms in duration. If your task take more time, lookout for other alternatives.

HandlerThread is one alternative to Thread or AsyncTask. If you need to update UI from HandlerThread, post a message on UI Thread Looper and UI Thread Handler can handle UI updates.

Example code:

Android: Toast in a thread

jQuery animated number counter from zero to value

You can get the element itself in .each(), try this instead of using this

$('.Count').each(function (index, value) {
    jQuery({ Counter: 0 }).animate({ Counter: value.text() }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            value.text(Math.ceil(this.Counter));
        }
    });
});

How to read the RGB value of a given pixel in Python?

install PIL using the command "sudo apt-get install python-imaging" and run the following program. It will print RGB values of the image. If the image is large redirect the output to a file using '>' later open the file to see RGB values

import PIL
import Image
FILENAME='fn.gif' #image can be in gif jpeg or png format 
im=Image.open(FILENAME).convert('RGB')
pix=im.load()
w=im.size[0]
h=im.size[1]
for i in range(w):
  for j in range(h):
    print pix[i,j]

How to restore to a different database in sql server?

You can create a new db then use the "Restore Wizard" enabling the Overwrite option or;

View the content;

RESTORE FILELISTONLY FROM DISK='c:\your.bak'

note the logical names of the .mdf & .ldf from the results, then;

RESTORE DATABASE MyTempCopy FROM DISK='c:\your.bak'
WITH 
   MOVE 'LogicalNameForTheMDF' TO 'c:\MyTempCopy.mdf',
   MOVE 'LogicalNameForTheLDF' TO 'c:\MyTempCopy_log.ldf'

To create the database MyTempCopy with the contents of your.bak.

Example (restores a backup of a db called 'creditline' to 'MyTempCopy';

RESTORE FILELISTONLY FROM DISK='e:\mssql\backup\creditline.bak'

>LogicalName
>--------------
>CreditLine
>CreditLine_log

RESTORE DATABASE MyTempCopy FROM DISK='e:\mssql\backup\creditline.bak'
WITH 
   MOVE 'CreditLine' TO 'e:\mssql\MyTempCopy.mdf',
   MOVE 'CreditLine_log' TO 'e:\mssql\MyTempCopy_log.ldf'

>RESTORE DATABASE successfully processed 186 pages in 0.010 seconds (144.970 MB/sec).

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just change your line of code to

<a href="~/Required/[email protected]">Edit</a>

from where you are calling this function that will pass corect id

Repeat command automatically in Linux

sleep already returns 0. As such, I'm using:

while sleep 3 ; do ls -l ; done

This is a tiny bit shorter than mikhail's solution. A minor drawback is that it sleeps before running the target command for the first time.

What is __future__ in Python used for and how/when to use it, and how it works

Or is it like saying "Since this is python v2.7, use that different 'print' function that has also been added to python v2.7, after it was added in python 3. So my 'print' will no longer be statements (eg print "message" ) but functions (eg, print("message", options). That way when my code is run in python 3, 'print' will not break."

In

from __future__ import print_function

print_function is the module containing the new implementation of 'print' as per how it is behaving in python v3.

This has more explanation: http://python3porting.com/noconv.html

How to create a toggle button in Bootstrap

Bootstrap 3 has options to create toggle buttons based on checkboxes or radio buttons: http://getbootstrap.com/javascript/#buttons

Checkboxes

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" checked> Option 1 (pre-checked)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 3
  </label>
</div>

Radio buttons

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" checked> Option 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3"> Option 3
  </label>
</div>

For these to work you must initialize .btns with Bootstrap's Javascript:

$('.btn').button();

Sublime Text 2 multiple line edit

I was facing the same problem on Linux, what I did was to select all the content (ctrl-A) and then press ctrl+shift+L, It gives you a cursor on each line and then you can add similar content to each column.

Also you can perform other operations like cut, copy and paste column wise.

PS :- If you want to select a rectangular set of data from text, you can also press shift and hold Right Mouse button and then select data in a rectangular fashion. Then press CTRL+SHIFT+L to get the cursor on each line.

Creating JSON on the fly with JObject

Simple way of creating newtonsoft JObject from Properties.

This is a Sample User Properties

public class User
{
    public string Name;
    public string MobileNo;
    public string Address;
}

and i want this property in newtonsoft JObject is:

JObject obj = JObject.FromObject(new User()
{
    Name = "Manjunath",
    MobileNo = "9876543210",
    Address = "Mumbai, Maharashtra, India",
});

Output will be like this:

{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}

Compiled vs. Interpreted Languages

The extreme and simple cases:

  • A compiler will produce a binary executable in the target machine's native executable format. This binary file contains all required resources except for system libraries; it's ready to run with no further preparation and processing and it runs like lightning because the code is the native code for the CPU on the target machine.

  • An interpreter will present the user with a prompt in a loop where he can enter statements or code, and upon hitting RUN or the equivalent the interpreter will examine, scan, parse and interpretatively execute each line until the program runs to a stopping point or an error. Because each line is treated on its own and the interpreter doesn't "learn" anything from having seen the line before, the effort of converting human-readable language to machine instructions is incurred every time for every line, so it's dog slow. On the bright side, the user can inspect and otherwise interact with his program in all kinds of ways: Changing variables, changing code, running in trace or debug modes... whatever.

With those out of the way, let me explain that life ain't so simple any more. For instance,

  • Many interpreters will pre-compile the code they're given so the translation step doesn't have to be repeated again and again.
  • Some compilers compile not to CPU-specific machine instructions but to bytecode, a kind of artificial machine code for a ficticious machine. This makes the compiled program a bit more portable, but requires a bytecode interpreter on every target system.
  • The bytecode interpreters (I'm looking at Java here) recently tend to re-compile the bytecode they get for the CPU of the target section just before execution (called JIT). To save time, this is often only done for code that runs often (hotspots).
  • Some systems that look and act like interpreters (Clojure, for instance) compile any code they get, immediately, but allow interactive access to the program's environment. That's basically the convenience of interpreters with the speed of binary compilation.
  • Some compilers don't really compile, they just pre-digest and compress code. I heard a while back that's how Perl works. So sometimes the compiler is just doing a bit of the work and most of it is still interpretation.

In the end, these days, interpreting vs. compiling is a trade-off, with time spent (once) compiling often being rewarded by better runtime performance, but an interpretative environment giving more opportunities for interaction. Compiling vs. interpreting is mostly a matter of how the work of "understanding" the program is divided up between different processes, and the line is a bit blurry these days as languages and products try to offer the best of both worlds.

In c++ what does a tilde "~" before a function name signify?

This is a destructor. It's called when the object is destroyed (out of life scope or deleted).

To be clear, you have to use ~NameOfTheClass like for the constructor, other names are invalid.

Websocket onerror - how to read error description?

Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).

you will almost never get these codes in practice so this code is pretty much pointless

var websocket;
if ("WebSocket" in window)
{
    websocket = new WebSocket("ws://yourDomainNameHere.org/");

    websocket.onopen = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
    };
    websocket.onclose = function (event) {
        var reason;
        alert(event.code);
        // See http://tools.ietf.org/html/rfc6455#section-7.4.1
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";

        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
    };
    websocket.onmessage = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
    };
    websocket.onerror = function (event) {
        $("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
    };
}
else
{
    alert("Websocket is not supported by your browser");
    return;
}

websocket.send("Yo wazzup");

websocket.close();

See http://jsfiddle.net/gr0bhrqr/

How to save a data.frame in R?

If you are only saving a single object (your data frame), you could also use saveRDS.
To save:

saveRDS(foo, file="data.Rda")

Then read it with:

bar <- readRDS(file="data.Rda")

The difference between saveRDS and save is that in the former only one object can be saved and the name of the object is not forced to be the same after you load it.

Order of execution of tests in TestNG

Tests like unit tests? What for? Tests HAVE to be independant, otherwise.... you can not run a test individually. If they are independent, why even interfere? Plus - what is an "order" if you run them in multiple threads on multiple cores?

Xcode 10: A valid provisioning profile for this executable was not found

I was struggling with the same issue and the solution in my case was to log in to the developer account(s). After updating to Xcode 10 all accounts were logged out.

Use the menu "Xcode -> Preferences ... -> Accounts" and make sure all accounts you use are logged in so the provisioning profiles are accessible.

Fake "click" to activate an onclick method

I haven't used jQuery, but IIRC, the first method mentioned doesn't trigger the onclick handler.

I'd call the associated onclick method directly, if you're not using the event details.

Created Button Click Event c#

    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

call javascript function on hyperlink click

With the onclick parameter...

<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>

How to show image using ImageView in Android

In res folder select the XML file in which you want to view your images,

<ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:src="@drawable/imagep1" />

SSRS Query execution failed for dataset

This problem was caused by an orphaned SQL Login. I ran my favorite sp_fixusers script and the error was resolved. The suggestion above to look at the logs was a good one...and it led me to my answer.

Python: Get relative path from comparing two absolute paths

os.path.commonprefix() and os.path.relpath() are your friends:

>>> print os.path.commonprefix(['/usr/var/log', '/usr/var/security'])
'/usr/var'
>>> print os.path.commonprefix(['/tmp', '/usr/var'])  # No common prefix: the root is the common prefix
'/'

You can thus test whether the common prefix is one of the paths, i.e. if one of the paths is a common ancestor:

paths = […, …, …]
common_prefix = os.path.commonprefix(list_of_paths)
if common_prefix in paths:
    …

You can then find the relative paths:

relative_paths = [os.path.relpath(path, common_prefix) for path in paths]

You can even handle more than two paths, with this method, and test whether all the paths are all below one of them.

PS: depending on how your paths look like, you might want to perform some normalization first (this is useful in situations where one does not know whether they always end with '/' or not, or if some of the paths are relative). Relevant functions include os.path.abspath() and os.path.normpath().

PPS: as Peter Briggs mentioned in the comments, the simple approach described above can fail:

>>> os.path.commonprefix(['/usr/var', '/usr/var2/log'])
'/usr/var'

even though /usr/var is not a common prefix of the paths. Forcing all paths to end with '/' before calling commonprefix() solves this (specific) problem.

PPPS: as bluenote10 mentioned, adding a slash does not solve the general problem. Here is his followup question: How to circumvent the fallacy of Python's os.path.commonprefix?

PPPPS: starting with Python 3.4, we have pathlib, a module that provides a saner path manipulation environment. I guess that the common prefix of a set of paths can be obtained by getting all the prefixes of each path (with PurePath.parents()), taking the intersection of all these parent sets, and selecting the longest common prefix.

PPPPPS: Python 3.5 introduced a proper solution to this question: os.path.commonpath(), which returns a valid path.

[Vue warn]: Cannot find element

I think the problem is your script is executed before the target dom element is loaded in the dom... one reason could be that you have placed your script in the head of the page or in a script tag that is placed before the div element #main. So when the script is executed it won't be able to find the target element thus the error.

One solution is to place your script in the load event handler like

window.onload = function () {
    var main = new Vue({
        el: '#main',
        data: {
            currentActivity: 'home'
        }
    });
}

Another syntax

window.addEventListener('load', function () {
    //your script
})

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

How to wait for the 'end' of 'resize' event and only then perform an action?

There is an elegant solution using the Underscore.js So, if you are using it in your project you can do the following -

$( window ).resize( _.debounce( resizedw, 500 ) );

This should be enough :) But, If you are interested to read more on that, you can check my blog post - http://rifatnabi.com/post/detect-end-of-jquery-resize-event-using-underscore-debounce(deadlink)

php static function

In a nutshell, you don't have the object as $this in the second case, as the static method is a function/method of the class not the object instance.

Git pushing to remote branch

You can push your local branch to a new remote branch like so:

git push origin master:test

(Assuming origin is your remote, master is your local branch name and test is the name of the new remote branch, you wish to create.)

If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u (on newer versions of Git) or --set-upstream, so:

git push -u origin master:test

or

git push --set-upstream origin master:test

...will create a new remote branch, named test, in remote repository origin, based on your local master, and setup your local master to track it.

How can I use Bash syntax in Makefile targets?

You can call bash directly within your Makefile instead of using the default shell:

bash -c "ls -al"

instead of:

ls -al

Is it possible to validate the size and type of input=file in html5

    <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>
    <script>
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more then' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct- '+fileSize+' bytes');
            }
        }else{
            alert('choose file, please');
            return false;
        }

    });
});
    </script>

http://jsfiddle.net/9bhcB/2/

Which browser has the best support for HTML 5 currently?

Ones that are built using a recent webkit build, and Presto.

Safari 3.1 for webkit
Opera for Presto.

I'm pretty sure firefox will start supporting html5 partially in 3.1

All support is extremely partial. Check here for information on what is supported.

Java - What does "\n" mean?

In the specific case of the code example from the original question, the

System.out.print("\n");

is there to move to a new line between incrementing i.

So the first print statement prints all of the elements of Grid[0][j]. When the innermost for loop has completed, the "\n" gets printed and then all of the elements of Grid[1][j] are printed on the next line, and this is repeated until you have a 10x10 grid of the elements of the 2-dimensional array, Grid.

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

How can I easily switch between PHP versions on Mac OSX?

Example: Let us switch from php 7.4 to 7.3

brew unlink [email protected]
brew install [email protected]
brew link [email protected]

If you get Warning: [email protected] is keg-only and must be linked with --force Then try with:

brew link [email protected] --force

How to change Named Range Scope

For me it works that when I create new Name tag for the same range from the Name Manager it gives me the option to change scope ;) workbook comes as default and can be changed to any of the available sheets.

What is the difference between visibility:hidden and display:none?

The difference goes beyond style and is reflected in how the elements behave when manipulated with JavaScript.

Effects and side effects of display: none:

  • the target element is taken out of the document flow (doesn't affect layout of other elements);
  • all descendants are affected (are not displayed either and cannot “snap out” of this inheritance);
  • measurements cannot be made for the target element nor for its descendants – they are not rendered at all, thus their clientWidth, clientHeight, offsetWidth, offsetHeight, scrollWidth, scrollHeight, getBoundingClientRect(), getComputedStyle(), all return 0s.

Effects and side-effects of visibility: hidden:

  • the target element is hidden from view, but is not taken out of the flow and affects layout, occupying its normal space;
  • innerText (but not innerHTML) of the target element and descendants returns empty string.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

How to inject a Map using the @Value Spring Annotation?

You can inject values into a Map from the properties file using the @Value annotation like this.

The property in the properties file.

propertyname={key1:'value1',key2:'value2',....}

In your code.

@Value("#{${propertyname}}")  private Map<String,String> propertyname;

Note the hashtag as part of the annotation.

How to pass a user / password in ansible command

I used the command

ansible -i inventory example -m ping -u <your_user_name> --ask-pass

And it will ask for your password.

For anyone who gets the error:

to use the 'ssh' connection type with passwords, you must install the sshpass program

On MacOS, you can follow below instructions to install sshpass:

  1. Download the Source Code
  2. Extract it and cd into the directory
  3. ./configure
  4. sudo make install

pandas resample documentation

B         business day frequency
C         custom business day frequency (experimental)
D         calendar day frequency
W         weekly frequency
M         month end frequency
SM        semi-month end frequency (15th and end of month)
BM        business month end frequency
CBM       custom business month end frequency
MS        month start frequency
SMS       semi-month start frequency (1st and 15th)
BMS       business month start frequency
CBMS      custom business month start frequency
Q         quarter end frequency
BQ        business quarter endfrequency
QS        quarter start frequency
BQS       business quarter start frequency
A         year end frequency
BA, BY    business year end frequency
AS, YS    year start frequency
BAS, BYS  business year start frequency
BH        business hour frequency
H         hourly frequency
T, min    minutely frequency
S         secondly frequency
L, ms     milliseconds
U, us     microseconds
N         nanoseconds

See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.

Note that there isn't a list of all the different how options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how by name.

Java Enum return Int

In my opinion the most readable version

public enum PIN_PULL_RESISTANCE {
    PULL_UP {
        @Override
        public int getValue() {
            return 1;
        }
    },
    PULL_DOWN {
        @Override
        public int getValue() {
            return 0;
        }
    };

    public abstract int getValue();
}

Show SOME invisible/whitespace characters in Eclipse

Unfortunately, you can only turn on all invisible (whitespace) characters at the same time. I suggest you file an enhancement request but I doubt they will pick it up.

The text component in Eclipse is very complicated as it is and they are not keen on making them even worse.

[UPDATE] This has been fixed in Eclipse 3.7: Go to Window > Preferences > General > Editors > Text Editors

Click on the link "whitespace characters" to fine tune what should be shown.

Kudos go to John Isaacks

How would I create a UIAlertView in Swift?

 let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
    let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
        print("Default is pressed.....")
    }
    let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel is pressed......")
    }
    let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
        print("Destructive is pressed....")

    }
    alertController.addAction(action1)
    alertController.addAction(action2)
    alertController.addAction(action3)
    self.present(alertController, animated: true, completion: nil)

}

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

@Raphael your solution does work. I encountered the same problem and solved it by increasing the maximum execution time to 180. There is an easier way to do it though:

  1. Open the Xampp control panel

  2. Click on 'config' behind 'Apache'

  3. Select 'PHP (php.ini)' from the dropdown -> A file should now open in your text editor

  4. Press ctrl+f and search for 'max_execution_time', you should fine a line which only says

    max_execution_time=30

  5. Change 30 to a bigger number (180 worked for me), like this:

    max_execution_time=180

  6. Save the file

  7. 'Stop' Apache server

  8. Close Xampp

  9. Restart Xampp

  10. 'Start' Apache server

  11. Update Wordpress from the Admin dashboard

  12. Enjoy ;)

What is the difference between "px", "dip", "dp" and "sp"?

I would only use dp.

There is a lot of talk about using "sp" for font sizes, and while I appreciate the point, I don't think that it is the right thing to do from a design point of view. You can end up breaking your design if the user has some wonky font size selection, and the user will end up blaming the app, and not their own life choices.

Also, if you take an sp-font app on a 160 dpi tablet, you will find that everything scales up... but your font, which is going to look tiny in comparison. It isn't a good look.

While the idea of "sp" fonts has a good heart, it is a poor idea. Stick with dp for everything.

regex string replace

Just change + to -:

str = str.replace(/[^a-z0-9-]/g, "");

You can read it as:

  1. [^ ]: match NOT from the set
  2. [^a-z0-9-]: match if not a-z, 0-9 or -
  3. / /g: do global match

More information:

Using regular expressions to do mass replace in Notepad++ and Vim

Notepad ++ : Search Mode = Regular expression

Find what: (.*>)(.)

Replace with: \2

Show Image View from file path?

Most of the answers are working but no one mentioned that the high resolution image will slow down the app , In my case i used images RecyclerView which was taking 0.9 GB of device memory In Just 30 Images.

I/Choreographer: Skipped 73 frames! The application may be doing too much work on its main thread.

The solution is Sipmle you can degrade the quality like here : Reduce resolution of Bitmap

But I use Simple way , Glide handles the rest of work

fanContext?.let {
            Glide.with(it)
                .load(Uri.fromFile(File(item.filePath)))
                .into(viewHolder.imagePreview)
        }

Link to the issue number on GitHub within a commit message

github adds a reference to the commit if it contains #issuenbr (discovered this by chance).

Pretty-print an entire Pandas Series / DataFrame

Try using display() function. This would automatically use Horizontal and vertical scroll bars and with this you can display different datasets easily instead of using print().

display(dataframe)

display() supports proper alignment also.

However if you want to make the dataset more beautiful you can check pd.option_context(). It has lot of options to clearly show the dataframe.

Note - I am using Jupyter Notebooks.

ActiveRecord: size vs count

Sometimes size "picks the wrong one" and returns a hash (which is what count would do)

In that case, use length to get an integer instead of hash.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

This code simply worked for me

System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox 54\\firefox.exe");
String Firefoxdriverpath = "C:\\Users\\Hp\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", Firefoxdriverpath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);

How to perform update operations on columns of type JSONB in Postgres 9.4

For those that run into this issue and want a very quick fix (and are stuck on 9.4.5 or earlier), here is a potential solution:

Creation of test table

CREATE TABLE test(id serial, data jsonb);
INSERT INTO test(data) values ('{"name": "my-name", "tags": ["tag1", "tag2"]}');

Update statement to change jsonb value

UPDATE test 
SET data = replace(data::TEXT,': "my-name"',': "my-other-name"')::jsonb 
WHERE id = 1;

Ultimately, the accepted answer is correct in that you cannot modify an individual piece of a jsonb object (in 9.4.5 or earlier); however, you can cast the jsonb column to a string (::TEXT) and then manipulate the string and cast back to the jsonb form (::jsonb).

There are two important caveats

  1. this will replace all values equaling "my-name" in the json (in the case you have multiple objects with the same value)
  2. this is not as efficient as jsonb_set would be if you are using 9.5

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

Installed SSL certificate in certificate store, but it's not in IIS certificate list

You can export a pfx from IIS on another server, if you have a server with the cert successfully installed.

Update:

Working on another round of certificate updates (a renewal) I ran into this problem again, on every server I tried. @Geir's answer didn't work, but it did give me an idea. I identified the server where I had generated the Certificate Request and successfully installed the new cert there. From that server I was able to export a pfx and then import the pfx version on the rest of the servers. No need to redo the Cert Request.

How can I have same rule for two locations in NGINX config?

This is short, yet efficient and proven approach:

location ~ (patternOne|patternTwo){ #rules etc. }

So one can easily have multiple patterns with simple pipe syntax pointing to the same location block / rules.

jQuery Scroll to Div

Could just use JQuery position function to get coordinates of your div, then use javascript scroll:

var position = $("div").position();
scroll(0,position.top);

How to $watch multiple variable change in angular

Angular 1.3 provides $watchGroup specifically for this purpose:

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchGroup

This seems to provide the same ultimate result as a standard $watch on an array of expressions. I like it because it makes the intention clearer in the code.

How to get current value of RxJS Subject or Observable?

A Subject or Observable doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable is done with it.

If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers.

It also has a method getValue() to get the current value.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

Android : How to set onClick event for Button in List item of ListView

Try This,

public View getView(final int position, View convertView,ViewGroup parent) 
{
   if(convertView == null)
   {
        LayoutInflater inflater = getLayoutInflater();
        convertView  = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
   }

   Button Button1= (Button)  convertView  .findViewById(R.id.BUTTON1_ID);

   Button1.setOnClickListener(new OnClickListener() 
   { 
       @Override
       public void onClick(View v) 
       {
           // Your code that you want to execute on this button click
       }

   });


   return convertView ;
}

It may help you....

compareTo with primitives -> Integer / int

For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.


I would do either

int cmp = a > b ? +1 : a < b ? -1 : 0;

or a longer version

int cmp;
if (a > b)
   cmp = +1;
else if (a < b)
   cmp = -1;
else
   cmp = 0;

or

int cmp = Integer.compare(a, b); // in Java 7
int cmp = Double.compare(a, b); // before Java 7

It's best not to create an object if you don't need to.

Performance wise, the first is best.

If you know for sure that you won't get an overflow you can use

int cmp = a - b; // if you know there wont be an overflow.

you won't get faster than this.

Groovy Shell warning "Could not open/create prefs root node ..."

Dennis answer is correct. However I would like to explain the solution in a bit more detailed way (for Windows User):

  1. Go into your Start Menu and type regedit into the search field.
  2. Navigate to path HKEY_LOCAL_MACHINE\Software\JavaSoft (Windows 10 seems to now have this here: HKEY_LOCAL_MACHINE\Software\WOW6432Node\JavaSoft)
  3. Right click on the JavaSoft folder and click on New -> Key
  4. Name the new Key Prefs and everything should work.

Alternatively, save and execute a *.reg file with the following content:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs]

How do I check in JavaScript if a value exists at a certain array index?

Real detection: in operator

This question age is about 10 years and it is surprising that nobody mention about this yet - however some people see the problem when we use delete operator (e.g here). This is also a little bit counter intuitive solution but the in operator which works in 'object world' can also work with arrays (because we can look on array indexes like on 'keys'...). In this way we can detect and distinct between undefined array value and value (index) removed by delete

if(index in arrayName) {
   // do stuff 
}

_x000D_
_x000D_
let arr = [0, 1, 2, 3, null, undefined,6]

delete arr[2]; // we delete element at index=2

if(2 in arr) console.log('You will not see this because idx 2 was deleted');
if(5 in arr) console.log('This is element arr[5]:', arr[5]);



// Whole array and indexes bigger than arr.length:
for(let i=0; i<=9; i++) {
  let val = (i in arr) ? arr[i] : 'empty'
  let bound = i<arr.length ? '' : '(out of range)'
  console.log(`${i} value: `, val, bound);
}


console.log('Look on below aray on chrome console (not in SO snippet console)');
console.log('typeof arr:', typeof arr);
console.log(arr);
_x000D_
_x000D_
_x000D_

Chrome console reveals some info about snippet array with deleted index 2 - this index actually not exists at all (!!!) (same way as key is removed from object). What is also interesting here array is viewd as key-value pairs (we even see 'length' key). It is also interesting that typeof arr is Object (!!!), the delete and in operator works like for JS objects (also square brackets notation arr[idx] and obj[key] is similar) - so it looks like array is some special JS object in the core.

enter image description here

To get similar effect without delete define array as follows

[0, 1,, 3, null, undefined, 6] // pay attention to double comma: ",,"

How do I uninstall a package installed using npm link?

The package can be uninstalled using the same uninstall or rm command that can be used for removing installed packages. The only thing to keep in mind is that the link needs to be uninstalled globally - the --global flag needs to be provided.

In order to uninstall the globally linked foo package, the following command can be used (using sudo if necessary, depending on your setup and permissions)

sudo npm rm --global foo

This will uninstall the package.

To check whether a package is installed, the npm ls command can be used:

npm ls --global foo

Remove legend ggplot 2.2

As the question and user3490026's answer are a top search hit, I have made a reproducible example and a brief illustration of the suggestions made so far, together with a solution that explicitly addresses the OP's question.

One of the things that ggplot2 does and which can be confusing is that it automatically blends certain legends when they are associated with the same variable. For instance, factor(gear) appears twice, once for linetype and once for fill, resulting in a combined legend. By contrast, gear has its own legend entry as it is not treated as the same as factor(gear). The solutions offered so far usually work well. But occasionally, you may need to override the guides. See my last example at the bottom.

# reproducible example:
library(ggplot2)
p <- ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) + 
theme_bw() 

enter image description here

Remove all legends: @user3490026

p + theme(legend.position = "none")

Remove all legends: @duhaime

p + guides(fill = FALSE, color = FALSE, linetype = FALSE, shape = FALSE)

Turn off legends: @Tjebo

ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs), show.legend = FALSE) +
geom_point(aes(shape = factor(cyl)), show.legend = FALSE) +
geom_line(aes(linetype = factor(gear)), show.legend = FALSE) +
geom_smooth(aes(fill = factor(gear), color = gear), show.legend = FALSE) + 
theme_bw() 

Remove fill so that linetype becomes visible

p + guides(fill = FALSE)

Same as above via the scale_fill_ function:

p + scale_fill_discrete(guide = FALSE)

And now one possible answer to the OP's request

"to keep the legend of one layer (smooth) and remove the legend of the other (point)"

Turn some on some off ad-hoc post-hoc

p + guides(fill = guide_legend(override.aes = list(color = NA)), 
           color = FALSE, 
           shape = FALSE)  

enter image description here

php codeigniter count rows

If you really want to count all rows. You can use this in model function:

$this->db->select('count(*)');
$query = $this->db->get('home');
$cnt = $query->row_array();
return $cnt['count(*)'];

It returns single value, that is row count

"Invalid signature file" when attempting to run a .jar

In case you're using gradle, here is a full farJar task:

version = '1.0'
//create a single Jar with all dependencies
task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Title': 'Gradle Jar File Example',  
            'Implementation-Version': version,
            'Main-Class': 'com.example.main'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA' 
    with jar
}

Spring boot - Not a managed type

I had some problem while migrating from Spring boot 1.3.x to 1.5, I got it working after updating entity package at EntityManagerFactory bean

  @Bean(name="entityManagerFactoryDef")
  @Primary
  public LocalContainerEntityManagerFactoryBean defaultEntityManager() {
      Map map = new HashMap();
      map.put("hibernate.default_schema", env.getProperty("spring.datasource.username"));
      map.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
      LocalContainerEntityManagerFactoryBean em = createEntityManagerFactoryBuilder(jpaVendorProperties())
              .dataSource(primaryDataSource()).persistenceUnit("default").properties(map).build();
      em.setPackagesToScan("com.simple.entity");
      em.afterPropertiesSet();
      return em;
  }

This bean referred in Application class as below

@SpringBootApplication
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryDef")
public class SimpleApp {

}

Split text with '\r\n'

I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.

the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r

var serials = model.List.Replace("\n","").Split('\r').ToList<string>();

I like this approach because you can do it in just one line.

Split Spark Dataframe string column into multiple columns

pyspark.sql.functions.split() is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem() to retrieve each part of the array as a column itself:

split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))

The result will be:

col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
  18 |  856-yygrm |   856 | yygrm
 201 |  777-psgdg |   777 | psgdg

I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.

Find an element in a list of tuples

Or takewhile, ( addition to this, example of more values is shown ):

>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>> 

if unsorted, like:

>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>> 

Moment.js get day name from date

code

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');
console.log(weekDayName);

mydate is the input date. The variable weekDayName get the name of the day. Here the output is

Output

Wednesday

_x000D_
_x000D_
var mydate = "2017-08-30T00:00:00";_x000D_
console.log(moment(mydate).format('dddd'));_x000D_
console.log(moment(mydate).format('ddd'));_x000D_
console.log('Day in number[0,1,2,3,4,5,6]: '+moment(mydate).format('d'));_x000D_
console.log(moment(mydate).format('MMM'));_x000D_
console.log(moment(mydate).format('MMMM'));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You can find more debugging info just simply adding the option -loglevel debug, full command will be

ffmpeg -i INPUT OUTPUT -loglevel debug -v verbose

disable textbox using jquery?

This thread is a bit old but the information should be updated.

http://api.jquery.com/attr/

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

$("#radiobutt input[type=radio]").each(function(i){
$(this).click(function () {
    if(i==2) { //3rd radiobutton
        $("#textbox1").prop("disabled", true); 
        $("#checkbox1").prop("disabled", true); 
    }
    else {
        $("#textbox1").prop("disabled", false); 
        $("#checkbox1").prop("disabled", false);
    }
  });
});

How can I brew link a specific version?

I asked in #machomebrew and learned that you can switch between versions using brew switch.

$ brew switch libfoo mycopy 

to get version mycopy of libfoo.

Better way to remove specific characters from a Perl string

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

Try it like,

<?php 
    $name='your name';
    echo '<table>
       <tr><th>Name</th></tr>
       <tr><td>'.$name.'</td></tr>
    </table>';
?>

Updated

<?php 
    echo '<table>
       <tr><th>Rst</th><th>Marks</th></tr>
       <tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
    </table>';
?>

How to install PyQt4 in anaconda?

Updated version of @Alaaedeen's answer. You can specify any part of the version of any package you want to install. This may cause other package versions to change. For example, if you don't care about which specific version of PyQt4 you want, do:

conda install pyqt=4

This would install the latest minor version and release of PyQt 4. You can specify any portion of the version that you want, not just the major number. So, for example

conda install pyqt=4.11

would install the latest (or last) release of version 4.11.

Keep in mind that installing a different version of a package may cause the other packages that depend on it to be rolled forward or back to where they support the version you want.

SharePoint : How can I programmatically add items to a custom list instance

I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),

1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install

2- Add "using Microsoft.SharePoint.Client; "

then the below code

        string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
        SecureString passWord = new SecureString();

        var password = "Your password here";
        var securePassword = new SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        ClientContext clientContext = new ClientContext(siteUrl);
        clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
        List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
        ListItem oListItem = oList.AddItem(itemCreateInfo);
        oListItem["PK"] = "1";
        oListItem["Precinct"] = "Mangere";
        oListItem["Title"] = "Innovation";
        oListItem["Project_x005F_x0020_Name"] = "test from C#";
        oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
        oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
        oListItem.Update();

        clientContext.ExecuteQuery();

Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?

A few approaches:

1- Use MS flow and see them

2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column

3- Use a C# reader and read your sharepoint list

The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)

Tomcat 7: How to set initial heap size correctly?

Use following command to increase java heap size for tomcat7 (linux distributions) correctly:

echo 'export CATALINA_OPTS="-Xms512M -Xmx1024M"' > /usr/share/tomcat7/bin/setenv.sh

JavaScript/jQuery - How to check if a string contain specific words

In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

HTML5 Audio Looping

var audio = new Audio("http://rho.nu/pub/Game%20Of%20Thrones%20-%20Main%20Theme%20-%20Soundtrack.mp3");

audio.addEventListener('canplaythrough', function() {
    this.currentTime = this.duration - 10;
    this.loop = true;
    this.play();
});

Just set loop = true in the canplaythrough eventlistener.

http://jsbin.com/ciforiwano/1/edit?html,css,js,output

How to convert from int to string in objective c: example code

== shouldn't be used to compare objects in your if. For NSString use isEqualToString: to compare them.

How to run a C# application at Windows startup?

OK here are my 2 cents: try passing path with each backslash as double backslash. I have found sometimes calling WIN API requires that.

How to execute two mysql queries as one in PHP/MYSQL?

Update: Apparently possible by passing a flag to mysql_connect(). See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_-class of functions and prefer PDO.

You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.

For the record, it can be done using mysqli and the mysqli_multi_query-function.

How do I make this file.sh executable via double click?

You can just tell Finder to open the .sh file in Terminal:

  1. Select the file
  2. Get Info (cmd-i) on it
  3. In the "Open with" section, choose "Other…" in the popup menu
  4. Choose Terminal as the application

This will have the exact same effect as renaming it to .command except… you don't have to rename it :)

array of string with unknown size

I think you may be looking for the StringBuilder class. If not, then the generic List class in string form:

List<string> myStringList = new List<string();
myStringList.Add("Test 1");
myStringList.Add("Test 2");

Or, if you need to be absolutely sure that the strings remain in order:

Queue<string> myStringInOriginalOrder = new Queue<string();
myStringInOriginalOrder.Enqueue("Testing...");
myStringInOriginalOrder.Enqueue("1...");
myStringInOriginalOrder.Enqueue("2...");
myStringInOriginalOrder.Enqueue("3...");

Remember, with the List class, the order of the items is an implementation detail and you are not guaranteed that they will stay in the same order you put them in.

Logical operators ("and", "or") in DOS batch

OR is slightly tricky, but not overly so. Here is an example

set var1=%~1
set var2=%~2
::
set or_=
if "%var1%"=="Stack" set or_=true
if "%var2%"=="Overflow" set or_=true
if defined or_ echo Stack OR Overflow

Using a PagedList with a ViewModel ASP.Net MVC

For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.

Repository

    public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
    {
        List<Order> orders = new List<Order>();
        using (DatabaseContext db = new DatabaseContext())
        {
            orders = (from o in db.Orders
                      orderby o.Date descending //use orderby, otherwise Skip will throw an error
                      select o)
                      .Skip(itemsPerPage * page).Take(itemsPerPage)
                      .ToList();
            totalCount = db.Orders.Count();//return the number of pages
        }
        return orders;//the query is now already executed, it is a subset of all the orders.
    }

Controller

    public ActionResult Index(int? page)
    {
        int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
        OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
        int totalCount = 0;
        List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
        List<OrderViewModel> orderViews = new List<OrderViewModel>();
        foreach(Order order in orders)//convert your models to some view models.
        {
            orderViews.Add(orderMan.GenerateOrderViewModel(order));
        }
        //create staticPageList, defining your viewModel, current page, page size and total number of pages.
        IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
        return View(pageOrders);
    }

View

@using PagedList.Mvc;
@using PagedList; 

@model IPagedList<Babywatcher.Core.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container-fluid">
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @if (Model.Count > 0)
    {


        <table class="table">
          <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().orderId)
            </th>
            <!--rest of your stuff-->
        </table>

    }
    else
    {
        <p>No Orders yet.</p>
    }
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>

Bonus

Do above first, then perhaps use this!

Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).

Repository

In your order repository (in my case), add a static method to convert a model:

public static OrderModel ConvertToModel(Order entity)
{
    if (entity == null) return null;
    OrderModel model = new OrderModel
    {
        ContactId = entity.contactId,
        OrderId = entity.orderId,
    }
    return model;
}

Below your repository class, add this:

public static partial class Ex
{
    public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
    {
        bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
        return source.Select(x => new OrderModel
        {
            OrderId = x.orderId,
            //example use ConvertToModel of some other repository
            BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
            //example use another extension of some other repository
            Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
        });
    }
}

And then in your GetOrderPage method:

    public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
        out int totalCount)
    {
        IQueryable<Order> query = DbContext.Orders; //get queryable from db
        .....//do your filtering, sorting, paging (do not use .ToList() yet)

        return queryOrders.SelectOrderModel().AsEnumerable();
        //or, if you want to include relations
        return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
        //notice difference, first ToList(), then SelectOrderModel().
    }

Let me explain:

The static ConvertToModel method can be accessed by any other repository, as used above, I use ConvertToModel from some AddressRepository.

The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.

Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel() extension, includeRelations inside the extension will be true because the source is NOT a database query type (not an linq-to-sql IQueryable). When this is true, the extension can call other methods/extensions throughout your application for converting models.

Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList() yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations will be false so that it doesn't call other c# methods that SQL doesn't understand.

It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include() extra will load the relations.

jQuery - disable selected options

This seems to work:

$("#theSelect").change(function(){          
    var value = $("#theSelect option:selected").val();
    var theDiv = $(".is" + value);

    theDiv.slideDown().removeClass("hidden");
    //Add this...
    $("#theSelect option:selected").attr('disabled', 'disabled');
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    //...and this.
    $("#theSelect option:disabled").removeAttr('disabled');
});

Typescript import/as vs import/require?

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

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

I've copy/pasted the answer from this question here, and changed the names and spelling to fit this question.

Here is code to measure what is being asked:

#include <iostream>

struct string
{
    string() {}
    string(const string&) {std::cout << "string(const string&)\n";}
    string& operator=(const string&) {std::cout << "string& operator=(const string&)\n";return *this;}
#if (__has_feature(cxx_rvalue_references))
    string(string&&) {std::cout << "string(string&&)\n";}
    string& operator=(string&&) {std::cout << "string& operator=(string&&)\n";return *this;}
#endif

};

#if PROCESS == 1

string
do_something(string inval)
{
    // do stuff
    return inval;
}

#elif PROCESS == 2

string
do_something(const string& inval)
{
    string return_val = inval;
    // do stuff
    return return_val; 
}

#if (__has_feature(cxx_rvalue_references))

string
do_something(string&& inval)
{
    // do stuff
    return std::move(inval);
}

#endif

#endif

string source() {return string();}

int main()
{
    std::cout << "do_something with lvalue:\n\n";
    string x;
    string t = do_something(x);
#if (__has_feature(cxx_rvalue_references))
    std::cout << "\ndo_something with xvalue:\n\n";
    string u = do_something(std::move(x));
#endif
    std::cout << "\ndo_something with prvalue:\n\n";
    string v = do_something(source());
}

For me this outputs:

$ clang++ -std=c++11 -stdlib=libc++ -DPROCESS=1 test.cpp
$ a.out
do_something with lvalue:

string(const string&)
string(string&&)

do_something with xvalue:

string(string&&)
string(string&&)

do_something with prvalue:

string(string&&)
$ clang++ -std=c++11 -stdlib=libc++ -DPROCESS=2 test.cpp
$ a.out
do_something with lvalue:

string(const string&)

do_something with xvalue:

string(string&&)

do_something with prvalue:

string(string&&)

The table below summarizes my results (using clang -std=c++11). The first number is the number of copy constructions and the second number is the number of move constructions:

+----+--------+--------+---------+
|    | lvalue | xvalue | prvalue |
+----+--------+--------+---------+
| p1 |  1/1   |  0/2   |   0/1   |
+----+--------+--------+---------+
| p2 |  1/0   |  0/1   |   0/1   |
+----+--------+--------+---------+

The pass-by-value solution requires only one overload but costs an extra move construction when passing lvalues and xvalues. This may or may not be acceptable for any given situation. Both solutions have advantages and disadvantages.

When should I use git pull --rebase?

Just remember:

  • pull = fetch + merge
  • pull --rebase = fetch + rebase

So, choose the way what you want to handle your branch.

You'd better know the difference between merge and rebase :)

How to convert the background to transparent?

For Photoshop you need to download Photoshop portable.... Load image e press "w" click in image e suave as png or gif....

Altering a column to be nullable

If this was MySQL syntax, the type would have been missing, as some other responses point out. Correct MySQL syntax would have been:

ALTER TABLE Merchant_Pending_Functions MODIFY NumberOfLocations INT NULL

Posting here for clarity to MySQL users.

Pandas Split Dataframe into two Dataframes at a specific row

I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.

import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)

np.split(df, [100,200,300], axis=0] wants explicit index numbers which may or may not be desirable.

How does a ArrayList's contains() method evaluate objects?

Just wanted to note that the following implementation is wrong when value is not a primitive type:

public class Thing
{
    public Object value;  

    public Thing (Object x)
    {
        this.value = x;
    }

    @Override
    public boolean equals(Object object)
    {
        boolean sameSame = false;

        if (object != null && object instanceof Thing)
        {
            sameSame = this.value == ((Thing) object).value;
        }

        return sameSame;
    }
}

In that case I propose the following:

public class Thing {
    public Object value;  

    public Thing (Object x) {
        value = x;
    }

    @Override
    public boolean equals(Object object) {

        if (object != null && object instanceof Thing) {
            Thing thing = (Thing) object;
            if (value == null) {
                return (thing.value == null);
            }
            else {
                return value.equals(thing.value);
            }
        }

        return false;
    }
}

APK signing error : Failed to read key from keystore

Removing double-quotes solve my problem, now its:

DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug

Creating a PDF from a RDLC Report in the Background

You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:

var lr = new LocalReport
{
    ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? @"C:\", "Reports", "PathOfMyReport.rdlc"),
    EnableExternalImages = true
};

lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));

string mimeType, encoding, extension;

Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
    (
        "PDF",
        @"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
        out mimeType,
        out encoding,
        out extension,
        out streams,
        out warnings
    );

var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));

var idx = 0;
while (File.Exists(saveAs))
{
    idx++;
    saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}

using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
    stream.Write(renderedBytes, 0, renderedBytes.Length);
    stream.Close();
}

lr.Dispose();

You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

How to reload a div without reloading the entire page?

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

Why doesn't java.util.Set have get(int index)?

You can do new ArrayList<T>(set).get(index)

How to extract epoch from LocalDate and LocalDateTime?

Look at this method to see which fields are supported. You will find for LocalDateTime:

•NANO_OF_SECOND 
•NANO_OF_DAY 
•MICRO_OF_SECOND 
•MICRO_OF_DAY 
•MILLI_OF_SECOND 
•MILLI_OF_DAY 
•SECOND_OF_MINUTE 
•SECOND_OF_DAY 
•MINUTE_OF_HOUR 
•MINUTE_OF_DAY 
•HOUR_OF_AMPM 
•CLOCK_HOUR_OF_AMPM 
•HOUR_OF_DAY 
•CLOCK_HOUR_OF_DAY 
•AMPM_OF_DAY 
•DAY_OF_WEEK 
•ALIGNED_DAY_OF_WEEK_IN_MONTH 
•ALIGNED_DAY_OF_WEEK_IN_YEAR 
•DAY_OF_MONTH 
•DAY_OF_YEAR 
•EPOCH_DAY 
•ALIGNED_WEEK_OF_MONTH 
•ALIGNED_WEEK_OF_YEAR 
•MONTH_OF_YEAR 
•PROLEPTIC_MONTH 
•YEAR_OF_ERA 
•YEAR 
•ERA 

The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate (with even less supported fields).

If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.

Coming back to your question and the numbers in your code:

The result 1605 is correct
  => (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1

16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).

UPDATE after given timezone info:

local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861

As JSR-310-code with two equivalent approaches:

long secondsSinceUnixEpoch1 =
  LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();

long secondsSinceUnixEpoch2 =
  LocalDate
    .of(2014, 2, 4)
    .atTime(19, 51, 1)
    .atZone(ZoneId.of("Europe/Oslo"))
    .toEpochSecond();

Installing SetupTools on 64-bit Windows

Apparently (having faced related 64- and 32-bit issues on OS X) there is a bug in the Windows installer. I stumbled across this workaround, which might help - basically, you create your own registry value HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.6\InstallPath and copy over the InstallPath value from HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath. See the answer below for more details.

If you do this, beware that setuptools may only install 32-bit libraries.

NOTE: the responses below offer more detail, so please read them too.

Mips how to store user input string

Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:

         .text
         .globl __start
    __start:
         la $a0,str1 #Load and print string asking for string
         li $v0,4
         syscall

         li $v0,8 #take in input
         la $a0, buffer #load byte space into address
         li $a1, 20 # allot the byte space for string
         move $t0,$a0 #save string to t0
         syscall

         la $a0,str2 #load and print "you wrote" string
         li $v0,4
         syscall

         la $a0, buffer #reload byte space to primary address
         move $a0,$t0 # primary address = t0 address (load pointer)
         li $v0,4 # print string
         syscall

         li $v0,10 #end program
         syscall


               .data
             buffer: .space 20
             str1:  .asciiz "Enter string(max 20 chars): "
             str2:  .asciiz "You wrote:\n"
             ###############################
             #Output:
             #Enter string(max 20 chars): qwerty 123
             #You wrote:
             #qwerty 123
             #Enter string(max 20 chars):   new world oreddeYou wrote:
             #  new world oredde //lol special character
             ###############################

How can I resolve the error: "The command [...] exited with code 1"?

Check your paths: If you are using a separate build server for TFS (most likely), make sure that all your paths in the .csproj file match the TFS server paths. I got the above error when checking in the *.csproj file when it had references to my development machine paths and not the TFS server paths.

Remove multi-line commands: Also, try and remove multi-line commands into single-line commands in xml as a precaution. I had the following xml in the *.proj that caused issues in TFS:

<Exec Condition="bl.." 
Command=" Blah...
..." </Exec>

Changing the above xml to this worked:

  <Exec Condition="bl.." Command=" Blah..." </Exec>

Standard way to embed version into python package?

I use a JSON file in the package dir. This fits Zooko's requirements.

Inside pkg_dir/pkg_info.json:

{"version": "0.1.0"}

Inside setup.py:

from distutils.core import setup
import json

with open('pkg_dir/pkg_info.json') as fp:
    _info = json.load(fp)

setup(
    version=_info['version'],
    ...
    )

Inside pkg_dir/__init__.py:

import json
from os.path import dirname

with open(dirname(__file__) + '/pkg_info.json') as fp:
    _info = json.load(fp)

__version__ = _info['version']

I also put other information in pkg_info.json, like author. I like to use JSON because I can automate management of metadata.

Is it possible in Java to access private fields via reflection

Yes.

  Field f = Test.class.getDeclaredField("str");
  f.setAccessible(true);//Very important, this allows the setting to work.
  String value = (String) f.get(object);

Then you use the field object to get the value on an instance of the class.

Note that get method is often confusing for people. You have the field, but you don't have an instance of the object. You have to pass that to the get method

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

How do you change the size of figures drawn with matplotlib?

This works well for me:

from matplotlib import pyplot as plt

F = plt.gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.
plt.show() # or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array

This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html

Multiple actions were found that match the request in Web Api

For example => TestController

        [HttpGet]
        public string TestMethod(int arg0)
        {
            return "";
        }

        [HttpGet]
        public string TestMethod2(string arg0)
        {
            return "";
        }

        [HttpGet]
        public string TestMethod3(int arg0,string arg1)
        {
            return "";
        }

If you can only change WebApiConfig.cs file.

 config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/",
                defaults: null
            );

Thats it :)

And Result : enter image description here

Simulate Keypress With jQuery

The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

http://docs.jquery.com/Events/trigger#eventdata

Read the above documentation for more details.

How to restore default perspective settings in Eclipse IDE

Alt+w-->or click on window tab -->ResetPerspective

Finding all possible permutations of a given string in python

Here's a really simple generator version:

def find_all_permutations(s, curr=[]):
    if len(s) == 0:
        yield curr
    else:
        for i, c in enumerate(s):
            for combo in find_all_permutations(s[:i]+s[i+1:], curr + [c]):
                yield "".join(combo)

I think it's not so bad!

creating json object with variables

You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

var formObject = {
    formObject: [
        {
            firstName:firstName,  // no need to quote variable names
            lastName:lastName
        },
        {
            phoneNumber:phoneNumber,
            address:address
        }
    ]
};

This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

How can I time a code segment for testing performance with Pythons timeit?

Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.

And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).

That said, you can simply put your code in a function and run that function with timeit.timeit():

def function_to_repeat():
    # ...

duration = timeit.timeit(function_to_repeat, number=1000)

This would disable the garbage collection, repeatedly call the function_to_repeat() function, and time the total duration of those calls using timeit.default_timer(), which is the most accurate available clock for your specific platform.

You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup argument to either import or create those dependencies, and pass them into your function:

def function_to_repeat(var1, var2):
    # ...

duration = timeit.timeit(
    'function_to_repeat(var1, var2)',
    'from __main__ import function_to_repeat, var1, var2', 
    number=1000)

would grab the globals function_to_repeat, var1 and var2 from your script and pass those to the function each repetition.

Difference Between Select and SelectMany

Here is a code example with an initialized small collection for testing:

class Program
{
    static void Main(string[] args)
    {
        List<Order> orders = new List<Order>
        {
            new Order
            {
                OrderID = "orderID1",
                OrderLines = new List<OrderLine>
                {
                    new OrderLine
                    {
                        ProductSKU = "SKU1",
                        Quantity = 1
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU2",
                        Quantity = 2
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU3",
                        Quantity = 3
                    }
                }
            },
            new Order
            {
                OrderID = "orderID2",
                OrderLines = new List<OrderLine>
                {
                    new OrderLine
                    {
                        ProductSKU = "SKU4",
                        Quantity = 4
                    },
                    new OrderLine
                    {
                        ProductSKU = "SKU5",
                        Quantity = 5
                    }
                }
            }
        };

        //required result is the list of all SKUs in orders
        List<string> allSKUs = new List<string>();

        //With Select case 2 foreach loops are required
        var flattenedOrdersLinesSelectCase = orders.Select(o => o.OrderLines);
        foreach (var flattenedOrderLine in flattenedOrdersLinesSelectCase)
        {
            foreach (OrderLine orderLine in flattenedOrderLine)
            {
                allSKUs.Add(orderLine.ProductSKU);
            }
        }

        //With SelectMany case only one foreach loop is required
        allSKUs = new List<string>();
        var flattenedOrdersLinesSelectManyCase = orders.SelectMany(o => o.OrderLines);
        foreach (var flattenedOrderLine in flattenedOrdersLinesSelectManyCase)
        {
            allSKUs.Add(flattenedOrderLine.ProductSKU);
        }

       //If the required result is flattened list which has OrderID, ProductSKU and Quantity,
       //SelectMany with selector is very helpful to get the required result
       //and allows avoiding own For loops what according to my experience do code faster when
       // hundreds of thousands of data rows must be operated
        List<OrderLineForReport> ordersLinesForReport = (List<OrderLineForReport>)orders.SelectMany(o => o.OrderLines,
            (o, ol) => new OrderLineForReport
            {
                OrderID = o.OrderID,
                ProductSKU = ol.ProductSKU,
                Quantity = ol.Quantity
            }).ToList();
    }
}
class Order
{
    public string OrderID { get; set; }
    public List<OrderLine> OrderLines { get; set; }
}
class OrderLine
{
    public string ProductSKU { get; set; }
    public int Quantity { get; set; }
}
class OrderLineForReport
{
    public string OrderID { get; set; }
    public string ProductSKU { get; set; }
    public int Quantity { get; set; }
}

android start activity from service

UPDATE ANDROID 10 AND HIGHER

Start an activity from service (foreground or background) is no longer allowed.

There are still some restrictions that can be seen in the documentation

https://developer.android.com/guide/components/activities/background-starts

How to return a value from pthread threads in C?

Here is a correct solution. In this case tdata is allocated in the main thread, and there is a space for the thread to place its result.

#include <pthread.h>
#include <stdio.h>

typedef struct thread_data {
   int a;
   int b;
   int result;

} thread_data;

void *myThread(void *arg)
{
   thread_data *tdata=(thread_data *)arg;

   int a=tdata->a;
   int b=tdata->b;
   int result=a+b;

   tdata->result=result;
   pthread_exit(NULL);
}

int main()
{
   pthread_t tid;
   thread_data tdata;

   tdata.a=10;
   tdata.b=32;

   pthread_create(&tid, NULL, myThread, (void *)&tdata);
   pthread_join(tid, NULL);

   printf("%d + %d = %d\n", tdata.a, tdata.b, tdata.result);   

   return 0;
}

disable Bootstrap's Collapse open/close animation

If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...

Just add this somewhere in your code:

$(document).ready(
    $('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
        e.preventDefault();
    }),
    $('[data-toggle="collapse"]').on('click', function(e) {
        e.preventDefault();
        $($(this).data('target')).toggleClass('in');
    })
);

How to have the formatter wrap code with IntelliJ?

Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.

Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin.

Python: count repeated elements in the list

This works for Python 2.6.6

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result

prints

{'a': 2, 'b': 1}

Why can't I do <img src="C:/localfile.jpg">?

what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().

How to get a random value from dictionary?

To select 50 random key values from a dictionary set dict_data:

sample = random.sample(set(dict_data.keys()), 50)

Capture characters from standard input without waiting for enter to be pressed

The following is a solution extracted from Expert C Programming: Deep Secrets, which is supposed to work on SVr4. It uses stty and ioctl.

#include <sys/filio.h>
int kbhit()
{
 int i;
 ioctl(0, FIONREAD, &i);
 return i; /* return a count of chars available to read */
}
main()
{
 int i = 0;
 intc='';
 system("stty raw -echo");
 printf("enter 'q' to quit \n");
 for (;c!='q';i++) {
    if (kbhit()) {
        c=getchar();
       printf("\n got %c, on iteration %d",c, i);
    }
}
 system("stty cooked echo");
}

How to get last N records with activerecord?

In my rails (rails 4.2) project, I use

Model.last(10) # get the last 10 record order by id

and it works.

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

Convert double to float in Java

The problem is, your value cannot be stored accurately in single precision floating point type. Proof:

public class test{
    public static void main(String[] args){
        Float a = Float.valueOf("23423424666767");
        System.out.printf("%f\n", a); //23423424135168,000000
        System.out.println(a);        //2.34234241E13
    }
}

Another thing is: you don't get "2.3423424666767E13", it's just the visual representation of the number stored in memory. "How you print out" and "what is in memory" are two distinct things. Example above shows you how to print the number as float, which avoids scientific notation you were getting.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

sending email via php mail function goes to spam

If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.

How to automatically crop and center an image

I was looking for a pure CSS solution using img tags (not the background image way).

I found this brilliant way to achieve the goal on crop thumbnails with css:

.thumbnail {
  position: relative;
  width: 200px;
  height: 200px;
  overflow: hidden;
}
.thumbnail img {
  position: absolute;
  left: 50%;
  top: 50%;
  height: 100%;
  width: auto;
  -webkit-transform: translate(-50%,-50%);
      -ms-transform: translate(-50%,-50%);
          transform: translate(-50%,-50%);
}
.thumbnail img.portrait {
  width: 100%;
  height: auto;
}

It is similar to @Nathan Redblur's answer but it allows for portrait images, too.

Works like a charm for me. The only thing you need to know about the image is whether it is portrait or landscape in order to set the .portrait class so I had to use a bit of Javascript for this part.

Regular expression to check if password is "8 characters including 1 uppercase letter, 1 special character, alphanumeric characters"

The regular expression you are after will most likely be huge and a nightmare to maintain especially for people who are not that familiar with regular expressions.

I think it would be easier to break your regex down and do it one bit at a time. It might take a bit more to do, but I am pretty sure that maintaining it and debugging it would be easier. This would also allow you to provide more directed error messages to your users (other than just Invalid Password) which should improve user experience.

From what I am seeing you are pretty fluent in regex, so I would presume that giving you the regular expressions to do what you need would be futile.

Seeing your comment, this is how I would go about it:

  • Must be eight characters Long: You do not need a regex for this. Using the .Length property should be enough.

  • Including one uppercase letter: You can use the [A-Z]+ regular expression. If the string contains at least one upper case letter, this regular expression will yield true.

  • One special character: You can use either the \W which will match any character which is not a letter or a number or else, you can use something like so [!@#] to specify a custom list of special characters. Note though that characters such as $, ^, ( and ) are special characters in the regular expression language, so they need to be escaped like so: \$. So in short, you might use the \W.

  • Alphanumeric characters: Using the \w+ should match any letter and number and underscore.

Take a look at this tutorial for more information.

Getting values from query string in an url using AngularJS $location

Very late answer :( but for someone who is in need, this works Angular js works too :) URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

FYI: IE is not supported

use this function from instead of URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit

How to draw a dotted line with css?

Try dashed...

<hr style="border-top: 2px dashed black;color:transparent;"/>

Circular (or cyclic) imports in Python

There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.

Imports are pretty straightforward really. Just remember the following:

'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line.

If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed.

If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty.

Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.

Take that lot together and you shouldn't get any surprises when importing modules.

Detecting a long press with Android

setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {

                int action = MotionEventCompat.getActionMasked(event);


                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        longClick = false;
                        x1 = event.getX();
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (event.getEventTime() - event.getDownTime() > 500 && Math.abs(event.getX() - x1) < MIN_DISTANCE) {
                            longClick = true;
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                                if (longClick) {
                                    Toast.makeText(activity, "Long preess", Toast.LENGTH_SHORT).show();
                                } 
                }
                return true;
            }
        });

Maven Error: Could not find or load main class

this worked for me....

I added the following line to properties in pom.xml

<properties>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>

Adding div element to body or document in JavaScript

Using Javascript

var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);

Using jQuery

$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');

How to add form validation pattern in Angular 2?

You could build your form using FormBuilder as it let you more flexible way to configure form.

export class MyComp {
  form: ControlGroup;

  constructor(@Inject()fb: FormBuilder) {  
    this.form = fb.group({  
      foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]  
    });  
  }

Then in your template :

<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div> 

You can also customize ng-invalid CSS class.

As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.

export class MyValidators {
  static regex(pattern: string): Function {
    return (control: Control): {[key: string]: any} => {
      return control.value.match(pattern) ? null : {pattern: true};
    };
  }
}

Hope that it help you.

Set background image in CSS using jquery

Remove the semi-colon after no-repeat, in the url and try it .

$("#globalsearchstr").focus(function(){
    $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");
});

svn over HTTP proxy

svn:// doesn't talk http, therefor there's nothing a http proxy could do.

Any reason why http doesn't work? Have you considered https? If you really need it, you probably have to have port 3690 opened in your firewall.

Linq order by, group by and order by each group?

Alternatively you can do like this :

     var _items = from a in StudentsGrades
                  group a by a.Name;

     foreach (var _itemGroup in _items)
     {
        foreach (var _item in _itemGroup.OrderBy(a=>a.grade))
        {
           ------------------------
           --------------------------
        }
     }

Check/Uncheck checkbox with JavaScript

Try This:

//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');

//UnCheck
document.getElementById('chk').removeAttribute('checked');

How to throw a C++ exception

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

How to use registerReceiver method?

The whole code if somebody need it.

void alarm(Context context, Calendar calendar) {
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);

    final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
    IntentFilter intentFilter = new IntentFilter(SOME_ACTION);

    AlarmReceiver mReceiver = new AlarmReceiver();
    context.registerReceiver(mReceiver, intentFilter);

    Intent anotherIntent = new Intent(SOME_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
    alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

    Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}

class AlarmReceiver extends BroadcastReceiver {     
    @Override
    public void onReceive(Context context, Intent arg1) {
        Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
    }
}

Why doesn't the height of a container element increase if it contains floated elements?

You need to add overflow:auto to your parent div for it to encompass the inner floated div:

<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange;overflow:auto">
    <div style="width:500px; height:200px; background-color:black; float:right">
    </div>
</div>

jsFiddle example

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

I have had the same issues since before, but today I had to set up one new server. What I could learn in this time...

The basic process to allow authentication without a password is as follows:

  1. On the server, validate if your home folder has the .ssh folder. If it doesn't exist, you can create it manually with a mkdir command and then to assign the correct permissions with chmod, or otherwise you could use the same utility, ssh-keygen, to create private/public keys, but on the server for your user. This process will create the required .ssh folder.

  2. On the local machine you also need to create the private/public keys with the ssh-keygen utility.

  3. You need to move your public key to file .ssh/authorized_keys to the server. To achieve this, you can use the ssh-copy-id utility, or you can do it manually using the cat and scp commands.

  4. In the best of cases, this will allow connect to your server without a password.

OK, now the issues that I found today: first there are several key generation algorithms: rsa, dsa, ecdsa and ed25519 and there are many releases of OpenSSH (you can have one version on your local machine and an old version on your server):

Hint: Using ssh -v helps to see additional information when you are connecting to the server.

OpenSSH_8.2p1 Ubuntu-4, OpenSSL 1.1.1f 31 Mar 2020

debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3

The error in my case today was that I was trying to use a key with a "newer" generation algorithm that was not supported by the installed version of OpenSSH on the server. When I had checked the supported algorithms, another error that I found was that the server was rejecting my algorithm:

debug1: Skipping ssh-dss key /home/user/.ssh/id_dsa - not in PubkeyAcceptedKeyTypes

After that, I had to change the algorithm of my key and then I could connect with the server successfully.

OpenSSH releases notes: Link

Disable clipboard prompt in Excel VBA on workbook close

I can offer two options

  1. Direct copy

Based on your description I'm guessing you are doing something like

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy
ThisWorkbook.Sheets("SomeSheet").Paste
wb2.close

If this is the case, you don't need to copy via the clipboard. This method copies from source to destination directly. No data in clipboard = no prompt

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy ThisWorkbook.Sheets("SomeSheet").Cells(<YourCell")
wb2.close
  1. Suppress prompt

You can prevent all alert pop-ups by setting

Application.DisplayAlerts = False

[Edit]

  1. To copy values only: don't use copy/paste at all

Dim rSrc As Range
Dim rDst As Range
Set rSrc = wb2.Sheets("YourSheet").Range("YourRange")
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
rDst = rSrc.Value

How do I adb pull ALL files of a folder present in SD Card

On Android 6 with ADB version 1.0.32, you have to put / behind the folder you want to copy. E.g adb pull "/sdcard/".

DLL load failed error when importing cv2

You can download the latest OpenCV 3.2.0 for Python 3.6 on Windows 32-bit or 64-bit machine, look for file starts withopencv_python-3.2.0-cp36-cp36m, from this unofficial site. Then type below command to install it:

  • pip install opencv_python-3.2.0-cp36-cp36m-win32.whl (32-bit version)
  • pip install opencv_python-3.2.0-cp36-cp36m-win_amd64.whl (64-bit version)

I think it would be easier.

Update on 2017-09-15:

OpenCV 3.3.0 wheel files are now available in the unofficial site and replaced OpenCV 3.2.0.

Update on 2018-02-15:

OpenCV 3.4.0 wheel files are now available in the unofficial site and replaced OpenCV 3.3.0.

Update on 2018-06-19:

OpenCV 3.4.1 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support, and replaced OpenCV 3.4.0.

Update on 2018-10-03:

OpenCV 3.4.3 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support, and replaced OpenCV 3.4.1.

Update on 2019-01-30:

OpenCV 4.0.1 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support.

Update on 2019-06-10:

OpenCV 3.4.6 and OpenCV 4.1.0 wheel files are now available in the unofficial site with CPython 3.5/3.6/3.7 support.

How to convert URL parameters to a JavaScript object?

_x000D_
_x000D_
console.log(decodeURI('abc=foo&def=%5Basf%5D&xyz=5')_x000D_
  .split('&')_x000D_
  .reduce((result, current) => {_x000D_
    const [key, value] = current.split('=');_x000D_
_x000D_
    result[key] = value;_x000D_
_x000D_
    return result_x000D_
  }, {}))
_x000D_
_x000D_
_x000D_

Java SecurityException: signer information does not match

In my case it was a package name conflict. Current project and signed referenced library had one package in common package.foo.utils. Just changed the current project error-prone package name to something else.

htaccess remove index.php from url

For more detail

create .htaccess file on project root directory and put below code for remove index.php

  RewriteEngine on
  RewriteCond $1 !^(index.php|resources|robots.txt)
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php/$1 [L,QSA]

List comprehension vs map

If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer map over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a map function to overload python's map. Then by passing the appropriate map function to the rest of your code, you may not have to modify your original serial code to have it run in parallel (etc).

How to create roles in ASP.NET Core and assign them to users?

I have created an action in the Accounts controller that calls a function to create the roles and assign the Admin role to the default user. (You should probably remove the default user in production):

    private async Task CreateRolesandUsers()
    {  
        bool x = await _roleManager.RoleExistsAsync("Admin");
        if (!x)
        {
            // first we create Admin rool    
            var role = new IdentityRole();
            role.Name = "Admin";
            await _roleManager.CreateAsync(role);

            //Here we create a Admin super user who will maintain the website                   

            var user = new ApplicationUser();
            user.UserName = "default";
            user.Email = "[email protected]";

            string userPWD = "somepassword";

            IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);

            //Add default User to Role Admin    
            if (chkUser.Succeeded)
            {
                var result1 = await _userManager.AddToRoleAsync(user, "Admin");
            }
        }

        // creating Creating Manager role     
        x = await _roleManager.RoleExistsAsync("Manager");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Manager";
            await _roleManager.CreateAsync(role);
        }

        // creating Creating Employee role     
        x = await _roleManager.RoleExistsAsync("Employee");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Employee";
            await _roleManager.CreateAsync(role);
        }
  }

After you could create a controller to manage roles for the users.

How to create a user in Django?

The correct way to create a user in Django is to use the create_user function. This will handle the hashing of the password, etc..

from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
                                 email='[email protected]',
                                 password='glass onion')

How to force a SQL Server 2008 database to go Offline

You need to use WITH ROLLBACK IMMEDIATE to boot other conections out with no regards to what or who is is already using it.

Or use WITH NO_WAIT to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details

How do I line up 3 divs on the same row?

Old topic but maybe someone will like it.

fiddle link http://jsfiddle.net/74ShU/

<div class="mainDIV">
    <div class="leftDIV"></div>
    <div class="middleDIV"></div>
    <div class="rightDIV"></div>
</div>

and css

.mainDIV{
    position:relative;
    background:yellow;
    width:100%;
    min-width:315px;
}
.leftDIV{
    position:absolute;
    top:0px;
    left:0px;
    height:50px;
    width:100px;
    background:red;
}
.middleDIV{
    height:50px;
    width:100px;
    background:blue;
    margin:0px auto;
}
.rightDIV{
    position:absolute;
    top:0px;
    right:0px;
    height:50px;
    width:100px;
    background:green;
}

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How to convert color code into media.brush?

Sorry to be so late to the party! I came across a similar issue, in WinRT. I'm not sure whether you're using WPF or WinRT, but they do differ in some ways (some better than others). Hopefully this will help people across the board, whichever situation they're in.

You could always use the code from the converter class I created to re-use and do in your C# code-behind, or wherever you're using it, to be honest:

I made it with the intention that a 6-digit (RGB), or an 8-digit (ARGB) Hex value could be used either way.

So I created a converter class:

public class StringToSolidColorBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var hexString = (value as string).Replace("#", "");

        if (string.IsNullOrWhiteSpace(hexString)) throw new FormatException();
        if (hexString.Length != 6 || hexString.Length != 8) throw new FormatException();

        try
        {
            var a = hexString.Length == 8 ? hexString.Substring(0, 2) : "255";
            var r = hexString.Length == 8 ? hexString.Substring(2, 2) : hexString.Substring(0, 2);
            var g = hexString.Length == 8 ? hexString.Substring(4, 2) : hexString.Substring(2, 2);
            var b = hexString.Length == 8 ? hexString.Substring(6, 2) : hexString.Substring(4, 2);

            return new SolidColorBrush(ColorHelper.FromArgb(
                byte.Parse(a, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(r, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(g, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(b, System.Globalization.NumberStyles.HexNumber)));
        }
        catch
        {
            throw new FormatException();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Added it into my App.xaml:

<ResourceDictionary>
    ...
    <converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />
    ...
</ResourceDictionary>

And used it in my View's Xaml:

<Grid>
    <Rectangle Fill="{Binding RectangleColour,
               Converter={StaticResource StringToSolidColorBrushConverter}}"
               Height="20" Width="20" />
</Grid>

Works a charm!

Side note... Unfortunately, WinRT hasn't got the System.Windows.Media.BrushConverter that H.B. suggested; so I needed another way, otherwise I would have made a VM property that returned a SolidColorBrush (or similar) from the RectangleColour string property.

Converting string to numeric

As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.

Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :

> x <- factor(sample(4:8,10,replace=T))
> x
 [1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
 [1] 6 4 8 6 7 6 8 5 8 4

To show it works.

The timings :

> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
   user  system elapsed 
   0.11    0.00    0.11 
> system.time(as.numeric(levels(x))[x])
   user  system elapsed 
      0       0       0 

It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.

How to select different app.config for several build configurations

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

Hope this helps.