Programs & Examples On #Subsonic

SubSonic is A Super High-fidelity Batman Utility Belt that works up your Data Access (using Linq in 3.0), throws in some much-needed utility functions, and generally speeds along your dev cycle.

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

I had the same problem and solved by using Newtonsoft.Json;

var list = JsonConvert.SerializeObject(model,
    Formatting.None,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

return Content(list, "application/json");

MySQL pivot table query with dynamic columns

I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

SET @sql = '';
SELECT
    @sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
    SELECT
      DISTINCT
        CONCAT(
         'MAX(IF(pa.fieldname = ''',
          fieldname,
          ''', pa.fieldvalue, NULL)) AS ',
          fieldname
        ) as output
    FROM
        product_additional
) as temp;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Structure padding and packing

Are these structures padded or packed?

They're padded.

The only possibility that initially springs to mind, where they could be packed, is if char and int were the same size, so that the minimum size of the char/int/char structure would allow for no padding, ditto for the int/char structure.

However, that would require both sizeof(int) and sizeof(char) to be four (to get the twelve and eight sizes). The whole theory falls apart since it's guaranteed by the standard that sizeof(char) is always one.

Were char and int the same width, the sizes would be one and one, not four and four. So, in order to then get a size of twelve, there would have to be padding after the final field.


When does padding or packing take place?

Whenever the compiler implementation wants it to. Compilers are free to insert padding between fields, and following the final field (but not before the first field).

This is usually done for performance as some types perform better when they're aligned on specific boundaries. There are even some architectures that will refuse to function (i.e, crash) is you try to access unaligned data (yes, I'm looking at you, ARM).

You can generally control packing/padding (which is really opposite ends of the same spectrum) with implementation-specific features such as #pragma pack. Even if you cannot do that in your specific implementation, you can check your code at compile time to ensure it meets your requirement (using standard C features, not implementation-specific stuff).

For example:

// C11 or better ...
#include <assert.h>
struct strA { char a; int  b; char c; } x;
struct strB { int  b; char a;         } y;
static_assert(sizeof(struct strA) == sizeof(char)*2 + sizeof(int), "No padding allowed");
static_assert(sizeof(struct strB) == sizeof(char)   + sizeof(int), "No padding allowed");

Something like this will refuse to compile if there is any padding in those structures.

Build Error - missing required architecture i386 in file

I too got the same error am using xcode version 4.0.2 so what i did was selected the xcode project file and from their i selected the Target option their i could see the app of my project so i clicked on it and went to the build settings option.

Their in the search option i typed Framework search path, and deleted all the settings and then clicked the build button and that worked for me just fine,

Thanks and Regards

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Update: Using DateTimeFormat, introduced in java 8:

The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.

Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.

The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.

Here is the example code:

DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Original answer - with old API SimpleDateFormat

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018

Setting the height of a SELECT in IE

Yes, you can.

I was able to set the height of my SELECT to exactly what I wanted in IE8 and 9. The trick is to set the box-sizing property to content-box. Doing so will set the content area of the SELECT to the height, but keep in mind that margin, border and padding values will not be calculated in the width/height of the SELECT, so adjust those values accordingly.

select {
    display: block;
    padding: 6px 4px;
    -moz-box-sizing: content-box;
    -webkit-box-sizing:content-box;
    box-sizing:content-box;
    height: 15px;
}

Here is a working jsFiddle. Would you mind confirming and marking the appropriate answer?

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                String header = dataGridView1.Columns[i].HeaderText;
                //String cellText = row.Cells[i].Text;
                DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column 
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
                int colWidth = column.Width; // store columns width after auto resize           
                colWidth += 50; // add 30 pixels to what 'colWidth' already is
                this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
            }
        }

Creating and Update Laravel Eloquent

2020 Update

As in Laravel >= 5.3, if someone is still curious how to do so in easy way. Its possible by using : updateOrCreate().

For example for asked question you can use something like:

$matchThese = ['shopId'=>$theID,'metadataKey'=>2001];
ShopMeta::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Above code will check the table represented by ShopMeta, which will be most likely shop_metas unless not defined otherwise in model itself

and it will try to find entry with

column shopId = $theID

and

column metadateKey = 2001

and if it finds then it will update column shopOwner of found row to New One.

If it finds more than one matching rows then it will update the very first row that means which has lowest primary id.

If not found at all then it will insert a new row with :

shopId = $theID,metadateKey = 2001 and shopOwner = New One

Notice Check your model for $fillable and make sue that you have every column name defined there which you want to insert or update and rest columns have either default value or its id column auto incremented one.

Otherwise it will throw error when executing above example:

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field '...' doesn't have a default value (SQL: insert into `...` (`...`,.., `updated_at`, `created_at`) values (...,.., xxxx-xx-xx xx:xx:xx, xxxx-xx-xx xx:xx:xx))'

As there would be some field which will need value while inserting new row and it will not be possible as either its not defined in $fillable or it doesnt have default value.

For more reference please see Laravel Documentation at : https://laravel.com/docs/5.3/eloquent

One example from there is:

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

which pretty much clears everything.

Query Builder Update

Someone has asked if it is possible using Query Builder in Laravel. Here is reference for Query Builder from Laravel docs.

Query Builder works exactly the same as Eloquent so anything which is true for Eloquent is true for Query Builder as well. So for this specific case, just use the same function with your query builder like so:

$matchThese = array('shopId'=>$theID,'metadataKey'=>2001);
DB::table('shop_metas')::updateOrCreate($matchThese,['shopOwner'=>'New One']);

Of course, don't forget to add DB facade:

use Illuminate\Support\Facades\DB;

OR

use DB;

I hope it helps

How to limit the maximum files chosen when using multiple file input

On change of the input track how many files are selected:

_x000D_
_x000D_
$("#image").on("change", function() {_x000D_
    if ($("#image")[0].files.length > 2) {_x000D_
        alert("You can select only 2 images");_x000D_
    } else {_x000D_
        $("#imageUploadForm").submit();_x000D_
    }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<strong>On change of the input track how many files are selected:</strong>_x000D_
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >
_x000D_
_x000D_
_x000D_

Best way to clear a PHP array's values

The question is not really answered by the posts. Keeping the keys and clearing the values is the focus of the question.

foreach($resultMasterCleaned['header'] as $ekey => $eval) {
    $resultMasterCleaned[$key][$eval] = "";                 
}

As in the case of a two dimensional array holding CSV values and to blank out a particular row. Looping through seems the only way.

CSS table-cell equal width

Just using max-width: 0 in the display: table-cell element worked for me:

_x000D_
_x000D_
.table {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.table-cell {_x000D_
  display: table-cell;_x000D_
  max-width: 0px;_x000D_
  border: 1px solid gray;_x000D_
}
_x000D_
<div class="table">_x000D_
  <div class="table-cell">short</div>_x000D_
  <div class="table-cell">loooooong</div>_x000D_
  <div class="table-cell">Veeeeeeery loooooong</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use a Java8 lambda to sort a stream in reverse order?

Alternative way sharing:

ASC

List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName)).collect(Collectors.toList());

DESC

List<Animal> animals = this.service.findAll();
animals = animals.stream().sorted(Comparator.comparing(Animal::getName).reversed()).collect(Collectors.toList());

AngularJS - How to use $routeParams in generating the templateUrl?

Alright, think I got it...

Little background first: The reason I needed this was to stick Angular on top of Node Express and have Jade process my partials for me.

So here's whatchya gotta do... (drink beer and spend 20+ hours on it first!!!)...

When you set up your module, save the $routeProvider globally:

// app.js:
var routeProvider
    , app = angular.module('Isomorph', ['ngResource']).config(function($routeProvider){

        routeProvider = $routeProvider;
        $routeProvider
            .when('/', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/home', {templateUrl: '/', controller: 'AppCtrl'})
            .when('/login', {templateUrl: '/login', controller: 'AppCtrl'})
            .when('/SAMPLE', {templateUrl: '/SAMPLE', controller: 'SAMPLECtrl'})
            .when('/map', {templateUrl: '/map', controller: 'MapCtrl'})
            .when('/chat', {templateUrl: '/chat', controller: 'ChatCtrl'})
            .when('/blog', {templateUrl: '/blog', controller: 'BlogCtrl'})
            .when('/files', {templateUrl: '/files', controller: 'FilesCtrl'})
            .when('/tasks', {templateUrl: '/tasks', controller: 'TasksCtrl'})
            .when('/tasks/new', {templateUrl: '/tasks/new', controller: 'NewTaskCtrl'})
            .when('/tasks/:id', {templateUrl: '/tasks', controller: 'ViewTaskCtrl'})
            .when('/tasks/:id/edit', {templateUrl: '/tasks', controller: 'EditTaskCtrl'})
            .when('/tasks/:id/delete', {templateUrl: '/tasks', controller: 'DeleteTaskCtrl'})
        .otherwise({redirectTo: '/login'});

});

// ctrls.js
...
app.controller('EditTaskCtrl', function($scope, $routeParams, $location, $http){

    var idParam = $routeParams.id;
    routeProvider.when('/tasks/:id/edit/', {templateUrl: '/tasks/' + idParam + '/edit'});
    $location.path('/tasks/' + idParam + '/edit/');

});
...

That may be more info than what was needed...

  • Basically, you'll wanna store your Module's $routeProvider var globally, eg as routeProvider so that it can be accessed by your Controllers.

  • Then you can just use routeProvider and create a NEW route (you can't 'RESET a route' / 'REpromise'; you must create a new one), I just added a slash (/) at the end so that it is as semantic as the first.

  • Then (inside your Controller), set the templateUrl to the view you want to hit.

  • Take out the controller property of the .when() object, lest you get an infinite request loop.

  • And finally (still inside the Controller), use $location.path() to redirect to the route that was just created.

If you're interested in how to slap an Angular app onto an Express app, you can fork my repo here: https://github.com/cScarlson/isomorph.

And this method also allows for you to keep the AngularJS Bidirectional Data-Bindings in case you want to bind your HTML to your database using WebSockets: otherwise without this method, your Angular data-bindings will just output {{model.param}}.

If you clone this at this time, you'll need mongoDB on your machine to run it.

Hope this solves this issue!

Cody

Don't drink your bathwater.

Getting input values from text box

<script>
  function submit(){
      var userPass = document.getElementById('pass');
      var userName = document.getElementById('user');
      alert(user.value);
      alert(pass.value);
  }
</script>

<input type="text" id="user" />
<input type="text" id="pass" />
<button onclick="submit();" href="javascript:;">Submit</button>

How can I make a weak protocol reference in 'pure' Swift (without @objc)

protocol must be subClass of AnyObject, class

example given below

    protocol NameOfProtocol: class {
   // member of protocol
    }
   class ClassName: UIViewController {
      weak var delegate: NameOfProtocol? 
    }

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

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

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ˜ 9.5 hours). If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed.

MySQL suggests:

You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property autoReconnect=true to avoid this problem.

How to change MySQL timezone in a database connection using Java?

Is there a way we can get the list of supported timeZone from MySQL ? ex - serverTimezone=America/New_York. That can solve many such issue. I believe every time you need to specify the correct time zone from the Application irrespective of the DB TimeZone.

How to change XAMPP apache server port?

I had problem too. I switced Port but couldn't start on 8012.

Skype was involved becouse it had the same port - 80. And it couldn't let apache change it's port.

So just restart computer and Before turning on any other programs Open xampp first change port let's say from 80 to 8000 or 8012 on these lines in httpd.conf

Listen 80
ServerName localhost:80

Restart xampp, Start apache, check localhost.

Set formula to a range of cells

I would update the formula in C1. Then copy the formula from C1 and paste it till C10...

Not sure about a more elegant solution

Range("C1").Formula = "=A1+B1"
Range("C1").Copy
Range("C1:C10").Pastespecial(XlPasteall)

How to Define Callbacks in Android?

In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.

Just as a random example:

// The callback interface
interface MyCallback {
    void callbackCall();
}

// The class that takes the callback
class Worker {
   MyCallback callback;

   void onEvent() {
      callback.callbackCall();
   }
}

// Option 1:

class Callback implements MyCallback {
   void callbackCall() {
      // callback code goes here
   }
}

worker.callback = new Callback();

// Option 2:

worker.callback = new MyCallback() {

   void callbackCall() {
      // callback code goes here
   }
};

I probably messed up the syntax in option 2. It's early.

Can I use jQuery with Node.js?

The module jsdom is a great tool. But if you want to evaluate entire pages and do some funky stuff on them server side I suggest running them in their own context:

vm.runInContext

So things like require / CommonJS on site will not blow your Node process itself.

You can find documentation here. Cheers!

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Does the join order matter in SQL?

for regular Joins, it doesn't. TableA join TableB will produce the same execution plan as TableB join TableA (so your C and D examples would be the same)

for left and right joins it does. TableA left Join TableB is different than TableB left Join TableA, BUT its the same than TableB right Join TableA

equals vs Arrays.equals in Java

The equals() of arrays is inherited from Object, so it does not look at the contents of the arrrays, it only considers each array equal to itself.

The Arrays.equals() methods do compare the arrays' contents. There's overloads for all primitive types, and the one for objects uses the objects' own equals() methods.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

Delete newline in Vim

The problem is that multiples char 0A (\n) that are invisible may accumulate. Supose you want to clean up from line 100 to the end:

Typing ESC and : (terminal commander)

:110,$s/^\n//

In a vim script:

execute '110,$s/^\n//'

Explanation: from 110 till the end search for lines that start with new line (are blank) and remove them

How to import a CSS file in a React Component

In cases where you just want to inject some styles from a stylesheet into a component without bundling in the whole stylesheet I recommend https://github.com/glortho/styled-import. For example:

const btnStyle = styledImport.react('../App.css', '.button')

// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.

NOTE: I am the author of this lib, and I built it for cases where mass imports of styles and CSS modules are not the best or most viable solution.

In git how is fetch different than pull and how is merge different than rebase?

pull vs fetch:

The way I understand this, is that git pull is simply a git fetch followed by git merge. I.e. you fetch the changes from a remote branch and then merge it into the current branch.


merge vs rebase:

A merge will do as the command says; merge the differences between current branch and the specified branch (into the current branch). I.e. the command git merge another_branch will the merge another_branch into the current branch.

A rebase works a bit differently and is kind of cool. Let's say you perform the command git rebase another_branch. Git will first find the latest common version between the current branch and another_branch. I.e. the point before the branches diverged. Then git will move this divergent point to the head of the another_branch. Finally, all the commits in the current branch since the original divergent point are replayed from the new divergent point. This creates a very clean history, with fewer branches and merges.

However, it is not without pitfalls! Since the version history is "rewritten", you should only do this if the commits only exists in your local git repo. That is: Never do this if you have pushed the commits to a remote repo.

The explanation on rebasing given in this online book is quite good, with easy-to-understand illustrations.


pull with rebasing instead of merge

I'm actually using rebase quite a lot, but usually it is in combination with pull:

git pull --rebase

will fetch remote changes and then rebase instead of merge. I.e. it will replay all your local commits from the last time you performed a pull. I find this much cleaner than doing a normal pull with merging, which will create an extra commit with the merges.

Access iframe elements in JavaScript

this code worked for me:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');

How to declare a variable in a template in Angular

I am using angular 6x and I've ended up by using below snippet. I've a scenerio where I've to find user from a task object. it contains array of users but I've to pick assigned user.

<ng-container *ngTemplateOutlet="memberTemplate; context:{o: getAssignee(task) }">
</ng-container>
<ng-template #memberTemplate let-user="o">
  <ng-container *ngIf="user">
    <div class="d-flex flex-row-reverse">
      <span class="image-block">
        <ngx-avatar placement="left" ngbTooltip="{{user.firstName}} {{user.lastName}}" class="task-assigned" value="28%" [src]="user.googleId" size="32"></ngx-avatar>
      </span>
    </div>
  </ng-container>
</ng-template>

Maven project version inheritance - do I have to specify the parent version?

You could also use:

$ mvn release:update-versions -DdevelopmentVersion={version}

to update the version numbers in your POMs.

Array formula on Excel for Mac

This doesn't seem to work in Mac Excel 2016. After a bit of digging, it looks like the key combination for entering the array formula has changed from ?+RETURN to CTRL+SHIFT+RETURN.

vim - How to delete a large block of text without counting the lines?

You can also enter a very large number, and then press dd if you wish to delete all the lines below the cursor.

How to install Selenium WebDriver on Mac OS

Install

If you use homebrew (which I recommend), you can install selenium using:

brew install selenium-server-standalone

Running

updated -port port_number

To run selenium, do: selenium-server -port 4444

For more options: selenium-server -help

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

Referencing another schema in Mongoose

Late reply, but adding that Mongoose also has the concept of Subdocuments

With this syntax, you should be able to reference your userSchema as a type in your postSchema like so:

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var postSchema = new Schema({
    name: String,
    postedBy: userSchema,
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Note the updated postedBy field with type userSchema.

This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.

How to upgrade Angular CLI to the latest version

This command works fine:

npm upgrade -g @angular/cli

Counting no of rows returned by a select query

Try wrapping your entire select in brackets, then running a count(*) on that

select count(*)
from
(
   select m.id
   from Monitor as m 
    inner join Monitor_Request as mr 
       on mr.Company_ID=m.Company_id   group by m.Company_id
    having COUNT(m.Monitor_id)>=5
) myNewTable

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

As sklearn.cross_validation module was deprecated, you can use:

import numpy as np
from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5)

X_trn, X_tst, y_trn, y_tst = train_test_split(X, y, test_size=0.2, random_state=42)

How to get all selected values of a multiple select box?

Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:

selected = Array.prototype.filter.apply(
  select.options, [
    function(o) {
      return o.selected;
    }
  ]
);

It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.

Another approach would be using selectors:

selected = Array.prototype.map.apply(
    select.querySelectorAll('option[selected="selected"]'),
    [function (o) { return o.value; }]
);

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

How does String substring work in Swift

enter image description here

All of the following examples use

var str = "Hello, playground"

Swift 4

Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring type back rather than a String. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, then it has to be copied over. This is good for stability (no one else is going to change it without your knowledge) but bad for efficiency.

A Substring, on the other hand, is a reference back to the original String from which it came. Here is an image from the documentation illustrating that.

No copying is needed so it is much more efficient to use. However, imagine you got a ten character Substring from a million character String. Because the Substring is referencing the String, the system would have to hold on to the entire String for as long as the Substring is around. Thus, whenever you are done manipulating your Substring, convert it to a String.

let myString = String(mySubstring)

This will copy just the substring over and the memory holding old String can be reclaimed. Substrings (as a type) are meant to be short lived.

Another big improvement in Swift 4 is that Strings are Collections (again). That means that whatever you can do to a Collection, you can do to a String (use subscripts, iterate over the characters, filter, etc).

The following examples show how to get a substring in Swift.

Getting substrings

You can get a substring from a string by using subscripts or a number of other methods (for example, prefix, suffix, split). You still need to use String.Index and not an Int index for the range, though. (See my other answer if you need help with that.)

Beginning of a string

You can use a subscript (note the Swift 4 one-sided range):

let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str[..<index] // Hello

or prefix:

let index = str.index(str.startIndex, offsetBy: 5)
let mySubstring = str.prefix(upTo: index) // Hello

or even easier:

let mySubstring = str.prefix(5) // Hello

End of a string

Using subscripts:

let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str[index...] // playground

or suffix:

let index = str.index(str.endIndex, offsetBy: -10)
let mySubstring = str.suffix(from: index) // playground

or even easier:

let mySubstring = str.suffix(10) // playground

Note that when using the suffix(from: index) I had to count back from the end by using -10. That is not necessary when just using suffix(x), which just takes the last x characters of a String.

Range in a string

Again we simply use subscripts here.

let start = str.index(str.startIndex, offsetBy: 7)
let end = str.index(str.endIndex, offsetBy: -6)
let range = start..<end

let mySubstring = str[range]  // play

Converting Substring to String

Don't forget, when you are ready to save your substring, you should convert it to a String so that the old string's memory can be cleaned up.

let myString = String(mySubstring)

Using an Int index extension?

I'm hesitant to use an Int based index extension after reading the article Strings in Swift 3 by Airspeed Velocity and Ole Begemann. Although in Swift 4, Strings are collections, the Swift team purposely hasn't used Int indexes. It is still String.Index. This has to do with Swift Characters being composed of varying numbers of Unicode codepoints. The actual index has to be uniquely calculated for every string.

I have to say, I hope the Swift team finds a way to abstract away String.Index in the future. But until them I am choosing to use their API. It helps me to remember that String manipulations are not just simple Int index lookups.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.

Also, google sets in its response header an 'X-Frame-Options' of SAMEORIGIN.

Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.

So, the only option is to make the request from your server to see if you can display the site in your IFrame.

So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.

Opening a new tab to read a PDF file

Just use target on your tag <a>

<a href="newsletter_01.pdf" target="_blank">Read more</a>

The target attribute specifies where to open the link. Using "_blank" will make your browser to open a new window/tab.

You could also use target in many ways. See http://www.w3schools.com/tags/att_a_target.asp

How to find substring inside a string (or how to grep a variable)?

expr is used instead of [ rather than inside it, and variables are only expanded inside double quotes, so try this:

if expr match "$LIST" "$SOURCE"; then

But I'm not really clear what SOURCE is supposed to represent.

It looks like your code will read in a pattern from standard input, and exit if it matches a database alias, otherwise it will echo "ok". Is that what you want?

excel VBA run macro automatically whenever a cell is changed

Another option is

Private Sub Worksheet_Change(ByVal Target As Range)
    IF Target.Address = "$D$2" Then
        MsgBox("Cell D2 Has Changed.")
    End If
End Sub

I believe this uses fewer resources than Intersect, which will be helpful if your worksheet changes a lot.

How to specify the private SSH-key to use when executing shell command on Git?

Other people's suggestions about ~/.ssh/config are extra complicated. It can be as simple as:

Host github.com
  IdentityFile ~/.ssh/github_rsa

Import existing source code to GitHub

Here are some instructions on how to initiate a GitHub repository and then push code you've already created to it. The first set of instructions are directly from GitHub.

Source: https://help.github.com/articles/create-a-repo/

  1. In the upper-right corner of any page, click, and then click New repository.

  2. Create a short, memorable name for your repository. For example, "hello-world".

  3. Optionally, add a description of your repository. For example, "My first repository on GitHub."

  4. Choose between creating a public or private repository.

  5. Initialize this repository with a README.

  6. Create repository.

Congratulations! You've successfully created your first repository, and initialized it with a README file.

Now after these steps you will want to push the code on your local computer up to the repository you just created and you do this following these steps:

  1. git init (in the root folder where your code is located)

  2. git add -A (this will add all the files and folders in your directory to be committed)

  3. git commit -am "First Project commit"

  4. git remote add origin [email protected]:YourGithubName/your-repo-name.git (you'll find this address on the GitHub repository you just created under "ssh clone URL" on the main page)

  5. git push -u origin master

That's it. Your code will now be pushed up to GitHub. Now every time you want to keep pushing code that has changed just do.

  1. git commit -m "New changes"

  2. git push origin master (if master is the branch you are working on)

Autoreload of modules in IPython

For IPython version 3.1, 4.x, and 5.x

%load_ext autoreload
%autoreload 2

Then your module will be auto-reloaded by default. This is the doc:

File:       ...my/python/path/lib/python2.7/site-packages/IPython/extensions/autoreload.py

Docstring:
``autoreload`` is an IPython extension that reloads modules
automatically before executing the line of code typed.

This makes for example the following workflow possible:

.. sourcecode:: ipython

   In [1]: %load_ext autoreload

   In [2]: %autoreload 2

   In [3]: from foo import some_function

   In [4]: some_function()
   Out[4]: 42

   In [5]: # open foo.py in an editor and change some_function to return 43

   In [6]: some_function()
   Out[6]: 43

The module was reloaded without reloading it explicitly, and the
object imported with ``from foo import ...`` was also updated.

There is a trick: when you forget all of the above when using ipython, just try:

import autoreload
?autoreload
# Then you get all the above

bootstrap jquery show.bs.modal event won't fire

Add this:

$(document).ready(function(){
    $(document).on('shown.bs.modal','.modal', function () {
         // DO EVENTS
    });
});

Routing HTTP Error 404.0 0x80070002

My solution, after trying EVERYTHING:

Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.

My final settings that worked:

  • IIS 7.5, Win2k8r2 x64,
  • Integrated mode application pool
  • Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authentication mode="None"/>
    
      <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
      <httpRuntime requestPathInvalidCharacters=""/>
    
      <httpModules>
        <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
      </httpModules>
    </system.web>
      <system.webServer>
        <!-- Modules for IIS 7.0 Integrated mode -->
        <modules>
          <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
        </modules>
    
        <!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
        <validation validateIntegratedModeConfiguration="false" />
      </system.webServer>
    
  • Global.ashx: (only method of any note)

    void Application_Start(object sender, EventArgs e) {
        // Register routes...
        System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
              "{*message}",
            //the default value for the message
              new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
            //any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
              new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
              new TestRoute.Handlers.PassthroughRouteHandler()
           );
    
        System.Web.Routing.RouteTable.Routes.Add(echoRoute);
    }
    
  • PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:

    public class PassthroughRouteHandler : IRouteHandler {
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
            requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
            return null;
        }
    }
    

"Cannot GET /" with Connect on Node.js

You'll see the message Cannot GET / if you don't specify which page it is that you're trying to get, in other words if your URL is something like http://localhost:8180. Make sure you enter a page name, e.g. http://localhost:8180/index.html.

Plotting categorical data with pandas and matplotlib

like this :

df.groupby('colour').size().plot(kind='bar')

How to clear memory to prevent "out of memory error" in excel vba?

Found this thread looking for a solution to my problem. Mine required a different solution that I figured out that might be of use to others. My macro was deleting rows, shifting up, and copying rows to another worksheet. Memory usage was exploding to several gigs and causing "out of memory" after processing around only 4000 records. What solved it for me?

application.screenupdating = false

Added that at the beginning of my code (be sure to make it true again, at the end) I knew that would make it run faster, which it did.. but had no idea about the memory thing.

After making this small change the memory usage didn't exceed 135 mb. Why did that work? No idea really. But it's worth a shot and might apply to you.

Xcode couldn't find any provisioning profiles matching

You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.

Android Fragment handle back button press

You can use from getActionBar().setDisplayHomeAsUpEnabled() :

@Override
public void onBackStackChanged() {
    int backStackEntryCount = getFragmentManager().getBackStackEntryCount();

    if(backStackEntryCount > 0){
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }else{
        getActionBar().setDisplayHomeAsUpEnabled(false);
    }
}

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

When using SASS how can I import a file from a different directory?

If using Web Compiler in Visual Studio you can add the path to includePath in compilerconfig.json.defaults. Then there is no need for some number of ../ since the compiler will use includePath as a location to look for the import.

For example:

"includePath": "node_modules/foundation-sites/scss",

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

If you really need to go this way, then this is what you can do. There are probably better ways of doing it, but this is all that I have at the moment. I did no database calls, I just used dummy data. Please modify the code to fit in with your scenario. I used jQuery to populate the HTML table.

In my controller I have the an action method called GetEmployees that returns a JSON result with all the employees. This is where you would call your repository to return the users from a database:

public ActionResult GetEmployees()
{
     List<User> userList = new List<User>();

     User user1 = new User
     {
          Id = 1,
          FirstName = "First name 1",
          LastName = "Last name 1"
     };

     User user2 = new User
     {
          Id = 2,
          FirstName = "First name 2",
          LastName = "Last name 2"
     };

     userList.Add(user1);
     userList.Add(user2);

     return Json(userList, JsonRequestBehavior.AllowGet);
}

The User class looks like this:

public class User
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
}

In your view you could have the following:

<div id="users">
     <table></table>
</div>

<script>

     $(document).ready(function () {

          var url = '/Home/GetEmployees';

          $.getJSON(url, function (data) {

               $.each(data, function (key, val) {

                    var user = '<tr><td>' + val.FirstName + '</td></tr>';

                    $('#users table').append(user);

               });
          });
     });

</script>

Regarding the code above: var url = '/Home/GetEmployees'; Home is the controller and GetEmployees is the action method that you defined above.

I hope this helps.

UPDATE:

This is how I would have done it..

I always create a view model class for a view. In this case I would have called it something like UserListViewModel:

public class UserListViewModel
{
     IEnumerable<User> Users { get; set; }
}

In my controller I would populate this Users list from a call to the database returning all the users:

public ActionResult List()
{
     UserListViewModel viewModel = new UserListViewModel
     {
          Users = userRepository.GetAllUsers()
     };

     return View(viewModel);
}

And in my view I would have the following:

<table>

@foreach(User user in Model.Users)
{
     <tr>
          <td>First Name:</td>
          <td>user.FirstName</td>
     </tr>
}

</table>

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> namesList = Arrays.asList(names);

or

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> temp = Arrays.asList(names);         

Above Statement adds the wrapper on the input array. So the methods like add & remove will not be applicable on list reference object 'namesList'.

If you try to add an element in the existing array/list then you will get "Exception in thread "main" java.lang.UnsupportedOperationException".

The above operation is readonly or viewonly.
We can not perform add or remove operation in list object. But

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.ArrayList<String> list1 = new ArrayList<>(Arrays.asList(names));

or

String names[] = new String[]{"Avinash","Amol","John","Peter"};
java.util.List<String> listObject = Arrays.asList(names);
java.util.ArrayList<String> list1 = new ArrayList<>(listObject);

In above statement you have created a concrete instance of an ArrayList class and passed a list as a parameter.

In this case method add & remove will work properly as both methods are from ArrayList class so here we won't get any UnSupportedOperationException.
Changes made in Arraylist object (method add or remove an element in/from an arraylist) will get not reflect in to original java.util.List object.

String names[] = new String[] {
    "Avinash",
    "Amol",
    "John",
    "Peter"
};

java.util.List < String > listObject = Arrays.asList(names);
java.util.ArrayList < String > list1 = new ArrayList < > (listObject);
for (String string: list1) {
    System.out.print("   " + string);
}
list1.add("Alex"); //Added without any exception
list1.remove("Avinash"); //Added without any exception will not make any changes in original list in this case temp object.


for (String string: list1) {
    System.out.print("   " + string);
}
String existingNames[] = new String[] {
    "Avinash",
    "Amol",
    "John",
    "Peter"
};
java.util.List < String > namesList = Arrays.asList(names);
namesList.add("Bob"); // UnsupportedOperationException occur
namesList.remove("Avinash"); //UnsupportedOperationException

Removing index column in pandas when reading a csv

you can specify which column is an index in your csv file by using index_col parameter of from_csv function if this doesn't solve you problem please provide example of your data

Get installed applications in a system

My requirement is to check if specific software is installed in my system. This solution works as expected. It might help you. I used a windows application in c# with visual studio 2015.

 private void Form1_Load(object sender, EventArgs e)
        {

            object line;
            string softwareinstallpath = string.Empty;
            string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            using (var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
            {
                using (var key = baseKey.OpenSubKey(registry_key))
                {
                    foreach (string subkey_name in key.GetSubKeyNames())
                    {
                        using (var subKey = key.OpenSubKey(subkey_name))
                        {
                            line = subKey.GetValue("DisplayName");
                            if (line != null && (line.ToString().ToUpper().Contains("SPARK")))
                            {

                                softwareinstallpath = subKey.GetValue("InstallLocation").ToString();
                                listBox1.Items.Add(subKey.GetValue("InstallLocation"));
                                break;
                            }
                        }
                    }
                }
            }

            if(softwareinstallpath.Equals(string.Empty))
            {
                MessageBox.Show("The Mirth connect software not installed in this system.")
            }



            string targetPath = softwareinstallpath + @"\custom-lib\";
            string[] files = System.IO.Directory.GetFiles(@"D:\BaseFiles");

            // Copy the files and overwrite destination files if they already exist. 
            foreach (var item in files)
            {
                string srcfilepath = item;
                string fileName = System.IO.Path.GetFileName(item);
                System.IO.File.Copy(srcfilepath, targetPath + fileName, true);
            }
            return;

        }

Set Windows process (or user) memory limit

Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.

Angular.js programmatically setting a form field to dirty

Small additional note to @rmag's answer. If you have empty but required fields that you want to make dirty use this:

$scope.myForm.username.$setViewValue($scope.myForm.username.$viewValue !== undefined 
    ? $scope.myForm.username.$viewValue : '');

Substring in VBA

Shorter:

   Split(stringval,":")(0)

List of all users that can connect via SSH

Read man sshd_config for more details, but you can use the AllowUsers directive in /etc/ssh/sshd_config to limit the set of users who can login.

e.g.

AllowUsers boris

would mean that only the boris user could login via ssh.

Multiple glibc libraries on a single host

If you look closely at the second output you can see that the new location for the libraries is used. Maybe there are still missing libraries that are part of the glibc.

I also think that all the libraries used by your program should be compiled against that version of glibc. If you have access to the source code of the program, a fresh compilation appears to be the best solution.

How to reduce the image size without losing quality in PHP

If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

Change the color of a checked menu item in a navigation drawer

Here's how you can do it in your Activity's onCreate method:

NavigationView navigationView = findViewById(R.id.nav_view);
ColorStateList csl = new ColorStateList(
    new int[][] {
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_checked}  // checked
    },
    new int[] {
        Color.BLACK,
        Color.RED
    }
);
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl);

How to style readonly attribute with CSS?

If you select the input by the id and then add the input[readonly="readonly"] tag in the css, something like:

 #inputID input[readonly="readonly"] {
     background-color: #000000;
 }

That will not work. You have to select a parent class or id an then the input. Something like:

 .parentClass, #parentID input[readonly="readonly"] {
     background-color: #000000;
 }

My 2 cents while waiting for new tickets at work :D

Find nearest value in numpy array

If you don't want to use numpy this will do it:

def find_nearest(array, value):
    n = [abs(i-value) for i in array]
    idx = n.index(min(n))
    return array[idx]

Windows.history.back() + location.reload() jquery

window.history.back() does not support reload or refresh of the page. But you can use following if you are okay with an extra refresh

window.history.back()
window.location.reload()

However a real complete solution would be as follows: I wrote a service to keep track of previous page and then navigate to that page with reload:true

Here is how i did it.

'use strict';

angular.module('tryme5App')
    .factory('RouterTracker', function RouterTracker($rootScope) {
          var routeHistory = [];
          var service = {
            getRouteHistory: getRouteHistory
          };

          $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
              routeHistory = [];
              routeHistory.push({route: from, routeParams: fromParams});
          });

          function getRouteHistory() {
            return routeHistory;
          }

          return service;       
    });

Make sure you have included this js file from you index.html

<script src="scripts/components/util/route.service.js"></script>

Now from you stateprovider or controller you can access this service and navigate

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
$state.go(routeHistory[0].route.name, null, { reload: true });

or alternatively even perform checks and conditional routing

var routeHistory = RouterTracker.getRouteHistory();    
console.log(routeHistory[0].route.name)
if(routeHistory[0].route.name == 'seat') {
      $state.go('seat', null, { reload: true });
} else {
      window.history.back()
}

Make sure you have added RouterTracker as an argument in your function in my case it was :

.state('seat.new', {
                parent: 'seat',
                url: '/new',
                data: {
                    authorities: ['ROLE_USER'],
                },
                onEnter: ['$stateParams', '$state', '$uibModal', 'RouterTracker', function($stateParams, $state, $uibModal, RouterTracker) {
  $uibModal.open({
      //....Open dialog.....
 }).result.then(function(result) {
            var routeHistory = RouterTracker.getRouteHistory();    
            console.log(routeHistory[0].route.name)
            $state.go(routeHistory[0].route.name, null, { reload: true });
 }, function() {
                    $state.go('^');
 })

How to make an AlertDialog in Flutter?

Or you can use RFlutter Alert library for that. It is easily customizable and easy-to-use. Its default style includes rounded corners and you can add buttons as much as you want.

Basic Alert:

Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();

Alert with Button:

Alert(
    context: context,
    type: AlertType.error,
    title: "RFLUTTER ALERT",
    desc: "Flutter is more awesome with RFlutter Alert.",
    buttons: [
    DialogButton(
        child: Text(
        "COOL",
        style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        onPressed: () => Navigator.pop(context),
        width: 120,
    )
    ],
).show();

You can also define generic alert styles.

*I'm one of developer of RFlutter Alert.

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

UPDATE 20200825:

Added below "Conclusion" paragraph

I've went down the pipenv rabbit hole (it's a deep and dark hole indeed...) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I've found.

DISCLAIMER:

This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It's about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.

venv

As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: "Changed in version 3.5: The use of venv is now recommended for creating virtual environments".

pipenv

pipenv- like venv - can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt, pipenv delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile is to supplant requirements.txt.

HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.

Conflicting Standards:

So if settling on a virtual envelope solution wasn't difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.

Conflict Resolution:

The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:

prefer built-in venv: if the target python has venv we'll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)

Conclusion:

So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv- which uses virtualenv - varies materially from venv.

Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.

Update 20200825:

An oft repeated criticism of Pipenv I saw when producing this analysis was that it was not actively maintained. Indeed, what's the point of using a solution whose future could be seen questionable due to lack of continuous development? After a dry spell of about 18 months, Pipenv is once again being actively developed. Indeed, large and material updates have since been released.

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

Unix's 'ls' sort by name

NOTICE: "a" comes AFTER "Z":

$ touch A.txt aa.txt Z.txt

$ ls

A.txt Z.txt aa.txt

How to make Bootstrap Panel body with fixed height

HTML :

<div class="span4">
  <div class="panel panel-primary">
    <div class="panel-heading">jhdsahfjhdfhs</div>
    <div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
  </div>
</div>

CSS :

.panel-height {
  height: 100px; / change according to your requirement/
}

Convert HTML Character Back to Text Using Java Standard Library

As @jem suggested, it is possible to use jsoup.

With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.

import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);

It seems that in some previous release this method is not present.

__init__() missing 1 required positional argument

The problem is with, you

def __init__(self, data):

when you create object from DHT class you should pass parameter the data should be dict type, like

data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)

But in your code youshould to change is

data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()

Or

if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()

how to use font awesome in own css?

Instructions for Drupal 8 / FontAwesome 5

Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)

Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}
?>

Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.

Make sure you import FontAwesome, add this at the top of the CSS file

@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

then add this in the CSS

input#edit-submit {
    font-family: 'Font Awesome\ 5 Free';
    background-color: transparent;
    border: 0;  
}

FLUSH ALL CACHES AND IT SHOULD WORK FINE

Add Google Font Effects

If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');

Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta

<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
  $form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>

LD_LIBRARY_PATH vs LIBRARY_PATH

LIBRARY_PATH is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.

LD_LIBRARY_PATH is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.

EDIT: As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH comes into play.

How to connect to Oracle 11g database remotely

You will need to run the lsnrctl utility on server A to start the listener. You would then connect from computer B using the following syntax:

sqlplus username/password@hostA:1521 /XE

The port information is optional if the default of 1521 is used.

Listener configuration documentation here. Remote connection documentation here.

Store List to session

Yes, you can store any object (I assume you are using ASP.NET with default settings, which is in-process session state):

Session["test"] = myList;

You should cast it back to the original type for use:

var list = (List<int>)Session["test"];
// list.Add(something);

As Richard points out, you should take extra care if you are using other session state modes (e.g. SQL Server) that require objects to be serializable.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

The hibernate.* properties are useless, they should be spring.jpa.* properties. Not to mention that you are trying to override those already set by using the spring.jpa.* properties. (For the explanation of each property I strongly suggest a read of the Spring Boot reference guide.

spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true

# Hibernate
spring.jpa.hibernate.ddl-auto=update

Also the packages to scan are automatically detected based on the base package of your Application class. If you want to specify something else use the @EntityScan annotation. Also specifying the most toplevel package isn't really wise as it will scan the whole class path which will severely impact performance.

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

In my situation MSSQLSERVER service had a problem so I restarted the service and problem solved.

So I recommend to go to Services app by : Windows key, search "Services", then find your Sql instance usually "SQL Server (MSSQLSERVER)" at for Microsoft sql server. Right click on service and click on Start, if disabled click on Restart.

displaying a string on the textview when clicking a button in android

This is because you DON'T associated the OnClickListener() on the button retrieve from the XML layout.

You don't need to create object because they are already created by the Android system when you inflate XML file (with the Activity.setContentLayout( int resourceLayoutId ) method).

Just retrieve them with the findViewById(...) method.

How to reset form body in bootstrap modal box?

You can make a JavaScript function to do that:

$.clearInput = function () {
        $('form').find('input[type=text], input[type=password], input[type=number], input[type=email], textarea').val('');
};

and then you can call that function each time your modal is hidden:

$('#Your_Modal').on('hidden', function () {
        $.clearInput();
});

When to use malloc for char pointers

Everytime the size of the string is undetermined at compile time you have to allocate memory with malloc (or some equiviallent method). In your case you know the size of your strings at compile time (sizeof("something") and sizeof("something else")).

What is SOA "in plain english"?

Service Oriented Architecture (SOA) is a software architectural style that builds applications as a collection of pluggable parts, each of which can be reused by other applications.

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

When saving, how can you check if a field has changed?

I had this situation before my solution was to override the pre_save() method of the target field class it will be called only if the field has been changed
useful with FileField example:

class PDFField(FileField):
    def pre_save(self, model_instance, add):
        # do some operations on your file 
        # if and only if you have changed the filefield

disadvantage:
not useful if you want to do any (post_save) operation like using the created object in some job (if certain field has changed)

Make xargs handle filenames that contain spaces

xargs on MacOS doesn't have -d option, so this solution uses -0 instead.

Get ls to output one file per line, then translate newlines into nulls and tell xargs to use nulls as the delimiter:

ls -1 *mp3 | tr "\n" "\0" | xargs -0 mplayer

what is difference between success and .done() method of $.ajax

success is the callback that is invoked when the request is successful and is part of the $.ajax call. done is actually part of the jqXHR object returned by $.ajax(), and replaces success in jQuery 1.8.

How to reload the current route with the angular 2 router

I am using setTimeout and navigationByUrl to solve this issue... And it is working fine for me.

It is redirected to other URL and instead comes again in the current URL...

 setTimeout(() => {
     this.router.navigateByUrl('/dashboard', {skipLocationChange: false}).then(() =>
           this.router.navigate([route]));
     }, 500)

Android emulator doesn't take keyboard input - SDK tools rev 20

Confirmed. I had the same problem after upgrading to Tools version 20. I had to Edit the AVD to add an option as follows:

  1. From Eclipse, Go to AVD Mananger.
  2. Select the particular AVD and click on Edit
  3. Go to the Hardware section, click on New.
  4. Select the Property Name : Keyboard Support
  5. By default, it is added with a value of 'no'. Just click on the value column and change it to 'yes'.
  6. Click on Edit AVD again.

This will add a property hw.keyboard=yes in config.ini file for the AVD.

You also have to set hw.mainKeys = yes

Compare two objects with .equals() and == operator

the return type of object.equals is already boolean. there's no need to wrap it in a method with branches. so if you want to compare 2 objects simply compare them:

boolean b = objectA.equals(objectB);

b is already either true or false.

How do I find all files containing specific text on Linux?

There's a new utility called The Silversearcher

sudo apt install silversearcher-ag

It works closely with Git and other VCS. So you won't get anything in a .git or another directory.

You can simply use

ag "Search query"

And it will do the task for you!

Safely limiting Ansible playbooks to a single machine?

I would suggest using --limit <hostname or ip>

How to create correct JSONArray in Java using JSONObject

I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.

String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);

Hope this helps :)

Warning: Failed propType: Invalid prop `component` supplied to `Route`

It's a syntax issue related to imports/exports in your files, mine resolved by removing an extra quote from my import

<Route path={`${match.path}/iso-line-number`} component={ISOLineNumber} />

export html table to csv

Should work on every modern browser and without jQuery or any dependency, here my implementation :

// Quick and simple export target #table_id into a csv
function download_table_as_csv(table_id, separator = ',') {
    // Select rows from table_id
    var rows = document.querySelectorAll('table#' + table_id + ' tr');
    // Construct csv
    var csv = [];
    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll('td, th');
        for (var j = 0; j < cols.length; j++) {
            // Clean innertext to remove multiple spaces and jumpline (break csv)
            var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
            // Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv)
            data = data.replace(/"/g, '""');
            // Push escaped string
            row.push('"' + data + '"');
        }
        csv.push(row.join(separator));
    }
    var csv_string = csv.join('\n');
    // Download it
    var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv';
    var link = document.createElement('a');
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

Then add your download button/link :

<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a>

CSV file is timedated and compatible with default Excel format.

Update after comments: Added second parameter "separator", it can be used to configure another character like ;, it's useful if you have user downloading your csv in different region of the world because they can use another default separator for Excel, for more information see : https://superuser.com/a/606274/908273

Downloading images with node.js

You can use Axios (a promise-based HTTP client for Node.js) to download images in the order of your choosing in an asynchronous environment:

npm i axios

Then, you can use the following basic example to begin downloading images:

const fs = require('fs');
const axios = require('axios');

/* ============================================================
  Function: Download Image
============================================================ */

const download_image = (url, image_path) =>
  axios({
    url,
    responseType: 'stream',
  }).then(
    response =>
      new Promise((resolve, reject) => {
        response.data
          .pipe(fs.createWriteStream(image_path))
          .on('finish', () => resolve())
          .on('error', e => reject(e));
      }),
  );

/* ============================================================
  Download Images in Order
============================================================ */

(async () => {
  let example_image_1 = await download_image('https://example.com/test-1.png', 'example-1.png');

  console.log(example_image_1.status); // true
  console.log(example_image_1.error); // ''

  let example_image_2 = await download_image('https://example.com/does-not-exist.png', 'example-2.png');

  console.log(example_image_2.status); // false
  console.log(example_image_2.error); // 'Error: Request failed with status code 404'

  let example_image_3 = await download_image('https://example.com/test-3.png', 'example-3.png');

  console.log(example_image_3.status); // true
  console.log(example_image_3.error); // ''
})();

C++ alignment when printing cout <<

See also: Which C I/O library should be used in C++ code?

struct Item
{
   std::string     artist;
   std::string     c;
   integer         price;  // in cents (as floating point is not acurate)
   std::string     Genre;
   integer         disc;
   integer         sale;
   integer         tax;
};

std::cout << "Sales Report for September 15, 2010\n"
          << "Artist  Title   Price   Genre   Disc    Sale    Tax Cash\n";
FOREACH(Item loop,data)
{
    fprintf(stdout,"%8s%8s%8.2f%7s%1s%8.2f%8.2f\n",
          , loop.artist
          , loop.title
          , loop.price / 100.0
          , loop.Genre
          , loop.disc , "%"
          , loop.sale / 100.0
          , loop.tax / 100.0);

   // or

    std::cout << std::setw(8) << loop.artist
              << std::setw(8) << loop.title
              << std::setw(8) << fixed << setprecision(2) << loop.price / 100.0
              << std::setw(8) << loop.Genre
              << std::setw(7) << loop.disc << std::setw(1) << "%"
              << std::setw(8) << fixed << setprecision(2) << loop.sale / 100.0
              << std::setw(8) << fixed << setprecision(2) << loop.tax / 100.0
              << "\n";

    // or

    std::cout << boost::format("%8s%8s%8.2f%7s%1s%8.2f%8.2f\n")
              % loop.artist
              % loop.title
              % loop.price / 100.0
              % loop.Genre
              % loop.disc % "%"
              % loop.sale / 100.0
              % loop.tax / 100.0;
}

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Put your prompt in the 1st option and disable it:

<selection>
    <option disabled selected>”Select a language”</option>
    <option>English</option>
    <option>Spanish</option>
</selection>

The first option will automatically be the selected default (what you see first when you look at the drop-down) but adding the selected attribute is more clear and actually needed when the first field is a disabled field.

The disabled attribute will make the option be un-selectable/grayed out.


Other answers suggest setting disabled=“disabled” but that’s only necessary if you need to parse as XHTML, which is basically a more strict version of HTML. disabled on it’s on is enough for standard HTML.


If you want to make the selection “required” (without accepting the “Select a language” option as an accepted answer):

Add the required attribute to selection and set the first option’s value to the empty string ””.

<selection required>
    <option disabled value=“”>Select a language</option>
    <option>English</option>
    <option>Spanish</option>
</selection>

Programmatically go back to the previous fragment in the backstack

When we are updating/add the fragments,

Should Include the .addToBackStack().

getSupportFragmentManager().beginTransaction()
    .add(detailFragment, "detail") // Add this transaction to the back stack (name is an optional name for this back stack state, or null).
    .addToBackStack(null)
    .commit();

After that if we give the getFragments.popBackStackImmediate() will return true if we add/update the fragments, and move back to the current screen.

Whoops, looks like something went wrong. Laravel 5.0

Go to project directory then follow below steps.

step 1: rename file .env.example `to .env

mv .env.example .env (for linux)

step 2: php artisan key:generate

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I know this isn't adding much to the conversation at this point but I'm running a file generation procedure and its going incredibly slow. I've been using replicate and saw this trim method and figured I'd give it a shot.

You can see in my code where the switch between the two is in addition to the new @padding variable (and the limitation that now exists). I ran my procedure with the function in both states with the same results in execution time. So at least in SQLServer2016, I'm not seeing any difference in efficiency that other found.

Anyways, here's my UDF that I wrote years ago plus the changes today which is much the same as other's other than it has a LEFT/RIGHT param option and some error checking.

CREATE FUNCTION PadStringTrim 
(
    @inputStr varchar(500), 
    @finalLength int, 
    @padChar varchar (1),
    @padSide varchar(1)
)
RETURNS VARCHAR(500)

AS BEGIN
    -- the point of this function is to avoid using replicate which is extremely slow in SQL Server
    -- to get away from this though we now have a limitation of how much padding we can add, so I've settled on a hundred character pad 
    DECLARE @padding VARCHAR (100) = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    SET @padding = REPLACE(@padding, 'X', @padChar)


    SET @inputStr = RTRIM(LTRIM(@inputStr))

    IF LEN(@inputStr) > @finalLength 
        RETURN '!ERROR!' -- can search for ! in the returned text 

    ELSE IF(@finalLength > LEN(@inputStr))
        IF @padSide = 'L'
            SET @inputStr = RIGHT(@padding + @inputStr, @finalLength)
            --SET @inputStr = REPLICATE(@padChar, @finalLength - LEN(@inputStr)) + @inputStr
        ELSE IF @padSide = 'R'
            SET @inputStr = LEFT(@inputStr + @padding, @finalLength)
            --SET @inputStr = @inputStr + REPLICATE(@padChar, @finalLength - LEN(@inputStr)) 



    -- if LEN(@inputStr) = @finalLength we just return it 
    RETURN @inputStr;
END

-- SELECT  dbo.PadStringTrim( tblAccounts.account, 20, '~' , 'R' ) from tblAccounts
-- SELECT  dbo.PadStringTrim( tblAccounts.account, 20, '~' , 'L' ) from tblAccounts

How can I get the count of milliseconds since midnight for the current?

Do you mean?

long millis = System.currentTimeMillis() % 1000;

BTW Windows doesn't allow timetravel to 1969

C:\> date
Enter the new date: (dd-mm-yy) 2/8/1969
The system cannot accept the date entered.

Is there a PowerShell "string does not contain" cmdlet or syntax?

If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:

Get-Content $FileName | foreach-object { `
   if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }

or better (IMO)

Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}

set div height using jquery (stretch div height)

The correct way to do this is with good-old CSS:

#content{
    width:100%;
    position:absolute;
    top:35px;
    bottom:35px;
}

And the bonus is that you don't need to attach to the window.onresize event! Everything will adjust as the document reflows. All for the low-low price of four lines of CSS!

MySQL root access from all hosts

MariaDB running on Raspbian - the file containing bind-address is hard to pinpoint. MariaDB have some not-very-helpful-info on the subject.

I used

# sudo grep -R bind-address /etc 

to locate where the damn thing is.

I also had to set the privileges and hosts in the mysql like everyone above pointed out.

And also had some fun time opening the 3306 port for remote connections to my Raspberry Pi - finally used iptables-persistent.

All works great now.

Pass parameters in setInterval function

By far the most practical answer is the one given by tvanfosson, all i can do is give you an updated version with ES6:

setInterval( ()=>{ funca(10,3); }, 500);

How do I convert strings in a Pandas data frame to a 'date' data type?

For the sake of completeness, another option, which might not be the most straightforward one, a bit similar to the one proposed by @SSS, but using rather the datetime library is:

import datetime
df["Date"] = df["Date"].apply(lambda x: datetime.datetime.strptime(x, '%Y-%d-%m').date())

How to convert timestamp to datetime in MySQL?

SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me

How to list all Git tags?

For a GUI to do this I have just found that 'gitk' supports named views. The views have several options for selecting commits. One handy one is a box for selecting "All tags". That seems to work for me to see the tags.

Use of alloc init instead of new

For a side note, I personally use [Foo new] if I want something in init to be done without using it's return value anywhere. If you do not use the return of [[Foo alloc] init] anywhere then you will get a warning. More or less, I use [Foo new] for eye candy.

nginx: send all requests to a single html page

Your original rewrite should almost work. I'm not sure why it would be redirecting, but I think what you really want is just

rewrite ^ /base.html break;

You should be able to put that in a location or directly in the server.

What does [STAThread] do?

It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.

This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).

Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.

How do I remove a library from the arduino environment?

The answer is only valid if you have not changed the "Sketchbook Location" field in Preferences. So, first, you need to open the Arduino IDE and go to the menu

"File -> Preferences"

In the dialog, look at the field "Sketchbook Location" and open the corresponding folder. The "libraries" folder in inside.

Capture Image from Camera and Display in Activity

You need to read up about the Camera. (I think to do what you want, you'd have to save the current image to your app, do the select/delete there, and then recall the camera to try again, rather than doing the retry directly inside the camera.)

How to decompile a whole Jar file?

If you happen to have both a bash shell and jad:

JAR=(your jar file name)
unzip -d $JAR.tmp $JAR
pushd $JAR.tmp
for f in `find . -name '*.class'`; do
    jad -d $(dirname $f) -s java -lnc $f
done
popd

I might be a tiny, tiny bit off with that, but it should work more or less as advertised. You should end up with $JAR.tmp containing your decompiled files.

Pointers in JavaScript?

Late answer but I have come across a way of passing primitive values by reference by means of closures. It is rather complicated to create a pointer, but it works.

function ptr(get, set) {
    return { get: get, set: set };
}

function helloWorld(namePtr) {
    console.log(namePtr.get());
    namePtr.set('jack');
    console.log(namePtr.get())
}

var myName = 'joe';
var myNamePtr = ptr(
    function () { return myName; },
    function (value) { myName = value; }
);

helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack

In ES6, the code can be shortened to use lambda expressions:

var myName = 'joe';
var myNamePtr = ptr(=> myName, v => myName = v);

helloWorld(myNamePtr); // joe, jack
console.log(myName); // jack

How do I push amended commit to the remote Git repository?

I had the same problem.

  • Accidentally amended the last commit that was already pushed
  • Done a lot of changes locally, committed some five times
  • Tried to push, got an error, panicked, merged remote, got a lot of not-my-files, pushed, failed, etc.

As a Git-newbie, I thought it was complete FUBAR.

Solution: Somewhat like @bara suggested + created a local backup branch

# Rewind to commit just before the pushed-and-amended one.
# Replace <hash> with the needed hash.
# --soft means: leave all the changes there, so nothing is lost.
git reset --soft <hash>

# Create new branch, just for a backup, still having all changes in it.
# The branch was feature/1234, new one - feature/1234-gone-bad
git checkout -b feature/1234-gone-bad

# Commit all the changes (all the mess) not to lose it & not to carry around
git commit -a -m "feature/1234 backup"

# Switch back to the original branch
git checkout feature/1234

# Pull the from remote (named 'origin'), thus 'repairing' our main problem
git pull origin/feature/1234

# Now you have a clean-and-non-diverged branch and a backup of the local changes.
# Check the needed files from the backup branch
git checkout feature/1234-gone-bad -- the/path/to/file.php

Maybe it's not a fast and clean solution, and I lost my history (1 commit instead of 5), but it saved a day's work.

Is it possible to serialize and deserialize a class in C++?

I recommend using boost serialization as described by other posters. Here is a good detailed tutorial on how to use it which complements the boost tutorials nicely: http://www.ocoudert.com/blog/2011/07/09/a-practical-guide-to-c-serialization/

Spring Boot - How to log all requests and responses with exceptions in single place?

In order to log requests that result in 400 only:

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.AbstractRequestLoggingFilter;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.WebUtils;

/**
 * Implementation is partially copied from {@link AbstractRequestLoggingFilter} and modified to output request information only if request resulted in 400.
 * Unfortunately {@link AbstractRequestLoggingFilter} is not smart enough to expose {@link HttpServletResponse} value in afterRequest() method.
 */
@Component
public class RequestLoggingFilter extends OncePerRequestFilter {

    public static final String DEFAULT_AFTER_MESSAGE_PREFIX = "After request [";

    public static final String DEFAULT_AFTER_MESSAGE_SUFFIX = "]";

    private final boolean includeQueryString = true;
    private final boolean includeClientInfo = true;
    private final boolean includeHeaders = true;
    private final boolean includePayload = true;

    private final int maxPayloadLength = (int) (2 * FileUtils.ONE_MB);

    private final String afterMessagePrefix = DEFAULT_AFTER_MESSAGE_PREFIX;

    private final String afterMessageSuffix = DEFAULT_AFTER_MESSAGE_SUFFIX;

    /**
     * The default value is "false" so that the filter may log a "before" message
     * at the start of request processing and an "after" message at the end from
     * when the last asynchronously dispatched thread is exiting.
     */
    @Override
    protected boolean shouldNotFilterAsyncDispatch() {
        return false;
    }

    @Override
    protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain)
            throws ServletException, IOException {

        final boolean isFirstRequest = !isAsyncDispatch(request);
        HttpServletRequest requestToUse = request;

        if (includePayload && isFirstRequest && !(request instanceof ContentCachingRequestWrapper)) {
            requestToUse = new ContentCachingRequestWrapper(request, maxPayloadLength);
        }

        final boolean shouldLog = shouldLog(requestToUse);

        try {
            filterChain.doFilter(requestToUse, response);
        } finally {
            if (shouldLog && !isAsyncStarted(requestToUse)) {
                afterRequest(requestToUse, response, getAfterMessage(requestToUse));
            }
        }
    }

    private String getAfterMessage(final HttpServletRequest request) {
        return createMessage(request, this.afterMessagePrefix, this.afterMessageSuffix);
    }

    private String createMessage(final HttpServletRequest request, final String prefix, final String suffix) {
        final StringBuilder msg = new StringBuilder();
        msg.append(prefix);
        msg.append("uri=").append(request.getRequestURI());

        if (includeQueryString) {
            final String queryString = request.getQueryString();
            if (queryString != null) {
                msg.append('?').append(queryString);
            }
        }

        if (includeClientInfo) {
            final String client = request.getRemoteAddr();
            if (StringUtils.hasLength(client)) {
                msg.append(";client=").append(client);
            }
            final HttpSession session = request.getSession(false);
            if (session != null) {
                msg.append(";session=").append(session.getId());
            }
            final String user = request.getRemoteUser();
            if (user != null) {
                msg.append(";user=").append(user);
            }
        }

        if (includeHeaders) {
            msg.append(";headers=").append(new ServletServerHttpRequest(request).getHeaders());
        }

        if (includeHeaders) {
            final ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
            if (wrapper != null) {
                final byte[] buf = wrapper.getContentAsByteArray();
                if (buf.length > 0) {
                    final int length = Math.min(buf.length, maxPayloadLength);
                    String payload;
                    try {
                        payload = new String(buf, 0, length, wrapper.getCharacterEncoding());
                    } catch (final UnsupportedEncodingException ex) {
                        payload = "[unknown]";
                    }
                    msg.append(";payload=").append(payload);
                }
            }
        }
        msg.append(suffix);
        return msg.toString();
    }

    private boolean shouldLog(final HttpServletRequest request) {
        return true;
    }

    private void afterRequest(final HttpServletRequest request, final HttpServletResponse response, final String message) {
        if (response.getStatus() == HttpStatus.BAD_REQUEST.value()) {
            logger.warn(message);
        }
    }

}

Invalid application of sizeof to incomplete type with a struct

The cause of errors such as "Invalid application of sizeof to incomplete type with a struct ... " is always lack of an include statement. Try to find the right library to include.

How to call Stored Procedures with EntityFramework?

This is an example of querying MySQL procedure using Entity Framework

This is the definition of my Stored Procedure in MySQL:

CREATE PROCEDURE GetUpdatedAds (
    IN curChangeTracker BIGINT
    IN PageSize INT
) 
BEGIN
   -- select some recored...
END;

And this is how I query it using Entity Framework:

 var curChangeTracker = new SqlParameter("@curChangeTracker", MySqlDbType.Int64).Value = 0;
 var pageSize = new SqlParameter("@PageSize", (MySqlDbType.Int64)).Value = 100;

 var res = _context.Database.SqlQuery<MyEntityType>($"call GetUpdatedAds({curChangeTracker}, {pageSize})");

Note that I am using C# String Interpolation to build my Query String.

Uncaught ReferenceError: $ is not defined error in jQuery

The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.

BOTTOM PART OF _Layout.cshtml:

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

</body>
</html>

I moved them above the @RenderBody() and all was fine.

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

</body>
</html>

How to throw std::exceptions with variable messages?

Here is my solution:

#include <stdexcept>
#include <sstream>

class Formatter
{
public:
    Formatter() {}
    ~Formatter() {}

    template <typename Type>
    Formatter & operator << (const Type & value)
    {
        stream_ << value;
        return *this;
    }

    std::string str() const         { return stream_.str(); }
    operator std::string () const   { return stream_.str(); }

    enum ConvertToString 
    {
        to_str
    };
    std::string operator >> (ConvertToString) { return stream_.str(); }

private:
    std::stringstream stream_;

    Formatter(const Formatter &);
    Formatter & operator = (Formatter &);
};

Example:

throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData);   // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str);    // explicitly cast to std::string

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

How to parse a CSV file using PHP

I been seeking the same thing without using some unsupported PHP class. Excel CSV dosn't always use the quote separators and escapes the quotes using "" because the algorithm was probably made back the 80's or something. After looking at several .csv parsers in the comments section on PHP.NET, I seen ones that even used callbacks or eval'd code and they either didnt work like needed or simply didnt work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.

    function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
    // SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
    // AUTHOR: [email protected]
    // RELEASED: 9/21/13 BETA
      { $r=1; $row=array(); $fields=array(); $csv="";
        $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
        $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

        if($mode=='EXCEL')// escape code = ""
         { $delim=','; $enclos='"'; $rowbr="\r\n"; }
        else //mode=STANDARD all fields enclosed
           { $delim=','; $enclos='"'; $rowbr="\r\n"; }

          $csv=""; $i=-1; $i2=0; $imax=count($rows);

          while( $i < $imax )
          {
            // get field names
            if($i == -1)
             { $row=$rows[0];
               if($fmt=='2D_FIELDNAME_ARRAY')
                { $i2=0; $i2max=count($row);
                  while( list($k, $v) = each($row) )
                   { $fields[$i2]=$k;
                     $i2++;
                   }
                }
               else //if($fmt='2D_NUMBERED_ARRAY')
                { $i2=0; $i2max=(count($rows[0]));
                  while($i2<$i2max)
                   { $fields[$i2]=$i2;
                     $i2++;
                   }
                }

               if($headerrow==true) { $row=$fields; }
               else                 { $i=0; $row=$rows[0];}
             }
            else
             { $row=$rows[$i];
             }

            $i2=0;  $i2max=count($row); 
            while($i2 < $i2max)// numeric loop (order really matters here)
            //while( list($k, $v) = each($row) )
             { if($i2 != 0) $csv=$csv.$delim;

               $v=$row[$fields[$i2]];

               if($mode=='EXCEL') //EXCEL 2quote escapes
                    { $newv = '"'.(str_replace('"', '""', $v)).'"'; }
               else  //STANDARD
                    { $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
               $csv=$csv.$newv;
               $i2++;
             }

            $csv=$csv."\r\n";

            $i++;
          }

         return $csv;
       }

    function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
     { // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
       // AUTHOR: [email protected]
       // RELEASED: 9/21/13 BETA
       //SWMessage("SW_ExplodeCSV() - CALLED HERE -");
       $rows=array(); $row=array(); $fields=array();// rows = array of arrays

       //escape code = '\'
       $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
       $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

       if($mode=='EXCEL')
        {// escape code = ""
          $delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="\r\n";
        }
       else //mode=STANDARD 
        {// all fields enclosed
          $delim=','; $enclos='"'; $rowbr="\r\n";
        }

       $indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
       $rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
       $headerflg=0; $quotedflg=0;
       $i=0; $i2=0; $imax=strlen($csv);   

       while($indxf < $imax)
         {
           //find first *possible* cell delimiters
           $indxl=strpos($csv, $delim, $indxf);  if($indxl===false) { $indxl=$imax; }
           $encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
           $rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }

           if(($encindxf>$indxl)||($encindxf>$rowindxl))
            { $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }
           else 
            { //find cell enclosure area (and real cell delimiter)
              $quoteflg=1;
              $enc=$encindxf; 
              while($enc<$indxl) //$enc = next open quote
               {// loop till unquoted delim. is found
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
                 $encindxl=$enc; //last close quote
                 $indxl=strpos($csv, $delim, $enc+1); if($indxl===false)  { $indxl=$imax; }//last delim.
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
                 if(($indxl==$imax)||($enc==$imax)) break;
               }
              $rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }

           if($quoteflg==0)
            { //no enclosured content - take as is
              $colflg=1;
              //get cell 
             // $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
              $cell=substr($csv, $indxf, ($indxl-$indxf));
            }
           else// if($rowindxl > $encindxf)
            { // cell enclosed
              $colflg=1;

             //get cell - decode cell content
              $cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);

              if($mode=='EXCEL') //remove EXCEL 2quote escapes
                { $cell=str_replace($esc_enclos, $enclos, $cell);
                }
              else //remove STANDARD esc. sceme
                { $cell=str_replace($escapes, $escapes2, $cell);
                }
            }

           if($colflg)
            {// read cell into array
              if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
               { $row[$fields[$colcnt]]=$cell; }
              else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
               { $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;

              $colcnt++; $colflg=0; $cell="";
              $indxf=$indxl+1;//strlen($delim);
            }
           if($rowflg)
            {// read row into big array
              if(($headerrow) && ($headerflg==0))
                {  $fields=$row;
                   $row=array();
                   $headerflg=1;
                }
              else
                { $rows[$rowcnt]=$row;
                  $row=array();
                  $rowcnt++; 
                }
               $colcnt=0; $rowflg=0; $cell="";
               $rowindxf=$rowindxl+2;//strlen($rowbr);
               $indxf=$rowindxf;
            }

           $i++;
           //SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt."   rowcnt = ".$rowcnt."   indxf = ".$indxf."   indxl = ".$indxl."   rowindxf = ".$rowindxf);
           //if($i>20) break;
         }

       return $rows;
     }

...bob can now go back to his speadsheets

C#: Looping through lines of multiline string

I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil but also available in this StackOverflow answer - you can easily copy just that class into your own utility project. You'd use it like this:

string text = @"First line
second line
third line";

foreach (string line in new LineReader(() => new StringReader(text)))
{
    Console.WriteLine(line);
}

Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik's:

using (StringReader reader = new StringReader(input))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do something with the line
    }
}

This way you only have to test for nullity once, and you don't have to think about a do/while loop either (which for some reason always takes me more effort to read than a straight while loop).

Getting rid of all the rounded corners in Twitter Bootstrap

With SASS Bootstrap - if you are compiling Bootstrap yourself - you can set all border radius (or more specific) simply to zero:

$border-radius:               0;
$border-radius-lg:            0;
$border-radius-sm:            0;

javaw.exe cannot find path

Make sure to download these from here:

enter image description here

Also create PATH enviroment variable on you computer like this (if it doesn't exist already):

  1. Right click on My Computer/Computer
  2. Properties
  3. Advanced system settings (or just Advanced)
  4. Enviroment variables
  5. If PATH variable doesn't exist among "User variables" click New (Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin; <-- please check out the right version, this may differ as Oracle keeps updating Java). ; in the end enables assignment of multiple values to PATH variable.
  6. Click OK! Done

enter image description here

To be sure that everything works, open CMD Prompt and type: java -version to check for Java version and javac to be sure that compiler responds.

enter image description here

I hope this helps. Good luck!

Indent List in HTML and CSS

You can use [Adjacent sibling combinators] as described in the W3 CSS Selectors Recommendation1 So you can use a + sign (or even a ~ tilde) apply a padding to the nested ul tag, as you described in your question and you'll get the result you need. I also think what you want it to override the main css, locally. You can do this:

<style>
    li+ul {padding-left: 20px;}
</style>

This way the inner ul will be nested including the bullets of the li elements. I wish this was helpful! =)

What is the difference between C# and .NET?

C# is a programming language.

.Net is a framework used for building applications on Windows.

.Net framework is not limited to C#. Different languages can target .Net framework and build applications using that framework. Examples are F# or VB.Net

What is the Auto-Alignment Shortcut Key in Eclipse?

Ctrl+Shift+F to invoke the Auto Formatter

Ctrl+I to indent the selected part (or all) of you code.

How can I plot a confusion matrix?

enter image description here

you can use plt.matshow() instead of plt.imshow() or you can use seaborn module's heatmap (see documentation) to plot the confusion matrix

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3], 
        [3,31,0,0,0,0,0,0,0,0,0], 
        [0,4,41,0,0,0,0,0,0,0,1], 
        [0,1,0,30,0,6,0,0,0,0,1], 
        [0,0,0,0,38,10,0,0,0,0,0], 
        [0,0,0,3,1,39,0,0,0,0,4], 
        [0,2,2,0,4,1,31,0,0,0,2],
        [0,1,0,0,0,0,0,36,0,2,0], 
        [0,0,0,0,0,0,1,5,37,5,1], 
        [3,0,0,0,0,0,0,0,0,39,0], 
        [0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
                  columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)

Formatting text in a TextBlock

There are various Inline elements that can help you, for the simplest formatting options you can use Bold, Italic and Underline:

<TextBlock>
    Sample text with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> words.
</TextBlock>

enter image description here

I think it is worth noting, that those elements are in fact just shorthands for Span elements with various properties set (i.e.: for Bold, the FontWeight property is set to FontWeights.Bold).

This brings us to our next option: the aforementioned Span element.

You can achieve the same effects with this element as above, but you are granted even more possibilities; you can set (among others) the Foreground or the Background properties:

<TextBlock>
    Sample text with <Span FontWeight="Bold">bold</Span>, <Span FontStyle="Italic">italic</Span> and <Span TextDecorations="Underline">underlined</Span> words. <Span Foreground="Blue">Coloring</Span> <Span Foreground="Red">is</Span> <Span Background="Cyan">also</Span> <Span Foreground="Silver">possible</Span>.
</TextBlock>

enter image description here

The Span element may also contain other elements like this:

<TextBlock>
    <Span FontStyle="Italic">Italic <Span Background="Yellow">text</Span> with some <Span Foreground="Blue">coloring</Span>.</Span>
</TextBlock>

enter image description here

There is another element, which is quite similar to Span, it is called Run. The Run cannot contain other inline elements while the Span can, but you can easily bind a variable to the Run's Text property:

<TextBlock>
    Username: <Run FontWeight="Bold" Text="{Binding UserName}"/>
</TextBlock>

enter image description here

Also, you can do the whole formatting from code-behind if you prefer:

TextBlock tb = new TextBlock();
tb.Inlines.Add("Sample text with ");
tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
tb.Inlines.Add(", ");
tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
tb.Inlines.Add("and ");
tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
tb.Inlines.Add("words.");

gcc-arm-linux-gnueabi command not found

I was also facing the same issue and resolved it after installing the following dependency:

sudo apt-get install lib32z1-dev

Super-simple example of C# observer/observable with delegates

In this model, you have publishers who will do some logic and publish an "event."
Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.

In C#, any object can publish a set of events to which other applications can subscribe.
When the publishing class raises an event, all the subscribed applications are notified.
The following figure shows this mechanism.

enter image description here

Simplest Example possible on Events and Delegates in C#:

code is self explanatory, Also I've added the comments to clear out the code.

  using System;

public class Publisher //main publisher class which will invoke methods of all subscriber classes
{
    public delegate void TickHandler(Publisher m, EventArgs e); //declaring a delegate
    public TickHandler Tick;     //creating an object of delegate
    public EventArgs e = null;   //set 2nd paramter empty
    public void Start()     //starting point of thread
    {
        while (true)
        {
            System.Threading.Thread.Sleep(300);
            if (Tick != null)   //check if delegate object points to any listener classes method
            {
                Tick(this, e);  //if it points i.e. not null then invoke that method!
            }
        }
    }
}

public class Subscriber1                //1st subscriber class
{
    public void Subscribe(Publisher m)  //get the object of pubisher class
    {
        m.Tick += HeardIt;              //attach listener class method to publisher class delegate object
    }
    private void HeardIt(Publisher m, EventArgs e)   //subscriber class method
    {
        System.Console.WriteLine("Heard It by Listener");
    }

}
public class Subscriber2                   //2nd subscriber class
{
    public void Subscribe2(Publisher m)    //get the object of pubisher class
    {
        m.Tick += HeardIt;               //attach listener class method to publisher class delegate object
    }
    private void HeardIt(Publisher m, EventArgs e)   //subscriber class method
    {
        System.Console.WriteLine("Heard It by Listener2");
    }

}

class Test
{
    static void Main()
    {
        Publisher m = new Publisher();      //create an object of publisher class which will later be passed on subscriber classes
        Subscriber1 l = new Subscriber1();  //create object of 1st subscriber class
        Subscriber2 l2 = new Subscriber2(); //create object of 2nd subscriber class
        l.Subscribe(m);     //we pass object of publisher class to access delegate of publisher class
        l2.Subscribe2(m);   //we pass object of publisher class to access delegate of publisher class

        m.Start();          //starting point of publisher class
    }
}

Output:

Heard It by Listener

Heard It by Listener2

Heard It by Listener

Heard It by Listener2

Heard It by Listener . . . (infinite times)

How to handle configuration in Go

I agree with nemo and I wrote a little tool to make it all real easy.

bitbucket.org/gotamer/cfg is a json configuration package

  • You define your config items in your application as a struct.
  • A json config file template from your struct is saved on the first run
  • You can save runtime modifications to the config

See doc.go for an example

Tesseract OCR simple example

I was able to get it to work by following these instructions.

  • Download the sample code Tesseract sample code

  • Unzip it to a new location

  • Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)

  • Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to) NuGet Tesseract

  • Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • Run (hit F5)

  • You should get this windows console output enter image description here

Change the background color of a row in a JTable

One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:

static class MyTableModel extends DefaultTableModel {

    List<Color> rowColours = Arrays.asList(
        Color.RED,
        Color.GREEN,
        Color.CYAN
    );

    public void setRowColour(int row, Color c) {
        rowColours.set(row, c);
        fireTableRowsUpdated(row, row);
    }

    public Color getRowColour(int row) {
        return rowColours.get(row);
    }

    @Override
    public int getRowCount() {
        return 3;
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int row, int column) {
        return String.format("%d %d", row, column);
    }
}

Note that setRowColour calls fireTableRowsUpdated; this will cause just that row of the table to be updated.

The renderer can get the model from the table:

static class MyTableCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        MyTableModel model = (MyTableModel) table.getModel();
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(model.getRowColour(row));
        return c;
    }
}

Changing a row's colour would be as simple as:

model.setRowColour(1, Color.YELLOW);

int value under 10 convert to string two digit number

The accepted answer is good and fast:

i.ToString("00")

or

i.ToString("000")

If you need more complexity, String.Format is worth a try:

var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
    str1 = String.Format("{0:00}", i);
    str2 = String.Format("{0:000}", i);
}

For the i = 10 case:

str1: "10"
str2: "010"

I use this, for example, to clear the text on particular Label Controls on my form by name:

private void EmptyLabelArray()
{
    var fmt = "Label_Row{0:00}_Col{0:00}";
    for (var rowIndex = 0; rowIndex < 100; rowIndex++)
    {
        for (var colIndex = 0; colIndex < 100; colIndex++)
        {
            var lblName = String.Format(fmt, rowIndex, colIndex);
            foreach (var ctrl in this.Controls)
            {
                var lbl = ctrl as Label;
                if ((lbl != null) && (lbl.Name == lblName))
                {
                    lbl.Text = null;
                }
            }
        }
    }
}

Angular2 multiple router-outlet in the same template

<a [routerLink]="[{ outlets: { list:['streams'], details:['parties'] } }]">Link</a>

<div id="list">
    <router-outlet name="list"></router-outlet>
</div>
<div id="details">
    <router-outlet name="details"></router-outlet>
</div>

`

 {
    path: 'admin',
    component: AdminLayoutComponent,
    children:[
      {
        path: '',
        component: AdminStreamsComponent, 
        outlet:'list'
      },
      {
        path: 'stream/:id',
        component: AdminStreamComponent,
        outlet:'details'
      }
    ]
  }

Remove empty elements from an array in Javascript

When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.

var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});

Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.

Returns

["some string yay", "Other string yay"]

How to start debug mode from command prompt for apache tomcat server?

There are two ways to run tomcat in debug mode

  1. Using jdpa run

  2. Using JAVA_OPTS

First setup the environment. Then start the server using following commands.

_x000D_
_x000D_
export JPDA_ADDRESS=8000_x000D_
_x000D_
export JPDA_TRANSPORT=dt_socket_x000D_
_x000D_
%TOMCAT_HOME%/bin/catalina.sh jpda start_x000D_
_x000D_
sudo catalina.sh jpda start
_x000D_
_x000D_
_x000D_

refer this article for more information this is clearly define it

How to get the height of a body element

Set

html { height: 100%; }
body { min-height: 100%; }

instead of height: 100%.

The result jQuery returns is correct, because you've set the height of the body to 100%, and that's probably the height of the viewport. These three DIVs were causing an overflow, because there weren't enough space for them in the BODY element. To see what I mean, set a border to the BODY tag and check where the border ends.

How to assign from a function which returns more than one value?

There's no right answer to this question. I really depends on what you're doing with the data. In the simple example above, I would strongly suggest:

  1. Keep things as simple as possible.
  2. Wherever possible, it's a best practice to keep your functions vectorized. That provides the greatest amount of flexibility and speed in the long run.

Is it important that the values 1 and 2 above have names? In other words, why is it important in this example that 1 and 2 be named a and b, rather than just r[1] and r[2]? One important thing to understand in this context is that a and b are also both vectors of length 1. So you're not really changing anything in the process of making that assignment, other than having 2 new vectors that don't need subscripts to be referenced:

> r <- c(1,2)
> a <- r[1]
> b <- r[2]
> class(r)
[1] "numeric"
> class(a)
[1] "numeric"
> a
[1] 1
> a[1]
[1] 1

You can also assign the names to the original vector if you would rather reference the letter than the index:

> names(r) <- c("a","b")
> names(r)
[1] "a" "b"
> r["a"]
a 
1 

[Edit] Given that you will be applying min and max to each vector separately, I would suggest either using a matrix (if a and b will be the same length and the same data type) or data frame (if a and b will be the same length but can be different data types) or else use a list like in your last example (if they can be of differing lengths and data types).

> r <- data.frame(a=1:4, b=5:8)
> r
  a b
1 1 5
2 2 6
3 3 7
4 4 8
> min(r$a)
[1] 1
> max(r$b)
[1] 8

Custom seekbar (thumb size, color and background)

Use tints ;)

<SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="15dp"
        android:minWidth="15dp"
        android:maxHeight="15dp"
        android:maxWidth="15dp"
        android:progress="20"
        android:thumbTint="@color/colorPrimaryDark"
        android:progressTint="@color/colorPrimary"/>

use the color you need in thumbTint and progressTint. It is much faster! :)

Edit ofc you can use in combination with android:progressDrawable="@drawable/seekbar"

How to convert a string with Unicode encoding to a string of letters

Updates regarding answers suggesting using The Apache Commons Lang's: StringEscapeUtils.unescapeJava() - it was deprecated,

Deprecated. as of 3.6, use commons-text StringEscapeUtils instead

The replacement is Apache Commons Text's StringEscapeUtils.unescapeJava()

Laravel 5 - redirect to HTTPS

I am using in Laravel 5.6.28 next middleware:

namespace App\Http\Middleware;

use App\Models\Unit;
use Closure;
use Illuminate\Http\Request;

class HttpsProtocol
{
    public function handle($request, Closure $next)
    {
        $request->setTrustedProxies([$request->getClientIp()], Request::HEADER_X_FORWARDED_ALL);

        if (!$request->secure() && env('APP_ENV') === 'prod') {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

1052: Column 'id' in field list is ambiguous

The simplest solution is a join with USING instead of ON. That way, the database "knows" that both id columns are actually the same, and won't nitpick on that:

SELECT id, name, section
  FROM tbl_names
  JOIN tbl_section USING (id)

If id is the only common column name in tbl_names and tbl_section, you can even use a NATURAL JOIN:

SELECT id, name, section
  FROM tbl_names
  NATURAL JOIN tbl_section

See also: https://dev.mysql.com/doc/refman/5.7/en/join.html

.datepicker('setdate') issues, in jQuery

Try changing it to:

queryDate = '2009-11-01';
$('#datePicker').datepicker({defaultDate: new Date (queryDate)});

Ruby max integer

There is no maximum since Ruby 2.4, as Bignum and Fixnum got unified into Integer. see Feature #12005

> (2 << 1000).is_a? Fixnum
(irb):322: warning: constant ::Fixnum is deprecated
=> true

> 1.is_a? Bignum
(irb):314: warning: constant ::Bignum is deprecated
=> true

> (2 << 1000).class
=> Integer

There won't be any overflow, what would happen is an out of memory.

How to convert a huge list-of-vector to a matrix more efficiently?

You can also use,

output <- as.matrix(as.data.frame(z))

The memory usage is very similar to

output <- matrix(unlist(z), ncol = 10, byrow = TRUE)

Which can be verified, with mem_changed() from library(pryr).

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

How to sort a dataFrame in python pandas by two or more columns?

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

Use Font Awesome Icons in CSS

Consolidating everything above, the following is the final class which works well

   .faArrowIcon {
        position:relative;
    }

    .faArrowIcon:before {
        font-family: FontAwesome;
        top:0;
        left:-5px;
        padding-right:10px;
        content: "\f0a9"; 
    }

'this' is undefined in JavaScript class methods

How are you calling the start function?

This should work (new is the key)

var o = new Request(destination, stay_open);
o.start();

If you directly call it like Request.prototype.start(), this will refer to the global context (window in browsers).

Also, if this is undefined, it results in an error. The if expression does not evaluate to false.

Update: this object is not set based on declaration, but by invocation. What it means is that if you assign the function property to a variable like x = o.start and call x(), this inside start no longer refers to o. This is what happens when you do setTimeout. To make it work, do this instead:

 var o = new Request(...);
 setTimeout(function() { o.start(); }, 1000);

click or change event on radio using jquery

_x000D_
_x000D_
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
     console.log(e.type);_x000D_
     return false;_x000D_
});
_x000D_
_x000D_
_x000D_

This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

Lastly, I'm simply showing an alternative syntax to attach the event to the element.

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

How to add an empty column to a dataframe?

Starting with v0.16.0, DF.assign() could be used to assign new columns (single/multiple) to a DF. These columns get inserted in alphabetical order at the end of the DF.

This becomes advantageous compared to simple assignment in cases wherein you want to perform a series of chained operations directly on the returned dataframe.

Consider the same DF sample demonstrated by @DSM:

df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
df
Out[18]:
   A  B
0  1  2
1  2  3
2  3  4

df.assign(C="",D=np.nan)
Out[21]:
   A  B C   D
0  1  2   NaN
1  2  3   NaN
2  3  4   NaN

Note that this returns a copy with all the previous columns along with the newly created ones. In order for the original DF to be modified accordingly, use it like : df = df.assign(...) as it does not support inplace operation currently.

getResourceAsStream returns null

There seems to be issue with the ClassLoader that you are using. Use the contextClassLoader to load class. This is irrespective of whether it is in a static/non-static method

Thread.currentThread().getContextClassLoader().getResourceAsStream......

How to read a file in reverse order?

If you are concerned about file size / memory usage, memory-mapping the file and scanning backwards for newlines is a solution:

How to search for a string in text files?

How can I compile LaTeX in UTF8?

I'm not sure whether I got your problem but maybe it helps if you store the source using a UTF-8 encoding.

I'm also using \usepackage[utf8]{inputenc} in my LaTeX sources and by storing the files as UTF-8 files everything works just peachy.

window.print() not working in IE

The way we typically handle printing is to just open the new window with everything in it that needs to be sent to the printer. Then we have the user actually click on their browsers Print button.

This has always been acceptable in the past, and it sidesteps the security restrictions that Chilln is talking about.

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

I had this issue when tried to run a 32-bit OS with more than 3584 MB of RAM allocated for it. Setting the guest OS RAM to 3584 MB and less helped.

But i ended just enabling the flag in BIOS nevertheless.

Getting Data from Android Play Store

The Google Play Store doesn't provide this data, so the sites must just be scraping it.

How to insert strings containing slashes with sed?

The s command can use any character as a delimiter; whatever character comes after the s is used. I was brought up to use a #. Like so:

s#?page=one&#/page/one#g

Is a Java hashmap search really O(1)?

This basically goes for most hash table implementations in most programming languages, as the algorithm itself doesn't really change.

If there are no collisions present in the table, you only have to do a single look-up, therefore the running time is O(1). If there are collisions present, you have to do more than one look-up, which drives down the performance towards O(n).

How to read multiple Integer values from a single line of input in Java?

created this code specially for the Hacker earth exam


  Scanner values = new Scanner(System.in);  //initialize scanner
  int[] arr = new int[6]; //initialize array 
  for (int i = 0; i < arr.length; i++) {
      arr[i] = (values.hasNext() == true ? values.nextInt():null);
      // it will read the next input value
  }

 /* user enter =  1 2 3 4 5
    arr[1]= 1
    arr[2]= 2
    and soo on 
 */ 

Random record from MongoDB

In Python using pymongo:

import random

def get_random_doc():
    count = collection.count()
    return collection.find()[random.randrange(count)]

Change Git repository directory location.

Report from the future: April 2018.

I wanted to normalize my local repos on my Mac and my Windows, which had ended up in different local folders.

The Windows 10 client made me go through the "Can't Find" > "Locate" routine, tedious but not terrible. Also need to update the local "Clone path" in Options for future use.

When I consolidated the mac folders, the Github client just found them again - I had to do nothing!

Android: I am unable to have ViewPager WRAP_CONTENT

in my case adding clipToPadding solved the problem.

<android.support.v4.view.ViewPager
    ...
    android:clipToPadding="false"
    ...
    />

Cheers!

Omitting all xsi and xsd namespaces when serializing an object in .NET?

After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To wit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the defalt namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.

YouTube Video Embedded via iframe Ignoring z-index?

Just add one of these two to the src url:

&wmode=Opaque

&wmode=transparent

<iframe id="videoIframe" width="500" height="281" src="http://www.youtube.com/embed/xxxxxx?rel=0&wmode=transparent" frameborder="0" allowfullscreen></iframe>

Sieve of Eratosthenes - Finding Primes Python

My implementation:

import math
n = 100
marked = {}
for i in range(2, int(math.sqrt(n))):
    if not marked.get(i):
        for x in range(i * i, n, i):
            marked[x] = True

for i in range(2, n):
    if not marked.get(i):
        print i

Get the last three chars from any string - Java

You can use a substring

String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

How can I replace newlines using PowerShell?

A CRLF is two characters, of course, the CR and the LF. However, `n consists of both. For example:

PS C:\> $x = "Hello
>> World"

PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>

I think you're running into problems with the `r. I was able to remove the `r from your example, use only `n, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.

Create folder with batch but only if it doesn't already exist

This should work for you:

IF NOT EXIST "\path\to\your\folder" md \path\to\your\folder

However, there is another method, but it may not be 100% useful:

md \path\to\your\folder >NUL 2>NUL

This one creates the folder, but does not show the error output if folder exists. I highly recommend that you use the first one. The second one is if you have problems with the other.

jQuery AJAX cross domain

I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.

  • server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
  • before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
  • you may set flag once or everytime before using jQuery ajax function
  • now I can read .xml document in IE and Firefox. Other browsers I did not test.
  • response document can be plain/text, xml, json or anything else

Here is an example jQuery ajax call with some debug sysouts.

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

jquery click event not firing?

Is this markup added to the DOM asynchronously? You will need to use live in that case:

NOTE: .live has been deprecated and removed in the latest versions of jQuery (for good reason). Please refer to the event delegation strategy below for usage and solution.

<script>
    $(document).ready(function(){
        $('.play_navigation a').live('click', function(){
            console.log("this is the click");
            return false;
        });
    });
</script>

The fact that you are able to re-run your script block and have it work tells me that for some reason the elements weren't available at the time of binding or the binding was removed at some point. If the elements weren't there at bind-time, you will need to use live (or event delegation, preferably). Otherwise, you need to check your code for something else that would be removing the binding.

Using jQuery 1.7 event delegation:

$(function () {

    $('.play_navigation').on('click', 'a', function (e) {
        console.log('this is the click');
        e.preventDefault();
    });

});

You can also delegate events up to the document if you feel that you would like to bind the event before the document is ready (note that this also causes jQuery to examine every click event to determine if the element matches the appropriate selector):

$(document).on('click', '.play_navigation a', function (e) {
    console.log('this is the click');
    e.preventDefault();
});

How to reload .bash_profile from the command line?

alias reload!=". ~/.bash_profile"

or if wanna add logs via functions

function reload! () {
    echo "Reloading bash profile...!"
    source ~/.bash_profile
    echo "Reloaded!!!"
}

Change color of Button when Mouse is over

As others already said, there seems to be no good solution to do that easily.
But to keep your code clean I suggest creating a seperate class that hides the ugly XAML.

How to use after we created the ButtonEx-class:

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfEx="clr-namespace:WpfExtensions"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <wpfEx:ButtonEx HoverBackground="Red"></wpfEx:ButtonEx>
    </Grid>
</Window>

ButtonEx.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WpfExtensions
{
    /// <summary>
    /// Standard button with extensions
    /// </summary>
    public partial class ButtonEx : Button
    {
        readonly static Brush DefaultHoverBackgroundValue = new BrushConverter().ConvertFromString("#FFBEE6FD") as Brush;

        public ButtonEx()
        {
            InitializeComponent();
        }

        public Brush HoverBackground
        {
            get { return (Brush)GetValue(HoverBackgroundProperty); }
            set { SetValue(HoverBackgroundProperty, value); }
        }
        public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.Register(
          "HoverBackground", typeof(Brush), typeof(ButtonEx), new PropertyMetadata(DefaultHoverBackgroundValue));
    }
}

ButtonEx.xaml
Note: This contains all the original XAML from System.Windows.Controls.Button

<Button x:Class="WpfExtensions.ButtonEx"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
            x:Name="buttonExtension">
    <Button.Resources>
        <Style x:Key="FocusVisual">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="10" StrokeDashArray="1 2"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <SolidColorBrush x:Key="Button.Static.Background" Color="#FFDDDDDD"/>
        <SolidColorBrush x:Key="Button.Static.Border" Color="#FF707070"/>
        <SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
        <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
        <SolidColorBrush x:Key="Button.Pressed.Background" Color="#FFC4E5F6"/>
        <SolidColorBrush x:Key="Button.Pressed.Border" Color="#FF2C628B"/>
        <SolidColorBrush x:Key="Button.Disabled.Background" Color="#FFF4F4F4"/>
        <SolidColorBrush x:Key="Button.Disabled.Border" Color="#FFADB2B5"/>
        <SolidColorBrush x:Key="Button.Disabled.Foreground" Color="#FF838383"/>
    </Button.Resources>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
            <Setter Property="Background" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
                            <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsDefaulted" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{Binding Path=HoverBackground, ElementName=buttonExtension}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                            </Trigger>
                            <Trigger Property="IsPressed" Value="true">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
                            </Trigger>
                            <Trigger Property="IsEnabled" Value="false">
                                <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
                                <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
                                <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{StaticResource Button.Disabled.Foreground}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Button.Style>
</Button>

Tip: You can add an UserControl with name "ButtonEx" to your project in VS Studio and then copy paste the stuff above in.

Pandas: Appending a row to a dataframe and specify its index label

There is another solution. The next code is bad (although I think pandas needs this feature):

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}

But the next code runs fine:

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))

Call Class Method From Another Class

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
    def method1(self, a, b, c):
        # foo

method = A.method1

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass) 
                     # but will not have access to the instance it's called on 
                     # (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

php random x digit number

The following code generates a 4 digits random number:

echo sprintf( "%04d", rand(0,9999));

converting drawable resource image into bitmap

You probably mean Notification.Builder.setLargeIcon(Bitmap), right? :)

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.large_icon);
notBuilder.setLargeIcon(largeIcon);

This is a great method of converting resource images into Android Bitmaps.

How do I get the entity that represents the current user in Symfony2?

Well, first you need to request the username of the user from the session in your controller action like this:

$username=$this->get('security.context')->getToken()->getUser()->getUserName();

then do a query to the db and get your object with regular dql like

$em = $this->get('doctrine.orm.entity_manager');    
"SELECT u FROM Acme\AuctionBundle\Entity\User u where u.username=".$username;
$q=$em->createQuery($query);
$user=$q->getResult();

the $user should now hold the user with this username ( you could also use other fields of course)

...but you will have to first configure your /app/config/security.yml configuration to use the appropriate field for your security provider like so:

security:
 provider:
  example:
   entity: {class Acme\AuctionBundle\Entity\User, property: username}

hope this helps!

How to install an npm package from GitHub directly?

I tried npm install git+https://github.com/visionmedia/express but that took way too long and I wasn't sure that would work.

What did work for me was - yarn add git+https://github.com/visionmedia/express.

File URL "Not allowed to load local resource" in the Internet Browser

I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.

Based on your screenshot, try formatting your link like so:

<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>

(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)

Difference between variable declaration syntaxes in Javascript (including global variables)?

In global scope there is no semantic difference.

But you really should avoid a=0 since your setting a value to an undeclared variable.

Also use closures to avoid editing global scope at all

(function() {
   // do stuff locally

   // Hoist something to global scope
   window.someGlobal = someLocal
}());

Always use closures and always hoist to global scope when its absolutely neccesary. You should be using asynchronous event handling for most of your communication anyway.

As @AvianMoncellor mentioned there is an IE bug with var a = foo only declaring a global for file scope. This is an issue with IE's notorious broken interpreter. This bug does sound familiar so it's probably true.

So stick to window.globalName = someLocalpointer