Programs & Examples On #Tableview

A table view is a means for displaying and editing hierarchical lists of information. For example: UITableView in Cocoa-touch.

Changing background color of selected cell?

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    if selected {
        self.contentView.backgroundColor = .black
    } else {
        self.contentView.backgroundColor = .white
    }
}

How to get textLabel of selected row in swift?

Swift 4

To get the label of the selected row:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
    print(cell.textLabel?.text)
}

To get the label of the deselected row:

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
    print(cell.textLabel?.text)
}

JavaFX 2.1 TableView refresh items

There seem to be several separate issues around oldItems.equals(newItems)

The first part of RT-22463: tableView won't update even if calling items.clear()

// refresh table 
table.getItems().clear();
table.setItems(listEqualToOld);    

that's fixed. Clearing out the old items before setting a new list clears out all old state, thus refreshing the table. Any example where this doesn't work might be a regression.

What's still not working is re-setting items without clearing first

// refresh table
table.setItems(listEqualToOld); 

That's a problem if the table is showing properties that are not involved into an item's equal decision (see example in RT-22463 or Aubin's) and covered - hopefully - by RT-39094

UPDATE: RT-39094 the latter is fixed as well, for 8u40! Should bubble up into the ea in a couple of weeks, speculating on u12 or such.

The technical reason seems to be an equality check in cell's implementation: checking for changes of the item before actually calling updateItem(T, boolean) was introduced to fix performance problems. Reasonable, just to hard-code "change" == old.equals(new) poses problems in some contexts.

A work-around that's fine for me (no formal testing!) is a custom TableRow which jumps in if identity check is required:

/**
 * Extended TableRow that updates its item if equal but not same.
 * Needs custom skin to update cells on invalidation of the 
 * item property.<p>
 * 
 * Looks ugly, as we have to let super doing its job and then
 * re-check the state. No way to hook anywhere else into super 
 * because all is private. <p>
 * 
 * Super might support a configuration option to check against
 * identity vs. against equality.<p>
 * 
 * Note that this is _not_ formally tested! Any execution paths calling
 * <code>updateItem(int)</code> other than through 
 * <code>indexedCell.updateIndex(int)</code> are not handled.
 * 
 * @author Jeanette Winzenburg, Berlin
 */
public class IdentityCheckingTableRow<T>  extends TableRow<T> {

    @Override
    public void updateIndex(int i) {
        int oldIndex = getIndex();
        T oldItem = getItem();
        boolean wasEmpty = isEmpty();
        super.updateIndex(i);
        updateItemIfNeeded(oldIndex, oldItem, wasEmpty);

    }

    /**
     * Here we try to guess whether super updateIndex didn't update the item if
     * it is equal to the old.
     * 
     * Strictly speaking, an implementation detail.
     * 
     * @param oldIndex cell's index before update
     * @param oldItem cell's item before update
     * @param wasEmpty cell's empty before update
     */
    protected void updateItemIfNeeded(int oldIndex, T oldItem, boolean wasEmpty) {
        // weed out the obvious
        if (oldIndex != getIndex()) return;
        if (oldItem == null || getItem() == null) return;
        if (wasEmpty != isEmpty()) return;
        // here both old and new != null, check whether the item had changed
        if (oldItem != getItem()) return;
        // unchanged, check if it should have been changed
        T listItem = getTableView().getItems().get(getIndex());
        // update if not same
        if (oldItem != listItem) {
            // doesn't help much because itemProperty doesn't fire
            // so we need the help of the skin: it must listen
            // to invalidation and force an update if 
            // its super wouldn't get a changeEvent
            updateItem(listItem, isEmpty());
        }
    }


    @Override
    protected Skin<?> createDefaultSkin() {
        return new TableRowSkinX<>(this);
    }


    public static class TableRowSkinX<T> extends TableRowSkin<T> {

        private WeakReference<T> oldItemRef;
        private InvalidationListener itemInvalidationListener;
        private WeakInvalidationListener weakItemInvalidationListener;
        /**
         * @param tableRow
         */
        public TableRowSkinX(TableRow<T> tableRow) {
            super(tableRow);
            oldItemRef = new WeakReference<>(tableRow.getItem());
            itemInvalidationListener = o -> {
                T newItem = ((ObservableValue<T>) o).getValue();
                T oldItem = oldItemRef != null ? oldItemRef.get() : null;
                oldItemRef = new WeakReference<>(newItem);
                if (oldItem != null && newItem != null && oldItem.equals(newItem)) {
                    forceCellUpdate();
                }
            };
            weakItemInvalidationListener = new WeakInvalidationListener(itemInvalidationListener);
            tableRow.itemProperty().addListener(weakItemInvalidationListener);
        }

        /**
         * Try to force cell update for equal (but not same) items.
         * C&P'ed code from TableRowSkinBase.
         */
        private void forceCellUpdate() {
            updateCells = true;
            getSkinnable().requestLayout();

            // update the index of all children cells (RT-29849).
            // Note that we do this after the TableRow item has been updated,
            // rather than when the TableRow index has changed (as this will be
            // before the row has updated its item). This will result in the
            // issue highlighted in RT-33602, where the table cell had the correct
            // item whilst the row had the old item.
            final int newIndex = getSkinnable().getIndex();
            for (int i = 0, max = cells.size(); i < max; i++) {
                cells.get(i).updateIndex(newIndex);
            }
       }

    }

    @SuppressWarnings("unused")
    private static final Logger LOG = Logger
            .getLogger(IdentityCheckingListCell.class.getName());

}

 // usage
 table.setRowFactory(p -> new IdentityCheckingTableRow());

Note that TableCell has a similar hard-coded equality check, so if the custom row doesn't suffice it might be necessary to use a custom TableCell with a similar workaround (haven't run into an example where that's needed, though)

How to change the text on the action bar

getSupportActionBar().setTitle("title");

Add a month to a Date

It is ambiguous when you say "add a month to a date".

Do you mean

  1. add 30 days?
  2. increase the month part of the date by 1?

In both cases a whole package for a simple addition seems a bit exaggerated.

For the first point, of course, the simple + operator will do:

d=as.Date('2010-01-01') 
d + 30 
#[1] "2010-01-31"

As for the second I would just create a one line function as simple as that (and with a more general scope):

add.months= function(date,n) seq(date, by = paste (n, "months"), length = 2)[2]

You can use it with arbitrary months, including negative:

add.months(d, 3)
#[1] "2010-04-01"
add.months(d, -3)
#[1] "2009-10-01"

Of course, if you want to add only and often a single month:

add.month=function(date) add.months(date,1)
add.month(d)
#[1] "2010-02-01"

If you add one month to 31 of January, since 31th February is meaningless, the best to get the job done is to add the missing 3 days to the following month, March. So correctly:

add.month(as.Date("2010-01-31"))
#[1] "2010-03-03"

In case, for some very special reason, you need to put a ceiling to the last available day of the month, it's a bit longer:

add.months.ceil=function (date, n){

  #no ceiling
  nC=add.months(date, n)

  #ceiling
  day(date)=01
  C=add.months(date, n+1)-1

  #use ceiling in case of overlapping
  if(nC>C) return(C)
  return(nC)
}

As usual you could add a single month version:

add.month.ceil=function(date) add.months.ceil(date,1)    

So:

  d=as.Date('2010-01-31')
  add.month.ceil(d)
  #[1] "2010-02-28"
  d=as.Date('2010-01-21')
  add.month.ceil(d)
  #[1] "2010-02-21"

And with decrements:

  d=as.Date('2010-03-31')
  add.months.ceil(d, -1)
  #[1] "2010-02-28"
  d=as.Date('2010-03-21')
  add.months.ceil(d, -1)
  #[1] "2010-02-21"

Besides you didn't tell if you were interested to a scalar or vector solution. As for the latter:

add.months.v= function(date,n) as.Date(sapply(date, add.months, n), origin="1970-01-01")

Note: *apply family destroys the class data, that's why it has to be rebuilt. The vector version brings:

d=c(as.Date('2010/01/01'), as.Date('2010/01/31'))
add.months.v(d,1)
[1] "2010-02-01" "2010-03-03"

Hope you liked it))

Highlight all occurrence of a selected word?

My favorite for doing this is the mark.vim plugin. It allows to highlight several words in different colors simultaneously.

Example Screenshot

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

Thanks, all, for the help. Picking from here and there comes this solution. This compiles clean. Have not tested the code yet. Tomorrow... maybe...

const char * timeServer[] = { "pool.ntp.org" }; // 0 - Worldwide 
#define WHICH_NTP            0 // Which NTP server name to use.
...
sendNTPpacket(const_cast<char*>(timeServer[WHICH_NTP])); // send an NTP packet to a server
...
void sendNTPpacket(char* address) { code }

I know, there's only 1 item in the timeServer array. But there could be more. The rest were commented out for now to save memory.

Table with 100% width with equal size columns

ALL YOU HAVE TO DO:

HTML:

<table id="my-table"><tr>
<td> CELL 1 With a lot of text in it</td>
<td> CELL 2 </td>
<td> CELL 3 </td>
<td> CELL 4 With a lot of text in it </td>
<td> CELL 5 </td>
</tr></table>

CSS:

#my-table{width:100%;} /*or whatever width you want*/
#my-table td{width:2000px;} /*something big*/

if you have th you need to set it too like this:

#my-table th{width:2000px;}

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

Add rows to CSV File in powershell

I know this is an old thread but it was the first I found when searching. The += solution did not work for me. The code that I did get to work is as below.

#this bit creates the CSV if it does not already exist
$headers = "Name", "Primary Type"
$psObject = New-Object psobject
foreach($header in $headers)
{
 Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
}
$psObject | Export-Csv $csvfile -NoTypeInformation

#this bit appends a new row to the CSV file
$bName = "My Name"
$bPrimaryType = "My Primary Type"
    $hash = @{
             "Name" =  $bName
             "Primary Type" = $bPrimaryType
              }

$newRow = New-Object PsObject -Property $hash
Export-Csv $csvfile -inputobject $newrow -append -Force

I was able to use this as a function to loop through a series of arrays and enter the contents into the CSV file.

It works in powershell 3 and above.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Changing upload_max_filesize on PHP

I got this to work using a .user.ini file in the same directory as my index.php script that loads my app. Here are the contents:

upload_max_filesize = "20M"
post_max_size = "25M"

This is the recommended solution for Heroku.

python time + timedelta equivalent

The solution is in the link that you provided in your question:

datetime.combine(date.today(), time()) + timedelta(hours=1)

Full example:

from datetime import date, datetime, time, timedelta

dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()

Output:

00:25:00

Is it possible to start activity through adb shell?

You can also find the name of the current on screen activity using

adb shell dumpsys window windows | grep 'mCurrentFocus'

How to make the background DIV only transparent using CSS

Fiddle: http://jsfiddle.net/uenrX/1/

The opacity property of the outer DIV cannot be undone by the inner DIV. If you want to achieve transparency, use rgba or hsla:

Outer div:

background-color: rgba(255, 255, 255, 0.9); /* Color white with alpha 0.9*/

Inner div:

background-color: #FFF; /* Background white, to override the background propery*/

EDIT
Because you've added filter:alpha(opacity=90) to your question, I assume that you also want a working solution for (older versions of) IE. This should work (-ms- prefix for the newest versions of IE):

/*Padded for readability, you can write the following at one line:*/
filter: progid:DXImageTransform.Microsoft.Gradient(
    GradientType=1,
    startColorStr="#E6FFFFFF",
    endColorStr="#E6FFFFFF");

/*Similarly: */
filter: progid:DXImageTransform.Microsoft.Gradient(
    GradientType=1,
    startColorStr="#E6FFFFFF",
    endColorStr="#E6FFFFFF");

I've used the Gradient filter, starting with the same start- and end-color, so that the background doesn't show a gradient, but a flat colour. The colour format is in the ARGB hex format. I've written a JavaScript snippet to convert relative opacity values to absolute alpha-hex values:

var opacity = .9;
var A_ofARGB = Math.round(opacity * 255).toString(16);
if(A_ofARGB.length == 1) A_ofARGB = "0"+a_ofARGB;
else if(!A_ofARGB.length) A_ofARGB = "00";
alert(A_ofARGB);

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

Call a stored procedure with another in Oracle

Sure, you just call it from within the SP, there's no special syntax.

Ex:

   PROCEDURE some_sp
   AS
   BEGIN
      some_other_sp('parm1', 10, 20.42);
   END;

If the procedure is in a different schema than the one the executing procedure is in, you need to prefix it with schema name.

   PROCEDURE some_sp
   AS
   BEGIN
      other_schema.some_other_sp('parm1', 10, 20.42);
   END;

How to show code but hide output in RMarkdown?

The results = 'hide' option doesn't prevent other messages to be printed. To hide them, the following options are useful:

  • {r, error=FALSE}
  • {r, warning=FALSE}
  • {r, message=FALSE}

In every case, the corresponding warning, error or message will be printed to the console instead.

Add default value of datetime field in SQL Server to a timestamp

This also works:

CREATE TABLE Example(
...
created datetime default GETDATE()
);

Or:

ALTER TABLE EXAMPLE ADD created datetime default GETDATE();

What is the difference between a schema and a table and a database?

Schemas contains Databases.

Databases are part of a Schema.

So, schemas > databases.

Schemas contains views, stored procedure(s), database(s), trigger(s) etc.

Get current directory name (without full path) in a Bash script

You can use the basename utility which deletes any prefix ending in / and the suffix (if present in string) from string, and prints the result on the standard output.

$basename <path-of-directory>

How do I properly compare strings in C?

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char s1[50],s2[50];
        printf("Enter the character of strings: ");
        gets(s1);
        printf("\nEnter different character of string to repeat: \n");
        while(strcmp(s1,s2))
        {
            printf("%s\n",s1);
            gets(s2);
        }
        return 0;
    }

This is very simple solution in which you will get your output as you want.

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

Absolutely. You can use the LINQ Dynamic Query Library, found on Scott Guthrie's blog. There's also an updated version available on CodePlex.

It lets you create OrderBy clauses, Where clauses, and just about everything else by passing in string parameters. It works great for creating generic code for sorting/filtering grids, etc.

var result = data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo asc");

var query = DbContext.Data
    .Where(/* ... */)
    .Select(/* ... */)
    .OrderBy("Foo ascending");

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

Very good i used this on a silex project

$app->after(function (Request $request, Response $response) {
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set("Access-Control-Allow-Credentials", "true");
        $response->headers->set("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
        $response->headers->set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    });

Regex pattern for numeric values

"[1-9][0-9]*|0"

I'd just use "[0-9]+" to represent positive whole numbers.

Cannot read property 'addEventListener' of null

I've a collection of quotes along with names. I'm using update button to update the last quote associated with a specific name but on clicking update button it's not updating. I'm including code below for server.js file and external js file (main.js).

main.js (external js)

var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})var update = document.getElementById('update');
if (update){
update.addEventListener('click', function () {

  fetch('quotes', {
  method: 'put',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    'name': 'Muskan',
    'quote': 'I find your lack of faith disturbing.'
  })
})
.then(res =>{
    if(res.ok) return res.json()
})
.then(data =>{
    console.log(data);
    window.location.reload(true);
})
})
}

server.js file

app.put('/quotes', (req, res) => {
  db.collection('quotations').findOneAndUpdate({name: 'Vikas'},{
    $set:{
        name: req.body.name,
        quote: req.body.quote
    }
  },{
    sort: {_id: -1},
    upsert: true
  },(err, result) =>{
    if (err) return res.send(err);
    res.send(result);
  })

})

Select query to remove non-numeric characters

This worked for me:

  1. I removed the single quotes.

  2. I then used a replace "," with ".".

Surely this will help someone:

" & txtFinalscore.Text.Replace(",", ".") & "

The ResourceConfig instance does not contain any root resource classes

Another thing to check is a combination of previous entries

You can have in your web.xml file this:

<init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.acme.rest</param-value>
</init-param>

and you can have

<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>resteasy.scan.providers</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>resteasy.scan.resources</param-name>
    <param-value>false</param-value>
</context-param>

but you cannot have both or you get this sort of error. The fix in this case would be to comment out one or the other (probably the first code snippet would be commented out)

WPF MVVM: How to close a window

There is a useful behavior for this task which doesn't break MVVM, a Behavior, introduced with Expression Blend 3, to allow the View to hook into commands defined completely within the ViewModel.

This behavior demonstrates a simple technique for allowing the ViewModel to manage the closing events of the View in a Model-View-ViewModel application.

This allows you to hook up a behavior in your View (UserControl) which will provide control over the control's Window, allowing the ViewModel to control whether the window can be closed via standard ICommands.

Using Behaviors to Allow the ViewModel to Manage View Lifetime in M-V-VM

http://gallery.expression.microsoft.com/WindowCloseBehavior/

Above link has been archived to http://code.msdn.microsoft.com/Window-Close-Attached-fef26a66#content

What is difference between @RequestBody and @RequestParam?

It is very simple just look at their names @RequestParam it consist of two parts one is "Request" which means it is going to deal with request and other part is "Param" which itself makes sense it is going to map only the parameters of requests to java objects. Same is the case with @RequestBody it is going to deal with the data that has been arrived with request like if client has send json object or xml with request at that time @requestbody must be used.

How to subtract/add days from/to a date?

There is of course a lubridate solution for this:

library(lubridate)
date <- "2009-10-01"

ymd(date) - 5
# [1] "2009-09-26"

is the same as

ymd(date) - days(5)
# [1] "2009-09-26"

Other time formats could be:

ymd(date) - months(5)
# [1] "2009-05-01"

ymd(date) - years(5)
# [1] "2004-10-01"

ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"

Making a mocked method return an argument that was passed to it

You can create an Answer in Mockito. Let's assume, we have an interface named Application with a method myFunction.

public interface Application {
  public String myFunction(String abc);
}

Here is the test method with a Mockito answer:

public void testMyFunction() throws Exception {
  Application mock = mock(Application.class);
  when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
    @Override
    public String answer(InvocationOnMock invocation) throws Throwable {
      Object[] args = invocation.getArguments();
      return (String) args[0];
    }
  });

  assertEquals("someString",mock.myFunction("someString"));
  assertEquals("anotherString",mock.myFunction("anotherString"));
}

Since Mockito 1.9.5 and Java 8, you can also use a lambda expression:

when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);

Force "portrait" orientation mode

Note that

android:screenOrientation="portrait"     
android:configChanges="orientation|keyboardHidden"

is added in the manifest file - where the activity is defined.

How to trigger event in JavaScript?

function fireMouseEvent(obj, evtName) {
    if (obj.dispatchEvent) {
        //var event = new Event(evtName);
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent(evtName, true, true, window,
                0, 0, 0, 0, 0, false, false, false, false, 0, null);
        obj.dispatchEvent(event);
    } else if (obj.fireEvent) {
        event = document.createEventObject();
        event.button = 1;
        obj.fireEvent("on" + evtName, event);
        obj.fireEvent(evtName);
    } else {
        obj[evtName]();
    }
}

var obj = document.getElementById("......");
fireMouseEvent(obj, "click");

Easy way to pull latest of all git submodules

All you need to do now is a simple git checkout

Just make sure to enable it via this global config: git config --global submodule.recurse true

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

It is because the WEB-INF folder does not exist at the location in the sub directory in the error. You either compile the application to use the WEB-INF folder under public_html OR copy the WEB-INF folder in sub folder as in the error above.

Convert hexadecimal string (hex) to a binary string

public static byte[] hexToBytes(String string) {
 int length = string.length();
 byte[] data = new byte[length / 2];
 for (int i = 0; i < length; i += 2) {
  data[i / 2] = (byte)((Character.digit(string.charAt(i), 16) << 4) + Character.digit(string.charAt(i + 1), 16));
 }
 return data;
}

Selenium WebDriver can't find element by link text

A CSS selector approach could definitely work here. Try:

driver.findElement(By.CssSelector("a.item")).Click();

This will not work if there are other anchors before this one of the class item. You can better specify the exact element if you do something like "#my_table > a.item" where my_table is the id of a table that the anchor is a child of.

How to select different app.config for several build configurations

SlowCheetah and FastKoala from the VisualStudio Gallery seem to be very good tools that help out with this problem.

However, if you want to avoid addins or use the principles they implement more extensively throughout your build/integration processes then adding this to your msbuild *proj files is a shorthand fix.

Note: this is more or less a rework of the No. 2 of @oleksii's answer.

This works for .exe and .dll projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
  </Target>

This works for web projects:

  <Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
  </Target>

Note that this step happens even before the build proper begins. The transformation of the config file happens in the project folder. So that the transformed web.config is available when you are debugging (a drawback of SlowCheetah).

Do remember that if you create the App_Config folder (or whatever you choose to call it), the various intermediate config files should have a Build Action = None, and Copy to Output Directory = Do not copy.

This combines both options into one block. The appropriate one is executed based on conditions. The TransformXml task is defined first though:

<Project>
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="TransformOnBuild" BeforeTargets="PrepareForBuild">
    <TransformXml Condition="Exists('App_Config\app.Base.config')" Source="App_Config\app.Base.config" Transform="App_Config\app.$(Configuration).config" Destination="app.config" />
    <TransformXml Condition="Exists('App_Config\Web.Base.config')" Source="App_Config\Web.Base.config" Transform="App_Config\Web.$(Configuration).config" Destination="Web.config" />
</Target>

Foreign Key to non-primary key

Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.

The problem is, that if you have that problem, the database-schema is denormalized.

You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.

So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.

So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.

And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...

Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:

IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO




CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
     @in_RM_ApertureID uniqueidentifier 
    ,@in_DatumVon AS datetime 
    ,@in_DatumBis AS datetime 
    ,@in_Status AS integer 
) 
    RETURNS bit 
AS 
BEGIN   
    DECLARE @bNoCheckForThisCustomer AS bit 
    DECLARE @bIsInvalidValue AS bit 
    SET @bNoCheckForThisCustomer = 'false' 
    SET @bIsInvalidValue = 'false' 

    IF @in_Status = 99 
        RETURN 'false' 


    IF @in_DatumVon > @in_DatumBis 
    BEGIN 
        RETURN 'true' 
    END 


    IF @bNoCheckForThisCustomer = 'true'
        RETURN @bIsInvalidValue 


    IF NOT EXISTS
    ( 
        SELECT 
             T_Raum.RM_UID 
            ,T_Raum.RM_Status 
            ,T_Raum.RM_DatumVon 
            ,T_Raum.RM_DatumBis 
            ,T_Raum.RM_ApertureID 
        FROM T_Raum 
        WHERE (1=1) 
        AND T_Raum.RM_ApertureID = @in_RM_ApertureID 
        AND @in_DatumVon >= T_Raum.RM_DatumVon 
        AND @in_DatumBis <= T_Raum.RM_DatumBis 
        AND T_Raum.RM_Status <> 99  
    ) 
        SET @bIsInvalidValue = 'true' -- IF ! 

    RETURN @bIsInvalidValue 
END 



GO



IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]  
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
CHECK 
( 
    NOT 
    ( 
        dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1 
    ) 
) 
GO


IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]')) 
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
GO

How to do a batch insert in MySQL

Insert into table(col1,col2) select col1,col2 from table_2;

Please refer to MySQL documentation on INSERT Statement

Entity Framework Queryable async

The problem seems to be that you have misunderstood how async/await work with Entity Framework.

About Entity Framework

So, let's look at this code:

public IQueryable<URL> GetAllUrls()
{
    return context.Urls.AsQueryable();
}

and example of it usage:

repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()

What happens there?

  1. We are getting IQueryable object (not accessing database yet) using repo.GetAllUrls()
  2. We create a new IQueryable object with specified condition using .Where(u => <condition>
  3. We create a new IQueryable object with specified paging limit using .Take(10)
  4. We retrieve results from database using .ToList(). Our IQueryable object is compiled to sql (like select top 10 * from Urls where <condition>). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)

Okay, let's look at first code:

public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
    var urls = await context.Urls.ToListAsync();
    return urls.AsQueryable();
}

With the same example of usage we got:

  1. We are loading in memory all billion urls stored in your database using await context.Urls.ToListAsync();.
  2. We got memory overflow. Right way to kill your server

About async/await

Why async/await is preferred to use? Let's look at this code:

var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));

What happens here?

  1. Starting on line 1 var stuff1 = ...
  2. We send request to sql server that we want to get some stuff1 for userId
  3. We wait (current thread is blocked)
  4. We wait (current thread is blocked)
  5. .....
  6. Sql server send to us response
  7. We move to line 2 var stuff2 = ...
  8. We send request to sql server that we want to get some stuff2 for userId
  9. We wait (current thread is blocked)
  10. And again
  11. .....
  12. Sql server send to us response
  13. We render view

So let's look to an async version of it:

var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));

What happens here?

  1. We send request to sql server to get stuff1 (line 1)
  2. We send request to sql server to get stuff2 (line 2)
  3. We wait for responses from sql server, but current thread isn't blocked, he can handle queries from another users
  4. We render view

Right way to do it

So good code here:

using System.Data.Entity;

public IQueryable<URL> GetAllUrls()
{
   return context.Urls.AsQueryable();
}

public async Task<List<URL>> GetAllUrlsByUser(int userId) {
   return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}

Note, than you must add using System.Data.Entity in order to use method ToListAsync() for IQueryable.

Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable. You can just use await context.Urls.ToListAsync() and work with materialized List<Url>.

Why doesn't RecyclerView have onItemClickListener()?

After reading @MLProgrammer-CiM's answer, here is my code:

class NormalViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    @Bind(R.id.card_item_normal)
    CardView cardView;

    public NormalViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        cardView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v instanceof CardView) {
            // use getAdapterPosition() instead of getLayoutPosition()
            int itemPosition = getAdapterPosition();
            removeItem(itemPosition);
        }
    }
}

Attempt to set a non-property-list object as an NSUserDefaults

I ran into this and eventually figured out it was because I was trying to use NSNumber as dictionary keys, and property lists only allow strings as keys. The documentation for setObject:forKey: doesn't mention this limitation, but the About Property Lists page that it links to does:

By convention, each Cocoa and Core Foundation object listed in Table 2-1 is called a property-list object. Conceptually, you can think of “property list” as being an abstract superclass of all these classes. If you receive a property list object from some method or function, you know that it must be an instance of one of these types, but a priori you may not know which type. If a property-list object is a container (that is, an array or dictionary), all objects contained within it must also be property-list objects. If an array or dictionary contains objects that are not property-list objects, then you cannot save and restore the hierarchy of data using the various property-list methods and functions. And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

(Emphasis mine)

SQL Server : trigger how to read value for Insert, Update, Delete

There is no updated dynamic table. There is just inserted and deleted. On an UPDATE command, the old data is stored in the deleted dynamic table, and the new values are stored in the inserted dynamic table.

Think of an UPDATE as a DELETE/INSERT combination.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

I had to turn PAE/NX off and then back to on...voila !!

Any way of using frames in HTML5?

Maybe some AJAX page content injection could be used as an alternative, though I still can't get around why your teacher would refuse to rid the website of frames.

Additionally, is there any specific reason you personally want to us HTML5?

But if not, I believe <iframe>s are still around.

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

Please add below jQuery Migrate Plugin

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.4.1.min.js"></script>

Capturing multiple line output into a Bash variable

Actually, RESULT contains what you want — to demonstrate:

echo "$RESULT"

What you show is what you get from:

echo $RESULT

As noted in the comments, the difference is that (1) the double-quoted version of the variable (echo "$RESULT") preserves internal spacing of the value exactly as it is represented in the variable — newlines, tabs, multiple blanks and all — whereas (2) the unquoted version (echo $RESULT) replaces each sequence of one or more blanks, tabs and newlines with a single space. Thus (1) preserves the shape of the input variable, whereas (2) creates a potentially very long single line of output with 'words' separated by single spaces (where a 'word' is a sequence of non-whitespace characters; there needn't be any alphanumerics in any of the words).

Where is svcutil.exe in Windows 7?

To find any file location

  1. In windows start menu Search box
  2. type in svcutil.exe
  3. Wait for results to populate
  4. Right click on svcutil.exe and Select 'Open file location'
  5. Copy Windows explorer path

Why doesn't Java allow overriding of static methods?

In Java (and many OOP languages, but I cannot speak for all; and some do not have static at all) all methods have a fixed signature - the parameters and types. In a virtual method, the first parameter is implied: a reference to the object itself and when called from within the object, the compiler automatically adds this.

There is no difference for static methods - they still have a fixed signature. However, by declaring the method static you have explicitly stated that the compiler must not include the implied object parameter at the beginning of that signature. Therefore, any other code that calls this must must not attempt to put a reference to an object on the stack. If it did do that, then the method execution would not work since the parameters would be in the wrong place - shifted by one - on the stack.

Because of this difference between the two; virtual methods always have a reference to the context object (i.e. this) so then it is possible to reference anything within the heap that belong to that instance of the object. But with static methods, since there is no reference passed, that method cannot access any object variables and methods since the context is not known.

If you wish that Java would change the definition so that a object context is passed in for every method, static or virtual, then you would in essence have only virtual methods.

As someone asked in a comment to the op - what is your reason and purpose for wanting this feature?

I do not know Ruby much, as this was mentioned by the OP, I did some research. I see that in Ruby classes are really a special kind of object and one can create (even dynamically) new methods. Classes are full class objects in Ruby, they are not in Java. This is just something you will have to accept when working with Java (or C#). These are not dynamic languages, though C# is adding some forms of dynamic. In reality, Ruby does not have "static" methods as far as I could find - in that case these are methods on the singleton class object. You can then override this singleton with a new class and the methods in the previous class object will call those defined in the new class (correct?). So if you called a method in the context of the original class it still would only execute the original statics, but calling a method in the derived class, would call methods either from the parent or sub-class. Interesting and I can see some value in that. It takes a different thought pattern.

Since you are working in Java, you will need to adjust to that way of doing things. Why they did this? Well, probably to improve performance at the time based on the technology and understanding that was available. Computer languages are constantly evolving. Go back far enough and there is no such thing as OOP. In the future, there will be other new ideas.

EDIT: One other comment. Now that I see the differences and as I Java/C# developer myself, I can understand why the answers you get from Java developers may be confusing if you are coming from a language like Ruby. Java static methods are not the same as Ruby class methods. Java developers will have a hard time understanding this, as will conversely those who work mostly with a language like Ruby/Smalltalk. I can see how this would also be greatly confusing by the fact that Java also uses "class method" as another way to talk about static methods but this same term is used differently by Ruby. Java does not have Ruby style class methods (sorry); Ruby does not have Java style static methods which are really just old procedural style functions, as found in C.

By the way - thanks for the question! I learned something new for me today about class methods (Ruby style).

Font.createFont(..) set color and size (java.awt.Font)

To set the color of a font, you must first initialize the color by doing this:

Color maroon = new Color (128, 0, 0);

Once you've done that, you then put:

Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string

Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.

PNG transparency issue in IE8

Dan Tello fix worked well for me.

One additional issue I found with IE8 was that if the PNG was held in a DIV with smaller CSS width or height dimensions than the PNG then the black edge prob was re-triggered.

Correcting the width and height CSS or removing them altogether fixed.

HttpServletRequest - how to obtain the referring URL?

Actually it's: request.getHeader("Referer"), or even better, and to be 100% sure, request.getHeader(HttpHeaders.REFERER), where HttpHeaders is com.google.common.net.HttpHeaders

What does ||= (or-equals) mean in Ruby?

x ||= y

is

x || x = y

"if x is false or undefined, then x point to y"

How to chain scope queries with OR instead of AND?

the squeel gem provides an incredibly easy way to accomplish this (prior to this I used something like @coloradoblue's method):

names = ["Kroger", "Walmart", "Target", "Aldi"]
matching_stores = Grocery.where{name.like_any(names)}

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

Handling MySQL datetimes and timestamps in Java

The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp. A few resources include:

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion

How to store Java Date to Mysql datetime...?

http://www.velocityreviews.com/forums/t599436-the-best-practice-to-deal-with-datetime-in-mysql-using-jdbc.html

EDIT:

As others have indicated, the suggestion of using strings may lead to issues.

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

When a static constructor throws an exception, it is wrapped inside a TypeInitializationException. You need to check the exception object's InnerException property to see the actual exception.

In a staging / production environment (where you don't have Visual Studio installed), you'll need to either:

  1. Trace/Log the exception and its InnerException (recursively): Add an event handler to the AppDomain.UnhandledException event, and put your logging/tracing code there. Use System.Diagnostics.Debug.WriteLine for tracing, or a logger (log4net, ETW). DbgView (a Sysinternals tool) can be used to view the Debug.WriteLine trace.
  2. Use a production debugger (such as WinDbg or NTSD) to diagnose the exception.
  3. Use Visual Studio's Remote Debugging to diagnose the exception (enabling you to debug the code on the target computer from your own development computer).

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

orderBy multiple fields in Angular

Make sure that the sorting is not to complicated for the end user. I always thought sorting on group and sub group is a little bit complicated to understand. If its a technical end user it might be OK.

Android ImageView setImageResource in code

you use that code

ImageView[] ivCard = new ImageView[1];

@override    
protected void onCreate(Bundle savedInstanceState)  

ivCard[0]=(ImageView)findViewById(R.id.imageView1);

Android replace the current fragment with another fragment

it's very simple how to replace with Fragment.

DataFromDb changeActivity = new DataFromDb();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.changeFrg, changeActivity);
    transaction.commit();

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

How do you run a SQL Server query from PowerShell?

There isn't a built-in "PowerShell" way of running a SQL query. If you have the SQL Server tools installed, you'll get an Invoke-SqlCmd cmdlet.

Because PowerShell is built on .NET, you can use the ADO.NET API to run your queries.

Linux: where are environment variables stored?

The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in

/proc/pid/environ

This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do

cat /proc/3940/environ | tr '\0' '\n'

Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.

Calculating Pearson correlation and significance in Python

If you don't feel like installing scipy, I've used this quick hack, slightly modified from Programming Collective Intelligence:

def pearsonr(x, y):
  # Assume len(x) == len(y)
  n = len(x)
  sum_x = float(sum(x))
  sum_y = float(sum(y))
  sum_x_sq = sum(xi*xi for xi in x)
  sum_y_sq = sum(yi*yi for yi in y)
  psum = sum(xi*yi for xi, yi in zip(x, y))
  num = psum - (sum_x * sum_y/n)
  den = pow((sum_x_sq - pow(sum_x, 2) / n) * (sum_y_sq - pow(sum_y, 2) / n), 0.5)
  if den == 0: return 0
  return num / den

Why is my toFixed() function not working?

Example simple (worked):

var a=Number.parseFloat($("#budget_project").val()); // from input field
var b=Number.parseFloat(html); // from ajax
var c=a-b;
$("#result").html(c.toFixed(2)); // put to id='result' (div or others)

Pandas DataFrame: replace all values in a column, based on condition

for single condition, ie. ( 'employrate'] > 70 )

       country        employrate alcconsumption
0  Afghanistan  55.7000007629394            .03
1      Albania  51.4000015258789           7.29
2      Algeria              50.5            .69
3      Andorra                            10.17
4       Angola  75.6999969482422           5.57

use this:

df.loc[df['employrate'] > 70, 'employrate'] = 7

       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   51.400002           7.29
2      Algeria   50.500000            .69
3      Andorra         nan          10.17
4       Angola    7.000000           5.57

therefore syntax here is:

df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]

For multiple conditions ie. (df['employrate'] <=55) & (df['employrate'] > 50)

use this:

df['employrate'] = np.where(
   (df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
   )

out[108]:
       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   11.000000           7.29
2      Algeria   11.000000            .69
3      Andorra         nan          10.17
4       Angola   75.699997           5.57

therefore syntax here is:

 df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])

Can a website detect when you are using Selenium with chromedriver?

Replacing cdc_ string

You can use vim or perl to replace the cdc_ string in chromedriver. See answer by @Erti-Chris Eelmaa to learn more about that string and how it's a detection point.

Using vim or perl prevents you from having to recompile source code or use a hex-editor.

Make sure to make a copy of the original chromedriver before attempting to edit it.

Our goal is to alter the cdc_ string, which looks something like $cdc_lasutopfhvcZLmcfl.

The methods below were tested on chromedriver version 2.41.578706.


Using Vim

vim /path/to/chromedriver

After running the line above, you'll probably see a bunch of gibberish. Do the following:

  1. Replace all instances of cdc_ with dog_ by typing :%s/cdc_/dog_/g.
    • dog_ is just an example. You can choose anything as long as it has the same amount of characters as the search string (e.g., cdc_), otherwise the chromedriver will fail.
  2. To save the changes and quit, type :wq! and press return.
    • If you need to quit without saving changes, type :q! and press return.

Using Perl

The line below replaces all cdc_ occurrences with dog_. Credit to Vic Seedoubleyew:

perl -pi -e 's/cdc_/dog_/g' /path/to/chromedriver

Make sure that the replacement string (e.g., dog_) has the same number of characters as the search string (e.g., cdc_), otherwise the chromedriver will fail.


Wrapping Up

To verify that all occurrences of cdc_ were replaced:

grep "cdc_" /path/to/chromedriver

If no output was returned, the replacement was successful.

Go to the altered chromedriver and double click on it. A terminal window should open up. If you don't see killed in the output, you've successfully altered the driver.

Make sure that the name of the altered chromedriver binary is chromedriver, and that the original binary is either moved from its original location or renamed.


My Experience With This Method

I was previously being detected on a website while trying to log in, but after replacing cdc_ with an equal sized string, I was able to log in. Like others have said though, if you've already been detected, you might get blocked for a plethora of other reasons even after using this method. So you may have to try accessing the site that was detecting you using a VPN, different network, etc.

"Could not load type [Namespace].Global" causing me grief

Just wanted to add my two cents. I was receiving the same error, and I tried all the suggestions to no avail. My situation is probably different?

Turns out, an auto-generated "AssemblyInfo.cs" file had some extraneous spaces, which was preventing me from launching the web app (via debug). Here's what the file looked like:

[assembly: AssemblyTitle("WebApplication2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("

            ")]
[assembly: AssemblyProduct("WebApplication2")]
[assembly: AssemblyCopyright("Copyright © 

             2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

After killing the spaces in the AssemblyCompany and AssemblyCopyright, I was finally able to build and launch the project.

Observed in the following environment: --Visual Studio 2017 Community version 15.3.0 --Win 7 x64 Enterprise --New Project > Visual C# > Web > ASP.NET Web Application > Web Forms

How to display both icon and title of action inside ActionBar?

Some of you guys have great answers, but I found some additional thing. If you want create a MenuItem with some SubMenu programmatically:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenu = menu.addSubMenu(0, Menu.NONE, 0, "Menu title");
        subMenu.getItem().setIcon(R.drawable.ic_action_child);
        subMenu.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        subMenu.add(0, Menu.NONE, 0, "Subitem 1");
        subMenu.add(0, Menu.NONE, 1, "Subitem 2");
        subMenu.add(0, Menu.NONE, 2, "Subitem 3");

        return true;
    }

How to save a git commit message from windows cmd?

If you enter git commit but omit to enter a comment using the –m parameter, then Git will open up the default editor for you to edit your check-in note. By default that is Vim. Now you can do two things:

Alternative 1 – Exit Vim without entering any comment and repeat

A blank or unsaved comment will be counted as an aborted attempt to commit your changes and you can exit Vim by following these steps:

  1. Press Esc to make sure you are not in edit mode (you can press Esc several times if you are uncertain)

  2. Type :q! enter
    (that is, colon, letter q, exclamation mark, enter), this tells Vim to discard any changes and exit)
    Git will then respond:

    Aborting commit due to empty commit message

    and you are once again free to commit using:

    git commit –m "your comment here"
    

Alternative 2 – Use Vim to write a comment

Follow the following steps to use Vim for writing your comments

  1. Press i to enter Edit Mode (or Insert Mode).
    That will leave you with a blinking cursor on the first line. Add your comment. Press Esc to make sure you are not in edit mode (you can press Esc several time if you are uncertain)
  2. Type :wq enter
    (that is colon, letter w, letter q, enter), this will tell Vim to save changes and exit)

Response from https://blogs.msdn.microsoft.com/kristol/2013/07/02/the-git-command-line-101-for-windows-users/

T-SQL: Looping through an array of known values

What I do in this scenario is create a table variable to hold the Ids.

  Declare @Ids Table (id integer primary Key not null)
  Insert @Ids(id) values (4),(7),(12),(22),(19)

-- (or call another table valued function to generate this table)

Then loop based on the rows in this table

  Declare @Id Integer
  While exists (Select * From @Ids)
    Begin
      Select @Id = Min(id) from @Ids
      exec p_MyInnerProcedure @Id 
      Delete from @Ids Where id = @Id
    End

or...

  Declare @Id Integer = 0 -- assuming all Ids are > 0
  While exists (Select * From @Ids
                where id > @Id)
    Begin
      Select @Id = Min(id) 
      from @Ids Where id > @Id
      exec p_MyInnerProcedure @Id 
    End

Either of above approaches is much faster than a cursor (declared against regular User Table(s)). Table-valued variables have a bad rep because when used improperly, (for very wide tables with large number of rows) they are not performant. But if you are using them only to hold a key value or a 4 byte integer, with a index (as in this case) they are extremely fast.

NumPy array initialization (fill with identical values)

You can use numpy.tile, e.g. :

v = 7
rows = 3
cols = 5
a = numpy.tile(v, (rows,cols))
a
Out[1]: 
array([[7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7],
       [7, 7, 7, 7, 7]])

Although tile is meant to 'tile' an array (instead of a scalar, as in this case), it will do the job, creating pre-filled arrays of any size and dimension.

How to update a plot in matplotlib?

You can also do like the following: This will draw a 10x1 random matrix data on the plot for 50 cycles of the for loop.

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()

Jenkins pipeline how to change to another folder

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 

Appending output of a Batch file To log file

This is not an answer to your original question: "Appending output of a Batch file To log file?"

For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"

(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")

Timeout:

Example (1 second):

TIMEOUT /T 1000 /NOBREAK

Sleep:

Example (1 second):

sleep -m 1000

Alternative methods:

Here's an answer to your 2nd followup question: "Along with the Timestamp?"

Create a date and time stamp in your batch files

Example:

echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log

How do I replicate a \t tab space in HTML?

&nbsp;&nbsp;&nbsp;&nbsp; would be a work around if you're only after the spacing.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You can use it without casting such as:

select sum(`stuff`) as mySum from test;

Or cast it to decimal:

select sum(cast(`stuff` as decimal(4,2))) as mySum from test;

SQLFiddle

EDIT

For SQL Server, you can use:

select sum(cast(stuff as decimal(5,2))) as mySum from test;

SQLFiddle

How can I create a self-signed cert for localhost?

Since this question is tagged with IIS and I can't find a good answer on how to get a trusted certificate I will give my 2 cents about it:

First use the command from @AuriRahimzadeh in PowerShell as administrator:

New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\LocalMachine\My"

This is good but the certificate is not trusted and will result in the following error. It is because it is not installed in Trusted Root Certification Authorities.

enter image description here

Solve this by starting mmc.exe.

Then go to:

File -> Add or Remove Snap-ins -> Certificates -> Add -> Computer account -> Local computer. Click Finish.

Expand the Personal folder and you will see your localhost certificate:

enter image description here

Copy the certificate into Trusted Root Certification Authorities - Certificates folder.

The final step is to open Internet Information Services (IIS) Manager or simply inetmgr.exe. From there go to your site, select Bindings... and Add... or Edit.... Set https and select your certificate from the drop down.

enter image description here

Your certificate is now trusted:

enter image description here

404 Not Found The requested URL was not found on this server

In Ubuntu I did not found httpd.conf, It may not exit longer now. Edit in apache2.conf file working for me.

cd /etc/apache2
sudo gedit apache2.conf

Here in apache2.conf change

<Directory /var/www/>
     Options Indexes FollowSymLinks
     AllowOverride None
     Require all granted
</Directory>

to

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>  

How to list the files in current directory?

Had a quick snoop around for this one, but this looks like it should work. I haven't tested it yet though.

    File f = new File("."); // current directory

    File[] files = f.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            System.out.print("directory:");
        } else {
            System.out.print("     file:");
        }
        System.out.println(file.getCanonicalPath());
    }

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

How to merge specific files from Git branches

Although not a merge per se, sometimes the entire contents of another file on another branch are needed. Jason Rudolph's blog post provides a simple way to copy files from one branch to another. Apply the technique as follows:

$ git checkout branch1 # ensure in branch1 is checked out and active
$ git checkout branch2 file.py

Now file.py is now in branch1.

How to get Top 5 records in SqLite?

select * from [Table_Name] limit 5

Android Studio how to run gradle sync manually?

I think ./gradlew tasks is same with Android studio sync. Why? I will explain it.

I meet a problem when I test jacoco coverage report. When I run ./gradlew clean :Test:testDebugUnitTest in command line directly , error appear.

Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.2.jar_5bdiis3s7lm1rcnv0gawjjfxc/jacocoagent.jar

However, if I click android studio sync firstly , it runs OK. Because the build/../jacocoagent.jar appear naturally. I dont know why, maybe there is bug in jacoco plugin. Unit I find running .gradlew tasks makes the jar appear as well. So I can get the same result in gralde script.

Besides, gradle --recompile-scripts does not work for the problem.

How to initialise memory with new operator in C++?

Yes there is:

std::vector<int> vec(SIZE, 0);

Use a vector instead of a dynamically allocated array. Benefits include not having to bother with explicitely deleting the array (it is deleted when the vector goes out of scope) and also that the memory is automatically deleted even if there is an exception thrown.

Edit: To avoid further drive-by downvotes from people that do not bother to read the comments below, I should make it more clear that this answer does not say that vector is always the right answer. But it sure is a more C++ way than "manually" making sure to delete an array.

Now with C++11, there is also std::array that models a constant size array (vs vector that is able to grow). There is also std::unique_ptr that manages a dynamically allocated array (that can be combined with initialization as answered in other answers to this question). Any of those are a more C++ way than manually handling the pointer to the array, IMHO.

PostgreSQL: Which version of PostgreSQL am I running?

I believe this is what you are looking for,

Server version:

pg_config --version

Client version:

psql --version

How to find the Target *.exe file of *.appref-ms

The appref-ms file does not point to the exe. When you hit that shortcut, it invokes the deployment manifest at the deployment provider url and checks for updates. It checks the application manifest (yourapp.exe.manifest) to see what files to download, and this file contains the definition of the entry point (i.e. the exe).

How to connect to a MS Access file (mdb) using C#?

The simplest way to connect is through an OdbcConnection using code like this

using System.Data.Odbc;

using(OdbcConnection myConnection = new OdbcConnection())
{
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    //execute queries, etc

}

where myConnectionString is something like this

myConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};" + 
"Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;

See ConnectionStrings

In alternative you could create a DSN and then use that DSN in your connection string

  • Open the Control Panel - Administrative Tools - ODBC Data Source Manager
  • Go to the System DSN Page and ADD a new DSN
  • Choose the Microsoft Access Driver (*.mdb) and press END
  • Set the Name of the DSN (choose MyDSN for this example)
  • Select the Database to be used
  • Try the Compact or Recover commands to see if the connection works

now your connectionString could be written in this way

myConnectionString = "DSN=myDSN;"

Define an <img>'s src attribute in CSS

#divID {
    background-image: url("http://imageurlhere.com");
    background-repeat: no-repeat;
    width: auto; /*or your image's width*/
    height: auto; /*or your image's height*/
    margin: 0;
    padding: 0;
}

How to change legend title in ggplot

There's another very simple answer which can work for some simple graphs.

Just add a call to guide_legend() into your graph.

ggplot(...) + ... + guide_legend(title="my awesome title")

As shown in the very nice ggplot docs.

If that doesn't work, you can more precisely set your guide parameters with a call to guides:

ggplot(...) + ... + guides(fill=guide_legend("my awesome title"))

You can also vary the shape/color/size by specifying these parameters for your call to guides as well.

AsyncTask Android example

ASync Task;

public class MainActivity extends AppCompatActivity {

 private String ApiUrl="your_api";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     MyTask myTask=new MyTask();
     try {
         String result=myTask.execute(ApiUrl).get();
         Toast.makeText(getApplicationContext(),result,Toast.LENGTH_SHORT).show();
     } catch (ExecutionException e) {
         e.printStackTrace();
     } catch (InterruptedException e) {
        e.printStackTrace();
     }

  }


   public class MyTask extends AsyncTask<String,Void,String>{


    @Override
    protected String doInBackground(String... strings) {
        String result="";
        HttpURLConnection httpURLConnection=null;
        URL url;

        try {
            url=new URL(strings[0]);
            httpURLConnection=(HttpURLConnection) url.openConnection();
            InputStream inputStream=httpURLConnection.getInputStream();
            InputStreamReader reader=new InputStreamReader(inputStream);
            result=getData(reader);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public String getData(InputStreamReader reader) throws IOException{
        String result="";
        int data=reader.read();
        while (data!=-1){
            char now=(char) data;
            result+=data;
            data=reader.read();
        }
        return result;
    }
  }
}

MongoDB: How to query for records where field is null or not set?

If you want to ONLY count the documents with sent_at defined with a value of null (don't count the documents with sent_at not set):

db.emails.count({sent_at: { $type: 10 }})

How to execute AngularJS controller function on page load?

call initial methods inside self initialize function.

(function initController() {

    // do your initialize here

})();

how to make a specific text on TextView BOLD

Here is my complete solution for dynamic String values with case check.

/**
 * Makes a portion of String formatted in BOLD.
 *
 * @param completeString       String from which a portion needs to be extracted and formatted.<br> eg. I am BOLD.
 * @param targetStringToFormat Target String value to format. <br>eg. BOLD
 * @param matchCase Match by target character case or not. If true, BOLD != bold
 * @return A string with a portion formatted in BOLD. <br> I am <b>BOLD</b>.
 */
public static SpannableStringBuilder formatAStringPortionInBold(String completeString, String targetStringToFormat, boolean matchCase) {
    //Null complete string return empty
    if (TextUtils.isEmpty(completeString)) {
        return new SpannableStringBuilder("");
    }

    SpannableStringBuilder str = new SpannableStringBuilder(completeString);
    int start_index = 0;

    //if matchCase is true, match exact string
    if (matchCase) {
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.contains(targetStringToFormat)) {
            return str;
        }

        start_index = str.toString().indexOf(targetStringToFormat);
    } else {
        //else find in lower cases
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.toLowerCase().contains(targetStringToFormat.toLowerCase())) {
            return str;
        }

        start_index = str.toString().toLowerCase().indexOf(targetStringToFormat.toLowerCase());
    }

    int end_index = start_index + targetStringToFormat.length();
    str.setSpan(new StyleSpan(BOLD), start_index, end_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return str;
}

Eg. completeString = "I am BOLD"

CASE I if *targetStringToFormat* = "bold" and *matchCase* = true

returns "I am BOLD" (since bold != BOLD)

CASE II if *targetStringToFormat* = "bold" and *matchCase* = false

returns "I am BOLD"

To Apply:

myTextView.setText(formatAStringPortionInBold("I am BOLD", "bold", false))

Hope that helps!

Postgres ERROR: could not open file for reading: Permission denied

COPY your table (Name, Latitude, Longitude) FROM 'C:\Temp\your file.csv' DELIMITERS ',' CSV HEADER;

Use c:\Temp\"Your File"\.

jquery-ui-dialog - How to hook into dialog close event

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

"close" property of dialog gives the close event for the same.

How to use HTML to print header and footer on every printed page of a document?

Based on some post, i think position: fixed works for me.

_x000D_
_x000D_
body {_x000D_
  background: #eaeaed;_x000D_
  -webkit-print-color-adjust: exact;_x000D_
}_x000D_
_x000D_
.my-footer {_x000D_
  background: #2db34a;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}_x000D_
_x000D_
.my-header {_x000D_
  background: red;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  position: fixed;_x000D_
  right: 0;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset=utf-8 />_x000D_
  <title>Header & Footer</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div>_x000D_
    <div class="my-header">Fixed Header</div>_x000D_
    <div class="my-footer">Fixed Footer</div>_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr>_x000D_
          <th>TH 1</th>_x000D_
          <th>TH 2</th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>TD 1</td>_x000D_
          <td>TD 2</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Press Ctrl+P in chrome see the header & footer text on each page. Hope it helps

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

How do I tar a directory of files and folders without including the directory itself?

Use pax.

Pax is a deprecated package but does the job perfectly and in a simple fashion.

pax -w > mydir.tar mydir

Backbone.js fetch with parameters

Another example if you are using Titanium Alloy:

 collection.fetch({ 
     data: {
             where : JSON.stringify({
                page: 1
             })
           } 
      });

HTML img align="middle" doesn't align an image

remove float left.

Edited: removed reference to align center on an image tag.

Dump a NumPy array into a csv file

If you want to save your numpy array (e.g. your_array = np.array([[1,2],[3,4]])) to one cell, you could convert it first with your_array.tolist().

Then save it the normal way to one cell, with delimiter=';' and the cell in the csv-file will look like this [[1, 2], [2, 4]]

Then you could restore your array like this: your_array = np.array(ast.literal_eval(cell_string))

Updating GUI (WPF) using a different thread

there.

I am also developing a serial port testing tool using WPF, and I'd like to share some experience of mine.

I think you should refactor your source code according to MVVM design pattern.

At the beginning, I met the same problem as you met, and I solved it using this code:

new Thread(() => 
{
    while (...)
    {
        SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...));
    }
}).Start();

This works, but is too ugly. I have no idea how to refactor it, until I saw this: http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

This is a very kindly step-by-step MVVM tutorial for beginners. No shiny UI, no complex logic, only the basic of MVVM.

Visual Studio 2015 doesn't have cl.exe

In Visual Studio 2019 you can find cl.exe inside

32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64

Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.

32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.

Rails Model find where not equal

Rails 4:

If you want to use both not equal and equal, you can use:

user_id = 4
group_id = 27
GroupUser.where(group_id: group_id).where.not(user_id: user_id)

If you want to use a variety of operators (ie. >, <), at some point you may want to switch notations to the following:

GroupUser.where("group_id > ? AND user_id != ?", group_id, user_id)

How to watch and compile all TypeScript sources?

Create a file named tsconfig.json in your project root and include following lines in it:

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "module": "commonjs",
        "target": "ES5",
        "outDir": "ts-built",
        "rootDir": "src"
    }
}

Please note that outDir should be the path of the directory to receive compiled JS files, and rootDir should be the path of the directory containing your source (.ts) files.

Open a terminal and run tsc -w, it'll compile any .ts file in src directory into .js and store them in ts-built directory.

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

No, a List<Dog> is not a List<Animal>. Consider what you can do with a List<Animal> - you can add any animal to it... including a cat. Now, can you logically add a cat to a litter of puppies? Absolutely not.

// Illegal code - because otherwise life would be Bad
List<Dog> dogs = new ArrayList<Dog>(); // ArrayList implements List
List<Animal> animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?

Suddenly you have a very confused cat.

Now, you can't add a Cat to a List<? extends Animal> because you don't know it's a List<Cat>. You can retrieve a value and know that it will be an Animal, but you can't add arbitrary animals. The reverse is true for List<? super Animal> - in that case you can add an Animal to it safely, but you don't know anything about what might be retrieved from it, because it could be a List<Object>.

How to fix nginx throws 400 bad request headers on any header testing tools?

Yes changing the error_to debug level as Emmanuel Joubaud suggested worked out (edit /etc/nginx/sites-enabled/default ):

        error_log /var/log/nginx/error.log debug;

Then after restaring nginx I got in the error log with my Python application using uwsgi:

        2017/02/08 22:32:24 [debug] 1322#1322: *1 connect to unix:///run/uwsgi/app/socket, fd:20 #2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 connected
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream connect: 0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 posix_memalign: 0000560E1F25A2A0:128 @16
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request body
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer buf fl:0 s:454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer in: 0000560E1F2A0928
        2017/02/08 22:32:24 [debug] 1322#1322: *1 writev: 454 of 454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer out: 0000000000000000
        2017/02/08 22:32:24 [debug] 1322#1322: *1 event timer add: 20: 60000:1486593204249
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http finalize request: -4, "/?" a:1, c:2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http request count:2 blk:0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5E40
        2017/02/08 22:32:24 [debug] 1322#1322: *1 delete posted event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http run request: "/?"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream check client, write event:1, "/"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream recv(): -1 (11: Resource temporarily unavailable)

Then I took a look to my uwsgi log and found out that:

        Invalid HTTP_HOST header: 'www.mysite.local'. You may need to add u'www.mysite.local' to ALLOWED_HOSTS.
        [pid: 10903|app: 0|req: 2/4] 192.168.221.2 () {38 vars in 450 bytes} [Wed Feb  8 22:32:24 2017] GET / => generated 54098 bytes in 55 msecs (HTTP/1.1 400) 4 headers in 135 bytes (1 switches on core 0)

And adding www.mysite.local to the settings.py ALLOWED_HOSTS fixed the issue :)

        ALLOWED_HOSTS = ['www.mysite.local']

Excel - match data from one range to another and get the value from the cell to the right of the matched data

I have added the following on my excel sheet

=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)

Still doesn't seem to work. I get an #N/A
BUT

=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)

Works

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

Share Text on Facebook from Android App via ACTION_SEND

Check this out : By this we can check activity results also....
// Open all sharing option for user
                    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
                    sharingIntent.setType("text/plain");                    
                    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, ShortDesc+" from "+BusinessName);
                    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, ShortDesc+" "+ShareURL);
                    sharingIntent.putExtra(Intent.EXTRA_TITLE, ShortDesc+" "+ShareURL);
                    startActivityForResult(Intent.createChooser(sharingIntent, "Share via"),1000);
/**
     * Get the result when we share any data to another activity 
     * */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
        case 1000:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 1 returned OK", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getApplicationContext(), "Activity 1 returned NOT OK", Toast.LENGTH_LONG).show();
            break;
        case 1002:
            if(resultCode == RESULT_OK)
                Toast.makeText(getApplicationContext(), "Activity 2 returned OK", Toast.LENGTH_LONG).show();
            break;
        }// end switch



    }// end onActivityResult

CSS performance relative to translateZ(0)

CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index values are likely to get screwed with.

If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.

So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased; is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.

Tree data structure in C#

Try this simple sample.

public class TreeNode<TValue>
{
    #region Properties
    public TValue Value { get; set; }
    public List<TreeNode<TValue>> Children { get; private set; }
    public bool HasChild { get { return Children.Any(); } }
    #endregion
    #region Constructor
    public TreeNode()
    {
        this.Children = new List<TreeNode<TValue>>();
    }
    public TreeNode(TValue value)
        : this()
    {
        this.Value = value;
    }
    #endregion
    #region Methods
    public void AddChild(TreeNode<TValue> treeNode)
    {
        Children.Add(treeNode);
    }
    public void AddChild(TValue value)
    {
        var treeNode = new TreeNode<TValue>(value);
        AddChild(treeNode);
    }
    #endregion
}

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

I have occurred the same error look following example-

async.waterfall([function(waterCB) {
    waterCB(null);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

In the above waterfall function, I am accepting inputArray parameter in waterfall 2nd function. But this inputArray not passed in waterfall 1st function in waterCB.

Cheak your function parameters Below are a correct example.

async.waterfall([function(waterCB) {
    waterCB(null, **inputArray**);
}, function(**inputArray**, waterCB) {
    waterCB(null);
}], function(waterErr, waterResult) {
    console.log('Done');
});

Thanks

Find an element in DOM based on an attribute value

Use query selectors, examples:

document.querySelectorAll(' input[name], [id|=view], [class~=button] ')

input[name] Inputs elements with name property.

[id|=view] Elements with id that start with view-.

[class~=button] Elements with the button class.

How to go back (ctrl+z) in vi/vim

You can use the u button to undo the last modification. (And Ctrl+R to redo it).

Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

DbEntityValidationException - How can I easily tell what caused the error?

Use try block in your code like

try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges

    context.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

You can check the details here as well

  1. http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/

  2. Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

  3. http://blogs.infosupport.com/improving-dbentityvalidationexception/

jQuery Validate Required Select

how to validate the select "qualifica" it has 3 choose

$(document).ready(function(){

    $('.validateForm').validate({
        rules: {
            fullname: 'required',
            ragionesociale: 'required',
            partitaiva: 'required',
            recapitotelefonico: 'required',
            qualifica: 'required',
            email: {
                required: true,
                email: true
            },
        },
        submitHandler: function(form) {

            var fullname = $('#fullname').val(),
                            ragionesociale = $('#ragionesociale').val(),
                            partitaiva = $('#partitaiva').val(),
                            email = $('#email').val(),
                            recapitotelefonico = $('#recapitotelefonico').val(),
                            qualifica = $('#qualifica').val(),
                            dataString = 'fullname=' + fullname + '&ragionesociale=' + ragionesociale + '&partitaiva=' + partitaiva + '&email=' + email + '&recapitotelefonico=' + recapitotelefonico + '&qualifica=' + qualifica;

            $.ajax({
                type: "POST",
                url: "util/sender.php",
                data: dataString,
                success: function() {

                    window.location.replace("./thank-you-page.php");


                }
            });
            return false;
        }
    });

});

HTML Table cellspacing or padding just top / bottom

CSS?

td {
  padding-top: 2px;
  padding-bottom: 2px;
}

Check if decimal value is null

A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue

How do I get an OAuth 2.0 authentication token in C#

The Rest Client answer is perfect! (I upvoted it)

But, just in case you want to go "raw"

..........

I got this to work with HttpClient.

/*
.nuget\packages\newtonsoft.json\12.0.1
.nuget\packages\system.net.http\4.3.4
*/

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;


    private static async Task<Token> GetElibilityToken(HttpClient client)
    {
        string baseAddress = @"https://blah.blah.blah.com/oauth2/token";

        string grant_type = "client_credentials";
        string client_id = "myId";
        string client_secret = "shhhhhhhhhhhhhhItsSecret";

        var form = new Dictionary<string, string>
                {
                    {"grant_type", grant_type},
                    {"client_id", client_id},
                    {"client_secret", client_secret},
                };

        HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
        return tok;
    }


internal class Token
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }
}       

Here is another working example (based off the answer above)......with a few more tweaks. Sometimes the token-service is finicky:

    private static async Task<Token> GetATokenToTestMyRestApiUsingHttpClient(HttpClient client)
    {
        /* this code has lots of commented out stuff with different permutations of tweaking the request  */

        /* this is a version of asking for token using HttpClient.  aka, an alternate to using default libraries instead of RestClient */

        OAuthValues oav = GetOAuthValues(); /* object has has simple string properties for TokenUrl, GrantType, ClientId and ClientSecret */

        var form = new Dictionary<string, string>
                {
                    { "grant_type", oav.GrantType },
                    { "client_id", oav.ClientId },
                    { "client_secret", oav.ClientSecret }
                };

        /* now tweak the http client */
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Add("cache-control", "no-cache");

        /* try 1 */
        ////client.DefaultRequestHeaders.Add("content-type", "application/x-www-form-urlencoded");

        /* try 2 */
        ////client.DefaultRequestHeaders            .Accept            .Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header

        /* try 3 */
        ////does not compile */client.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        ////application/x-www-form-urlencoded

        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, oav.TokenUrl);
        /////req.RequestUri = new Uri(baseAddress);

        req.Content = new FormUrlEncodedContent(form);

        ////string jsonPayload = "{\"grant_type\":\"" + oav.GrantType + "\",\"client_id\":\"" + oav.ClientId + "\",\"client_secret\":\"" + oav.ClientSecret + "\"}";
        ////req.Content = new StringContent(jsonPayload,                                                Encoding.UTF8,                                                "application/json");//CONTENT-TYPE header

        req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

        /* now make the request */
        ////HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
        HttpResponseMessage tokenResponse = await client.SendAsync(req);
        Console.WriteLine(string.Format("HttpResponseMessage.ReasonPhrase='{0}'", tokenResponse.ReasonPhrase));

        if (!tokenResponse.IsSuccessStatusCode)
        {
            throw new HttpRequestException("Call to get Token with HttpClient failed.");
        }

        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);

        return tok;
    }

APPEND

Bonus Material!

If you ever get a

"The remote certificate is invalid according to the validation procedure."

exception......you can wire in a handler to see what is going on (and massage if necessary)

using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Net;

namespace MyNamespace
{
    public class MyTokenRetrieverWithExtraStuff
    {
        public static async Task<Token> GetElibilityToken()
        {
            using (HttpClientHandler httpClientHandler = new HttpClientHandler())
            {
                httpClientHandler.ServerCertificateCustomValidationCallback = CertificateValidationCallBack;
                using (HttpClient client = new HttpClient(httpClientHandler))
                {
                    return await GetElibilityToken(client);
                }
            }
        }

        private static async Task<Token> GetElibilityToken(HttpClient client)
        {
            // throws certificate error if your cert is wired to localhost // 
            //string baseAddress = @"https://127.0.0.1/someapp/oauth2/token";

            //string baseAddress = @"https://localhost/someapp/oauth2/token";

        string baseAddress = @"https://blah.blah.blah.com/oauth2/token";

        string grant_type = "client_credentials";
        string client_id = "myId";
        string client_secret = "shhhhhhhhhhhhhhItsSecret";

        var form = new Dictionary<string, string>
                {
                    {"grant_type", grant_type},
                    {"client_id", client_id},
                    {"client_secret", client_secret},
                };

            HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
            var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
            Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
            return tok;
        }

        private static bool CertificateValidationCallBack(
        object sender,
        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
        System.Security.Cryptography.X509Certificates.X509Chain chain,
        System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                if (chain != null && chain.ChainStatus != null)
                {
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) &&
                           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                            continue;
                        }
                        else
                        {
                            if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return false;
                            }
                        }
                    }
                }

                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }


            /* overcome localhost and 127.0.0.1 issue */
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
            {
                if (certificate.Subject.Contains("localhost"))
                {
                    HttpRequestMessage castSender = sender as HttpRequestMessage;
                    if (null != castSender)
                    {
                        if (castSender.RequestUri.Host.Contains("127.0.0.1"))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;

        }


        public class Token
        {
            [JsonProperty("access_token")]
            public string AccessToken { get; set; }

            [JsonProperty("token_type")]
            public string TokenType { get; set; }

            [JsonProperty("expires_in")]
            public int ExpiresIn { get; set; }

            [JsonProperty("refresh_token")]
            public string RefreshToken { get; set; }
        }

    }
}

........................

I recently found (Jan/2020) an article about all this. I'll add a link here....sometimes having 2 different people show/explain it helps someone trying to learn it.

http://luisquintanilla.me/2017/12/25/client-credentials-authentication-csharp/

How to use the priority queue STL for objects?

You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement

bool operator<(const Person& lhs, const Person& rhs); 

it should work without any further changes. The implementation could be

bool operator<(const Person& lhs, const Person& rhs)
{
  return lhs.age < rhs.age;
}

If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,

struct LessThanByAge
{
  bool operator()(const Person& lhs, const Person& rhs) const
  {
    return lhs.age < rhs.age;
  }
};

then instantiate the queue like this:

std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;

Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.

C# Test if user has write access to a folder

For example for all users (Builtin\Users), this method works fine - enjoy.

public static bool HasFolderWritePermission(string destDir)
{
   if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
   try
   {
      DirectorySecurity security = Directory.GetAccessControl(destDir);
      SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
      foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
      {
          if(rule.IdentityReference == users)
          {
             FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
             if(rights.AccessControlType == AccessControlType.Allow)
             {
                    if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
             }
          }
       }
       return false;
    }
    catch
    {
        return false;
    }
}

Difference between __getattr__ vs __getattribute__

This is just an example based on Ned Batchelder's explanation.

__getattr__ example:

class Foo(object):
    def __getattr__(self, attr):
        print "looking up", attr
        value = 42
        self.__dict__[attr] = value
        return value

f = Foo()
print f.x 
#output >>> looking up x 42

f.x = 3
print f.x 
#output >>> 3

print ('__getattr__ sets a default value if undefeined OR __getattr__ to define how to handle attributes that are not found')

And if same example is used with __getattribute__ You would get >>> RuntimeError: maximum recursion depth exceeded while calling a Python object

How many times does each value appear in a column?

The quickest way would be with a pivot table. Make sure your column of data has a header row, highlight the data and the header, from the insert ribbon select pivot table and then drag your header from the pivot table fields list to the row labels and to the values boxes.

jQuery send HTML data through POST

If you want to send an arbitrary amount of data to your server, POST is the only reliable method to do that. GET would also be possible but clients and servers allow just a limited URL length (something like 2048 characters).

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

At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.

This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).

A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Hence:

(function($) {
  ...
})(jQuery);

Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal.

Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn. Typically you assign a function to jQuery.fn as plugins are usually just functions.

Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn.

Type 3 is a plugin, but it's not the best or easiest way to create one.

To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

Regex match digits, comma and semicolon?

word.matches("^[0-9,;]+$"); you were almost there

jQuery UI 1.10: dialog and zIndex option

Add zIndex property to dialog object:

$(elm).dialog(
 zIndex: 10000
);

How to avoid HTTP error 429 (Too Many Requests) python

I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.

Check out this article

Passing an array to a query using a WHERE clause

Safer.

$galleries = array(1,2,5);
array_walk($galleries , 'intval');
$ids = implode(',', $galleries);
$sql = "SELECT * FROM galleries WHERE id IN ($ids)";

Using set_facts and with_items together in Ansible

I was hunting around for an answer to this question. I found this helpful. The pattern wasn't apparent in the documentation for with_items.

https://github.com/ansible/ansible/issues/39389

- hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: set_fact
      set_fact:
        foo: "{{ foo }} + [ '{{ item }}' ]"
      with_items:
        - "one"
        - "two"
        - "three"
      vars:
        foo: []

    - name: Print the var
      debug:
        var: foo

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

With ASP.NET project with C# 4.5 I've solved such problem by installing ASP.NET extension in Web Platform Installer

The imported project "C:\Microsoft.CSharp.targets" was not found

I got this after reinstalling Windows. Visual Studio was installed, and I could see the Silverlight project type in the New Project window, but opening one didn't work. The solution was simple: I had to install the Silverlight Developer runtime and/or the Microsoft Silverlight 4 Tools for Visual Studio. This may seem stupid, but I overlooked it because I thought it should work, as the Silverlight project type was available.

Remove unwanted parts from strings in a column

How do I remove unwanted parts from strings in a column?

6 years after the original question was posted, pandas now has a good number of "vectorised" string functions that can succinctly perform these string manipulation operations.

This answer will explore some of these string functions, suggest faster alternatives, and go into a timings comparison at the end.


.str.replace

Specify the substring/pattern to match, and the substring to replace it with.

pd.__version__
# '0.24.1'

df    
    time result
1  09:00   +52A
2  10:00   +62B
3  11:00   +44a
4  12:00   +30b
5  13:00  -110a

df['result'] = df['result'].str.replace(r'\D', '')
df

    time result
1  09:00     52
2  10:00     62
3  11:00     44
4  12:00     30
5  13:00    110

If you need the result converted to an integer, you can use Series.astype,

df['result'] = df['result'].str.replace(r'\D', '').astype(int)

df.dtypes
time      object
result     int64
dtype: object

If you don't want to modify df in-place, use DataFrame.assign:

df2 = df.assign(result=df['result'].str.replace(r'\D', ''))
df
# Unchanged

.str.extract

Useful for extracting the substring(s) you want to keep.

df['result'] = df['result'].str.extract(r'(\d+)', expand=False)
df

    time result
1  09:00     52
2  10:00     62
3  11:00     44
4  12:00     30
5  13:00    110

With extract, it is necessary to specify at least one capture group. expand=False will return a Series with the captured items from the first capture group.


.str.split and .str.get

Splitting works assuming all your strings follow this consistent structure.

# df['result'] = df['result'].str.split(r'\D').str[1]
df['result'] = df['result'].str.split(r'\D').str.get(1)
df

    time result
1  09:00     52
2  10:00     62
3  11:00     44
4  12:00     30
5  13:00    110

Do not recommend if you are looking for a general solution.


If you are satisfied with the succinct and readable str accessor-based solutions above, you can stop here. However, if you are interested in faster, more performant alternatives, keep reading.


Optimizing: List Comprehensions

In some circumstances, list comprehensions should be favoured over pandas string functions. The reason is because string functions are inherently hard to vectorize (in the true sense of the word), so most string and regex functions are only wrappers around loops with more overhead.

My write-up, Are for-loops in pandas really bad? When should I care?, goes into greater detail.

The str.replace option can be re-written using re.sub

import re

# Pre-compile your regex pattern for more performance.
p = re.compile(r'\D')
df['result'] = [p.sub('', x) for x in df['result']]
df

    time result
1  09:00     52
2  10:00     62
3  11:00     44
4  12:00     30
5  13:00    110

The str.extract example can be re-written using a list comprehension with re.search,

p = re.compile(r'\d+')
df['result'] = [p.search(x)[0] for x in df['result']]
df

    time result
1  09:00     52
2  10:00     62
3  11:00     44
4  12:00     30
5  13:00    110

If NaNs or no-matches are a possibility, you will need to re-write the above to include some error checking. I do this using a function.

def try_extract(pattern, string):
    try:
        m = pattern.search(string)
        return m.group(0)
    except (TypeError, ValueError, AttributeError):
        return np.nan

p = re.compile(r'\d+')
df['result'] = [try_extract(p, x) for x in df['result']]
df

    time result
1  09:00     52
2  10:00     62
3  11:00     44
4  12:00     30
5  13:00    110

We can also re-write @eumiro's and @MonkeyButter's answers using list comprehensions:

df['result'] = [x.lstrip('+-').rstrip('aAbBcC') for x in df['result']]

And,

df['result'] = [x[1:-1] for x in df['result']]

Same rules for handling NaNs, etc, apply.


Performance Comparison

enter image description here

Graphs generated using perfplot. Full code listing, for your reference. The relevant functions are listed below.

Some of these comparisons are unfair because they take advantage of the structure of OP's data, but take from it what you will. One thing to note is that every list comprehension function is either faster or comparable than its equivalent pandas variant.

Functions

def eumiro(df):
    return df.assign(
        result=df['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC')))

def coder375(df):
    return df.assign(
        result=df['result'].replace(r'\D', r'', regex=True))

def monkeybutter(df):
    return df.assign(result=df['result'].map(lambda x: x[1:-1]))

def wes(df):
    return df.assign(result=df['result'].str.lstrip('+-').str.rstrip('aAbBcC'))

def cs1(df):
    return df.assign(result=df['result'].str.replace(r'\D', ''))

def cs2_ted(df):
    # `str.extract` based solution, similar to @Ted Petrou's. so timing together.
    return df.assign(result=df['result'].str.extract(r'(\d+)', expand=False))

def cs1_listcomp(df):
    return df.assign(result=[p1.sub('', x) for x in df['result']])

def cs2_listcomp(df):
    return df.assign(result=[p2.search(x)[0] for x in df['result']])

def cs_eumiro_listcomp(df):
    return df.assign(
        result=[x.lstrip('+-').rstrip('aAbBcC') for x in df['result']])

def cs_mb_listcomp(df):
    return df.assign(result=[x[1:-1] for x in df['result']])

How do I read a date in Excel format in Python?

After testing and a few days wait for feedback, I'll svn-commit the following whole new function in xlrd's xldate module ... note that it won't be available to the diehards still running Python 2.1 or 2.2.

##
# Convert an Excel number (presumed to represent a date, a datetime or a time) into
# a Python datetime.datetime
# @param xldate The Excel number
# @param datemode 0: 1900-based, 1: 1904-based.
# <br>WARNING: when using this function to
# interpret the contents of a workbook, you should pass in the Book.datemode
# attribute of that workbook. Whether
# the workbook has ever been anywhere near a Macintosh is irrelevant.
# @return a datetime.datetime object, to the nearest_second.
# <br>Special case: if 0.0 <= xldate < 1.0, it is assumed to represent a time;
# a datetime.time object will be returned.
# <br>Note: 1904-01-01 is not regarded as a valid date in the datemode 1 system; its "serial number"
# is zero.
# @throws XLDateNegative xldate < 0.00
# @throws XLDateAmbiguous The 1900 leap-year problem (datemode == 0 and 1.0 <= xldate < 61.0)
# @throws XLDateTooLarge Gregorian year 10000 or later
# @throws XLDateBadDatemode datemode arg is neither 0 nor 1
# @throws XLDateError Covers the 4 specific errors

def xldate_as_datetime(xldate, datemode):
    if datemode not in (0, 1):
        raise XLDateBadDatemode(datemode)
    if xldate == 0.00:
        return datetime.time(0, 0, 0)
    if xldate < 0.00:
        raise XLDateNegative(xldate)
    xldays = int(xldate)
    frac = xldate - xldays
    seconds = int(round(frac * 86400.0))
    assert 0 <= seconds <= 86400
    if seconds == 86400:
        seconds = 0
        xldays += 1
    if xldays >= _XLDAYS_TOO_LARGE[datemode]:
        raise XLDateTooLarge(xldate)

    if xldays == 0:
        # second = seconds % 60; minutes = seconds // 60
        minutes, second = divmod(seconds, 60)
        # minute = minutes % 60; hour    = minutes // 60
        hour, minute = divmod(minutes, 60)
        return datetime.time(hour, minute, second)

    if xldays < 61 and datemode == 0:
        raise XLDateAmbiguous(xldate)

    return (
        datetime.datetime.fromordinal(xldays + 693594 + 1462 * datemode)
        + datetime.timedelta(seconds=seconds)
        )

Found 'OR 1=1/* sql injection in my newsletter database

It probably aimed to select all the informations in your table. If you use this kind of query (for example in PHP) :

mysql_query("SELECT * FROM newsletter WHERE email = '$email'");

The email ' OR 1=1/* will give this kind of query :

mysql_query("SELECT * FROM newsletter WHERE email = '' OR 1=1/*");

So it selects all the rows (because 1=1 is always true and the rest of the query is 'commented'). But it was not successful

  • if strings used in your queries are escaped
  • if you don't display all the queries results on a page...

Frame Buster Buster ... buster code needed

After pondering this for a little while, I believe this will show them who's boss...

if(top != self) {
  window.open(location.href, '_top');
}

Using _top as the target parameter for window.open() will launch it in the same window.

MySQL Cannot Add Foreign Key Constraint

Try to use the same type of your primary keys - int(11) - on the foreign keys - smallint(5) - as well.

Hope it helps!

SQL Server: Difference between PARTITION BY and GROUP BY

We can take a simple example.

Consider a table named TableA with the following values:

id  firstname                   lastname                    Mark
-------------------------------------------------------------------
1   arun                        prasanth                    40
2   ann                         antony                      45
3   sruthy                      abc                         41
6   new                         abc                         47
1   arun                        prasanth                    45
1   arun                        prasanth                    49
2   ann                         antony                      49

GROUP BY

The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.

In more simple words GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

Syntax:

SELECT expression1, expression2, ... expression_n, 
       aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;

We can apply GROUP BY in our table:

select SUM(Mark)marksum,firstname from TableA
group by id,firstName

Results:

marksum  firstname
----------------
94      ann                      
134     arun                     
47      new                      
41      sruthy   

In our real table we have 7 rows and when we apply GROUP BY id, the server group the results based on id:

In simple words:

here GROUP BY normally reduces the number of rows returned by rolling them up and calculating Sum() for each row.

PARTITION BY

Before going to PARTITION BY, let us look at the OVER clause:

According to the MSDN definition:

OVER clause defines a window or user-specified set of rows within a query result set. A window function then computes a value for each row in the window. You can use the OVER clause with functions to compute aggregated values such as moving averages, cumulative aggregates, running totals, or a top N per group results.

PARTITION BY will not reduce the number of rows returned.

We can apply PARTITION BY in our example table:

SELECT SUM(Mark) OVER (PARTITION BY id) AS marksum, firstname FROM TableA

Result:

marksum firstname 
-------------------
134     arun                     
134     arun                     
134     arun                     
94      ann                      
94      ann                      
41      sruthy                   
47      new  

Look at the results - it will partition the rows and returns all rows, unlike GROUP BY.

Invalid default value for 'create_date' timestamp field

TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC (see doc). The default value must be within that range.

Other odd, related, behavior:

CREATE TABLE tbl1 (
    ts TIMESTAMP);  
Query OK, 0 rows affected (0.01 sec)

CREATE TABLE tbl2 (
    ts TIMESTAMP,
    ts2 TIMESTAMP);
ERROR 1067 (42000): Invalid default value for 'ts2'

CREATE TABLE tbl3 (
    ts TIMESTAMP,
    ts2 TIMESTAMP DEFAULT '1970-01-01 00:00:01');
Query OK, 0 rows affected (0.01 sec)

Side note, if you want to insert NULLS:

CREATE TABLE tbl4 (
    ts TIMESTAMP NULL DEFAULT NULL);

Setting dropdownlist selecteditem programmatically

var index = ctx.Items.FirstOrDefault(item => Equals(item.Value, Settings.Default.Format_Encoding));
ctx.SelectedIndex = ctx.Items.IndexOf(index);

OR

foreach (var listItem in ctx.Items)
  listItem.Selected = Equals(listItem.Value as Encoding, Settings.Default.Format_Encoding);

Should work.. especially when using extended RAD controls in which FindByText/Value doesn't even exist!

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

set NODE_ENV=production & nodemon app/app.js

will cause NODE_ENV to contain a space at the end:

process.env.NODE_ENV == 'production'; //false
process.env.NODE_ENV == 'production '; //true

As mentioned in a comment here, use this instead:

NODE_ENV=production&& nodemon app/app.js

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

What is the "__v" field in Mongoose

For remove in NestJS need to add option to Shema() decorator

@Schema({ versionKey: false })

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

If the issue is a missing intermediate certificate, you can enable Oracle JRE to automatically download the missing intermediate certificate as explained in this answer.

Just set the Java system property -Dcom.sun.security.enableAIAcaIssuers=true

For this to work the server's certificate must provide the URI to the intermediate certificate (the certificate's issuer). As far as I can tell, this is what browsers do as well and should be just as secure - I'm not a security expert though.

Edit: If I recall correctly, this seems to work at least with Java 8 and is documented here for Java 9.

Writing a large resultset to an Excel file using POI

Using SXSSF poi 3.8

package example;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class SXSSFexample {


    public static void main(String[] args) throws Throwable {
        FileInputStream inputStream = new FileInputStream("mytemplate.xlsx");
        XSSFWorkbook wb_template = new XSSFWorkbook(inputStream);
        inputStream.close();

        SXSSFWorkbook wb = new SXSSFWorkbook(wb_template); 
        wb.setCompressTempFiles(true);

        SXSSFSheet sh = (SXSSFSheet) wb.getSheetAt(0);
        sh.setRandomAccessWindowSize(100);// keep 100 rows in memory, exceeding rows will be flushed to disk
    for(int rownum = 4; rownum < 100000; rownum++){
        Row row = sh.createRow(rownum);
        for(int cellnum = 0; cellnum < 10; cellnum++){
            Cell cell = row.createCell(cellnum);
            String address = new CellReference(cell).formatAsString();
            cell.setCellValue(address);
        }

    }


    FileOutputStream out = new FileOutputStream("tempsxssf.xlsx");
    wb.write(out);
    out.close();
}

}

It requires:

  • poi-ooxml-3.8.jar,
  • poi-3.8.jar,
  • poi-ooxml-schemas-3.8.jar,
  • stax-api-1.0.1.jar,
  • xml-apis-1.0.b2.jar,
  • xmlbeans-2.3.0.jar,
  • commons-codec-1.5.jar,
  • dom4j-1.6.1.jar

Useful link

MySQL: When is Flush Privileges in MySQL really needed?

Privileges assigned through GRANT option do not need FLUSH PRIVILEGES to take effect - MySQL server will notice these changes and reload the grant tables immediately.

From MySQL documentation:

If you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE, your changes have no effect on privilege checking until you either restart the server or tell it to reload the tables. If you change the grant tables directly but forget to reload them, your changes have no effect until you restart the server. This may leave you wondering why your changes seem to make no difference!

To tell the server to reload the grant tables, perform a flush-privileges operation. This can be done by issuing a FLUSH PRIVILEGES statement or by executing a mysqladmin flush-privileges or mysqladmin reload command.

If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.

Printing Lists as Tabular Data

A simple way to do this is to loop over all columns, measure their width, create a row_template for that max width, and then print the rows. It's not exactly what you are looking for, because in this case, you first have to put your headings inside the table, but I'm thinking it might be useful to someone else.

table = [
    ["", "Man Utd", "Man City", "T Hotspur"],
    ["Man Utd", 1, 0, 0],
    ["Man City", 1, 1, 0],
    ["T Hotspur", 0, 1, 2],
]
def print_table(table):
    longest_cols = [
        (max([len(str(row[i])) for row in table]) + 3)
        for i in range(len(table[0]))
    ]
    row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols])
    for row in table:
        print(row_format.format(*row))

You use it like this:

>>> print_table(table)

            Man Utd   Man City   T Hotspur
  Man Utd         1          0           0
 Man City         1          1           0
T Hotspur         0          1           2

Python if not == vs if !=

It's about your way of reading it. not operator is dynamic, that's why you are able to apply it in

if not x == 'val':

But != could be read in a better context as an operator which does the opposite of what == does.

How do I format a string using a dictionary in python-3.x?

As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping) (Python 3.2+):

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass.

What this means is that you can use for example a defaultdict that would set (and return) a default value for keys that are missing:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

Even if the mapping provided is a dict, not a subclass, this would probably still be slightly faster.

The difference is not big though, given

>>> d = dict(foo='x', bar='y', baz='z')

then

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

is about 10 ns (2 %) faster than

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and


Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

Starting from 3.6 you can use the interpolated strings too:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.

Git: How to remove file from index without deleting files from any repository

Had the very same issue this week when I accidentally committed, then tried to remove a build file from a shared repository, and this:

http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html

has worked fine for me and not mentioned so far.

git update-index --assume-unchanged <file>

To remove the file you're interested in from version control, then use all your other commands as normal.

git update-index --no-assume-unchanged <file>

If you ever wanted to put it back in.

Edit: please see comments from Chris Johnsen and KPM, this only works locally and the file remains under version control for other users if they don't also do it. The accepted answer gives more complete/correct methods for dealing with this. Also some notes from the link if using this method:

Obviously there’s quite a few caveats that come into play with this. If you git add the file directly, it will be added to the index. Merging a commit with this flag on will cause the merge to fail gracefully so you can handle it manually.

Eclipse: How to build an executable jar with external jar?

Eclipse 3.5 has an option to package required libraries into the runnable jar. File -> Export... Choose runnable jar and click next. The runnable jar export window has a radio button where you can choose to package the required libraries into the jar.

How to "fadeOut" & "remove" a div in jQuery?

Use

.fadeOut(360).delay(400).remove();

ValueError: could not convert string to float: id

Obviously some of your lines don't have valid float data, specifically some line have text id which can't be converted to float.

When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.

#!/usr/bin/python

import os,sys
from scipy import stats
import numpy as np

f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
        list1=[float(x) for x in l1]
        list2=[float(x) for x in l2]
    except ValueError,e:
        print "error",e,"on line",i
    result=stats.ttest_ind(list1,list2)
    print result[1]

How to read a file into vector in C++?

Your loop is wrong:

for (int i=0; i=((Main.size())-1); i++) {

Try this:

for (int i=0; i < Main.size(); i++) {

Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:

#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy

int main()
{
  std::ifstream is("numbers.txt");
  std::istream_iterator<double> start(is), end;
  std::vector<double> numbers(start, end);
  std::cout << "Read " << numbers.size() << " numbers" << std::endl;

  // print the numbers to stdout
  std::cout << "numbers read in:\n";
  std::copy(numbers.begin(), numbers.end(), 
            std::ostream_iterator<double>(std::cout, " "));
  std::cout << std::endl;

}

although you should check the status of the ifstream for read errors.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

It could be related with your Java version. Go ahead and download the Database version which includes Java.

However, if you are configuring a local development workstation I recommend you to download the Express Edition.

Here is the link: http://www.oracle.com/technetwork/products/express-edition/downloads/index-083047.html

or google this: OracleXE112_Win64

Good luck!

getch and arrow codes

So, after alot of struggle, I miraculously solved this everannoying issue ! I was trying to mimic a linux terminal and got stuck at the part where it keeps a command history which can be accessed by pressing up or down arrow keys. I found ncurses lib to be painfuly hard to comprehend and slow to learn.

char ch = 0, k = 0;
while(1)
{
  ch = getch();
  if(ch == 27)                  // if ch is the escape sequence with num code 27, k turns 1 to signal the next
    k = 1;
  if(ch == 91 && k == 1)       // if the previous char was 27, and the current 91, k turns 2 for further use
    k = 2;
  if(ch == 65 && k == 2)       // finally, if the last char of the sequence matches, you've got a key !
    printf("You pressed the up arrow key !!\n");
  if(ch == 66 && k == 2)                             
    printf("You pressed the down arrow key !!\n");
  if(ch != 27 && ch != 91)      // if ch isn't either of the two, the key pressed isn't up/down so reset k
    k = 0;
  printf("%c - %d", ch, ch);    // prints out the char and it's int code

It's kind of bold but it explains alot. Good luck !

How to initialise a string from NSData in Swift

Since the third version of Swift you can do the following:

let desiredString = NSString(data: yourData, encoding: String.Encoding.utf8.rawValue)

simialr to what Sunkas advised.

How do I request a file but not save it with Wget?

You can use -O- (uppercase o) to redirect content to the stdout (standard output) or to a file (even special files like /dev/null /dev/stderr /dev/stdout )

wget -O- http://yourdomain.com

Or:

wget -O- http://yourdomain.com > /dev/null

Or: (same result as last command)

wget -O/dev/null http://yourdomain.com

Display tooltip on Label's hover?

Tooltips in bootstrap are good, but there is also a very good tooltip function in jQuery UI, which you can read about here.

Example:

<label for="male" id="foo" title="Hello This Will Have Some Value">Hello...</label>

Then, assuming you have already referenced jQuery and jQueryUI libraries in your head, add a script element like this:

<script type="text/javascript">
$(document).ready(function(){
    $(this).tooltip();
});
</script>

This will display the contents of the title attribute as a tooltip when you rollover any element with a title attribute.

How to check if a column exists before adding it to an existing table in PL/SQL?

To check column exists

select column_name as found
from user_tab_cols
where table_name = '__TABLE_NAME__'
and column_name = '__COLUMN_NAME__'

Reference link

Comparing two columns, and returning a specific adjacent cell in Excel

In cell D2 and copied down:

=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Add this code in the Module :

Public Sub ClearTextBoxes(frm As Form) 

    For Each Control In frm.Controls
        If TypeOf Control Is TextBox Then
            Control.Text = ""     'Clear all text
        End If       
    Next Control

End Sub

Add this code in the Form window to Call the Sub routine:

Private Sub Command1_Click()
    Call ClearTextBoxes(Me)
End Sub

Bootstrap 3 breakpoints and media queries

Here are the selectors used in Bootstrap 4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.

@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Right way to write JSON deserializer in Spring or extend it

I was trying to @Autowire a Spring-managed service into my Deserializer. Somebody tipped me off to Jackson using the new operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer. Here's how I was able to @Autowire my service class into my Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

Now that my Deserializer is a Spring-managed bean, auto-wiring works!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

AnchorService.java

@Service
public class AnchorService {}

Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

Read this:

http://www.quora.com/OAuth-2-0/How-does-OAuth-2-0-work

or an even simpler but quick explanation:

http://agileanswer.blogspot.se/2012/08/oauth-20-for-my-ninth-grader.html

The redirect URI is the callback entry point of the app. Think about how OAuth for Facebook works - after end user accepts permissions, "something" has to be called by Facebook to get back to the app, and that "something" is the redirect URI. Furthermore, the redirect URI should be different than the initial entry point of the app.

The other key point to this puzzle is that you could launch your app from a URL given to a webview. To do this, i simply followed the guide on here:

http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html

and

http://inchoo.net/mobile-development/iphone-development/launching-application-via-url-scheme/

note: on those last 2 links, "http://" works in opening mobile safari but "tel://" doesn't work in simulator

in the first app, I call

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"secondApp://"]];

In my second app, I register "secondApp" (and NOT "secondApp://") as the name of URL Scheme, with my company as the URL identifier.

How do you run a script on login in *nix?

Add an entry in /etc/profile that executes the script. This will be run during every log-on. If you are only doing this for your own account, use one of your login scripts (e.g. .bash_profile) to run it.

How do I enable the column selection mode in Eclipse?

A different approach:

The vrapper plugin emulates vim inside the Eclipse editor. One of its features is visual block mode which works fine inside Eclipse.

It is by default mapped to Ctrl-V which interferes with the paste command in Eclipse. You can either remap the visual block mode to a different shortcut, or remap the paste command to a different key. I chose the latter: remapped the paste command to Ctrl-Shift-V to match my terminal's behavior.

Fix height of a table row in HTML Table

This works, as long as you remove the height attribute from the table.

<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
  <tr><td height='9px' bgcolor="#990000">Upper</td></tr>
  <tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>

How to put a text beside the image?

I had a similar issue, where I had one div holding the image, and one div holding the text. The reason mine wasn't working, was that the div holding the image had display: inline-block while the div holding the text had display: inline.

I changed it to both be display: inline and it worked.

Here's a solution for a basic header section with a logo, title and tagline:

HTML

<div class="site-branding">
  <div class="site-branding-logo">
    <img src="add/Your/URI/Here" alt="what Is The Image About?" />
  </div>
</div>
<div class="site-branding-text">
  <h1 id="site-title">Site Title</h1>
  <h2 id="site-tagline">Site Tagline</h2>
</div>

CSS

div.site-branding { /* Position Logo and Text  */
  display: inline-block;
  vertical-align: middle;
}

div.site-branding-logo { /* Position logo within site-branding */
  display: inline;
  vertical-align: middle;
}

div.site-branding-text { /* Position text within site-branding */
    display: inline;
    width: 350px;
    margin: auto 0;
    vertical-align: middle;
}

div.site-branding-title { /* Position title within text */
    display: inline;
}

div.site-branding-tagline { /* Position tagline within text */
    display: block;
}

How do I convert a numpy array to (and display) an image?

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)

SQL - How do I get only the numbers after the decimal?

More generalized approach may be to merge PARSENAME and % operator. (as answered in two of the answers above)

Results as per 1st approach above by SQLMenace

select PARSENAME(0.001,1) 

Result: 001

select PARSENAME(0.0010,1) 

Result: 0010

select PARSENAME(-0.001,1)

Result: 001

select PARSENAME(-1,1)

Result: -1 --> Should not return integer part

select PARSENAME(0,1)

Result: 0

select PARSENAME(1,1)

Result: 1 --> Should not return integer part

select PARSENAME(100.00,1)

Result: 00

Results as per 1st approach above by Pavel Morshenyuk "0." is part of result in this case.

SELECT (100.0001 % 1)

Result: 0.0001

SELECT (100.0010 % 1)

Result: 0.0010

SELECT (0.0001 % 1)

Result: 0.0001

SELECT (0001 % 1)

Result: 0

SELECT (1 % 1)

Result: 0

SELECT (100 % 1)

Result: 0

Combining both:

SELECT PARSENAME((100.0001 % 1),1)

Result: 0001

SELECT PARSENAME((100.0010 % 1),1)

Result: 0010

SELECT PARSENAME((0.0001 % 1),1)

Result: 0001

SELECT PARSENAME((0001 % 1),1)

Result: 0

SELECT PARSENAME((1 % 1),1)

Result: 0

SELECT PARSENAME((100 % 1),1)

Result: 0

But still one issue which remains is the zero after the non zero numbers are part of the result (Example: 0.0010 -> 0010). May be one have to apply some other logic to remove that.

Differences between Oracle JDK and OpenJDK

A list of the few remaining cosmetic and packaging differences between Oracle JDK 11 and OpenJDK 11 can be found in this blog post:

https://blogs.oracle.com/java-platform-group/oracle-jdk-releases-for-java-11-and-later

In short:

  • Oracle JDK 11 emits a warning when using the -XX:+UnlockCommercialFeatures option,
  • it can be configured to provide usage log data to the “Advanced Management Console” tool,
  • it has always required third party cryptographic providers to be signed by a known certificate,
  • it will continue to include installers, branding and JRE packaging,
  • while the javac --release command behaves slightly differently for the Java 9 and Java 10 targets, and
  • the output of the java --version and java -fullversion commands will distinguish Oracle JDK builds from OpenJDK builds.

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

Simple way to repeat a string

repeated = str + str + str;

Sometimes simple is best. Everyone reading the code can see what's happening.

And the compiler will do the fancy stuff with StringBuilder behind the scenes for you.

'workbooks.worksheets.activate' works, but '.select' does not

You can't select a sheet in a non-active workbook.

You must first activate the workbook, then you can select the sheet.

workbooks("A").activate
workbooks("A").worksheets("B").select 

When you use Activate it automatically activates the workbook.

Note you can select >1 sheet in a workbook:

activeworkbook.sheets(array("sheet1","sheet3")).select

but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.

Unknown Column In Where Clause

See the following MySQL manual page: http://dev.mysql.com/doc/refman/5.0/en/select.html

"A select_expr can be given an alias using AS alias_name. The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses."

(...)

It is not permissible to refer to a column alias in a WHERE clause, because the column value might not yet be determined when the WHERE clause is executed. See Section B.5.4.4, “Problems with Column Aliases”.

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

Error handling in AngularJS http get then construct

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })

Incomplete type is not allowed: stringstream

Some of the system headers provide a forward declaration of std::stringstream without the definition. This makes it an 'incomplete type'. To fix that you need to include the definition, which is provided in the <sstream> header:

#include <sstream>

prevent property from being serialized in web API

I will show you 2 ways to accomplish what you want:

First way: Decorate your field with JsonProperty attribute in order to skip the serialization of that field if it is null.

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<Something> Somethings { get; set; }
}

Second way: If you are negotiation with some complex scenarios then you could use the Web Api convention ("ShouldSerialize") in order to skip serialization of that field depending of some specific logic.

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }

    public List<Something> Somethings { get; set; }

    public bool ShouldSerializeSomethings() {
         var resultOfSomeLogic = false;
         return resultOfSomeLogic; 
    }
}

WebApi uses JSON.Net and it use reflection to serialization so when it has detected (for instance) the ShouldSerializeFieldX() method the field with name FieldX will not be serialized.

Generate GUID in MySQL for existing Data?

// UID Format: 30B9BE365FF011EA8F4C125FC56F0F50
UPDATE `events` SET `evt_uid` = (SELECT UPPER(REPLACE(@i:=UUID(),'-','')));

// UID Format: c915ec5a-5ff0-11ea-8f4c-125fc56f0f50
UPDATE `events` SET `evt_uid` = (SELECT UUID());

// UID Format: C915EC5a-5FF0-11EA-8F4C-125FC56F0F50
UPDATE `events` SET `evt_uid` = (SELECT UPPER(@i:=UUID()));

convert float into varchar in SQL server without scientific notation

I have another solution since the STR() function would result some blank spaces, so I use the FORMAT() function as folowing example:

SELECT ':' + STR(1000.2324422), ':' + FORMAT(1000.2324422,'##.#######'), ':' + FORMAT(1000.2324422,'##')

The result of above code would be:

:      1000 :1000.2324422   :1000

C#: Limit the length of a string?

You can't. Bear in mind that foo is a variable of type string.

You could create your own type, say BoundedString, and have:

BoundedString foo = new BoundedString(5);
foo.Text = "hello"; // Fine
foo.Text = "naughty"; // Throw an exception or perhaps truncate the string

... but you can't stop a string variable from being set to any string reference (or null).

Of course, if you've got a string property, you could do that:

private string foo;
public string Foo
{
    get { return foo; }
    set
    {
        if (value.Length > 5)
        {
            throw new ArgumentException("value");
        }
        foo = value;
    }
}

Does that help you in whatever your bigger context is?

Creating a simple login form

Great Start to learning login forms. You are right, fieldset may not be the best tag.

However, I highly suggest you code it in HTML5 by using its robust form features.

HTML5 is actually easier to learn than older HTML for creating forms.

For example, read the following.

<section class="loginform cf">  
    <form name="login" action="index_submit" method="get" accept-charset="utf-8">  
        <ul>  
            <li><label for="usermail">Email</label>  
            <input type="email" name="usermail" placeholder="[email protected]" required></li>  
            <li><label for="password">Password</label>  
            <input type="password" name="password" placeholder="password" required></li>  
            <li>  
            <input type="submit" value="Login"></li>  
        </ul>  
    </form>  
</section>

Wasn't that easy for you to understand?

Try this http://www.hongkiat.com/blog/html5-loginpage/ and let me know if you have any questions.

How to catch a click event on a button?

All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.

An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.

package com.pointerunits.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
   private Button login;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      login = (Button)findViewById(R.id.loginbutton);
      login.setOnClickListener((OnClickListener) this);
      Log.i(DISPLAY_SERVICE, "Activity is created");

   }    

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {

      getMenuInflater().inflate(R.menu.main, menu);
      return true;
    }

   @Override
   public void onClick(View v) {
     Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
   }
}

How do you change library location in R?

I'm late to the party but I encountered the same thing when I tried to get fancy and move my library and then had files being saved to a folder that was outdated:

.libloc <<- "C:/Program Files/rest_of_your_Library_FileName"

One other point to mention is that for Windows Computers, if you copy the address from Windows Explorer, you have to manually change the '\' to a '/' for the directory to be recognized.

Dynamically Add Variable Name Value Pairs to JSON Object

With ECMAScript 6 there is a better way.

You can use computed property names in object property definitions, for example:

var name1 = 'John'; 
var value1 = '42'; 
var name2 = 'Sarah'; 
var value2 = '35';

var ipID = { 
             [name1] : value1, 
             [name2] : value2 
           }

This is equivalent to the following, where you have variables for the property names.

var ipID = { 
             John: '42', 
             Sarah: '35' 
           }

How to Diff between local uncommitted changes and origin

To see non-staged (non-added) changes to existing files

git diff

Note that this does not track new files. To see staged, non-commited changes

git diff --cached

Unable to make the session state request to the session state server

  1. Start–> Administrative Tools –> Services
  2. Right-click on the ASP.NET State Service and click “start”

Additionally you could set the service to automatic so that it will work after a reboot

SQL Server, How to set auto increment after creating a table without data loss?

Changing the IDENTITY property is really a metadata only change. But to update the metadata directly requires starting the instance in single user mode and messing around with some columns in sys.syscolpars and is undocumented/unsupported and not something I would recommend or will give any additional details about.

For people coming across this answer on SQL Server 2012+ by far the easiest way of achieving this result of an auto incrementing column would be to create a SEQUENCE object and set the next value for seq as the column default.

Alternatively, or for previous versions (from 2005 onwards), the workaround posted on this connect item shows a completely supported way of doing this without any need for size of data operations using ALTER TABLE...SWITCH. Also blogged about on MSDN here. Though the code to achieve this is not very simple and there are restrictions - such as the table being changed can't be the target of a foreign key constraint.

Example code.

Set up test table with no identity column.

CREATE TABLE dbo.tblFoo 
(
bar INT PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)


INSERT INTO dbo.tblFoo (bar)
SELECT TOP (10000) ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM master..spt_values v1, master..spt_values v2

Alter it to have an identity column (more or less instant).

BEGIN TRY;
    BEGIN TRANSACTION;

    /*Using DBCC CHECKIDENT('dbo.tblFoo') is slow so use dynamic SQL to
      set the correct seed in the table definition instead*/
    DECLARE @TableScript nvarchar(max)
    SELECT @TableScript = 
    '
    CREATE TABLE dbo.Destination(
        bar INT IDENTITY(' + 
                     CAST(ISNULL(MAX(bar),0)+1 AS VARCHAR) + ',1)  PRIMARY KEY,
        filler CHAR(8000),
        filler2 CHAR(49)
        )

        ALTER TABLE dbo.tblFoo SWITCH TO dbo.Destination;
    '       
    FROM dbo.tblFoo
    WITH (TABLOCKX,HOLDLOCK)

    EXEC(@TableScript)


    DROP TABLE dbo.tblFoo;

    EXECUTE sp_rename N'dbo.Destination', N'tblFoo', 'OBJECT';


    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
    PRINT ERROR_MESSAGE();
END CATCH;

Test the result.

INSERT INTO dbo.tblFoo (filler,filler2) 
OUTPUT inserted.*
VALUES ('foo','bar')

Gives

bar         filler    filler2
----------- --------- ---------
10001       foo       bar      

Clean up

DROP TABLE dbo.tblFoo