Programs & Examples On #Coff

COFF (Common Object File Format) is a file format for files containing machine code.

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

I installed python2.7 to solve this issue. I wish can help you.

Docker error cannot delete docker container, conflict: unable to remove repository reference

you can use -f option to force delete the containers .

sudo docker rmi -f training/webapp

You may stop the containers using sudo docker stop training/webapp before deleting

How to run TypeScript files from command line?

Like Zeeshan Ahmad's answer, I also think ts-node is the way to go. I would also add a shebang and make it executable, so you can just run it directly.

  1. Install typescript and ts-node globally:

    npm install -g ts-node typescript
    

    or

    yarn global add ts-node typescript
    
  2. Create a file hello with this content:

    #!/usr/bin/env ts-node-script
    
    import * as os from 'os'
    
    function hello(name: string) {
        return 'Hello, ' + name
    }
    const user = os.userInfo().username
    console.log(`Result: ${hello(user)}`)
    

    As you can see, line one has the shebang for ts-node

  3. Run directly by just executing the file

    $ ./hello
    Result: Hello, root
    

Some notes:


Update 2020-04-06: Some changes after great input in the comments: Update shebang to use ts-node-script instead of ts-node, link to issues in ts-node.

iPad Multitasking support requires these orientations

Go to your project target in Xcode > General > Set "Requires full screen" (under Hide status bar) to true.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

We have the following string which is a valid JSON ...

Clearly the JSON parser disagrees!

However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.

You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException ... then find out what is in the ByteArrayInputStream that it is attempting to parse.

How do I make an attributed string using Swift?

extension UILabel{
    func setSubTextColor(pSubString : String, pColor : UIColor){    
        let attributedString: NSMutableAttributedString = self.attributedText != nil ? NSMutableAttributedString(attributedString: self.attributedText!) : NSMutableAttributedString(string: self.text!);

        let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
        if range.location != NSNotFound {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
        }
        self.attributedText = attributedString
    }
}

Setting default value for TypeScript object passed as argument

Typescript supports default parameters now:

https://www.typescriptlang.org/docs/handbook/functions.html

Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:

function sayName(firstName: string, lastName = "Smith") {
  const name = firstName + ' ' + lastName;
  alert(name);
}

sayName('Bob');

How to run Gulp tasks sequentially one after the other

For me it was not running the minify task after concatenation as it expects concatenated input and it was not generated some times.

I tried adding to a default task in execution order and it didn't worked. It worked after adding just a return for each tasks and getting the minification inside gulp.start() like below.

/**
* Concatenate JavaScripts
*/
gulp.task('concat-js', function(){
    return gulp.src([
        'js/jquery.js',
        'js/jquery-ui.js',
        'js/bootstrap.js',
        'js/jquery.onepage-scroll.js',
        'js/script.js'])
    .pipe(maps.init())
    .pipe(concat('ux.js'))
    .pipe(maps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

/**
* Minify JavaScript
*/
gulp.task('minify-js', function(){
    return gulp.src('dist/js/ux.js')
    .pipe(uglify())
    .pipe(rename('ux.min.js'))
    .pipe(gulp.dest('dist/js'));
});

gulp.task('concat', ['concat-js'], function(){
   gulp.start('minify-js');
});

gulp.task('default',['concat']); 

Source http://schickling.me/synchronous-tasks-gulp/

Send value of submit button when form gets posted

Like the others said, you probably missunderstood the idea of a unique id. All I have to add is, that I do not like the idea of using "value" as the identifying property here, as it may change over time (i.e. if you want to provide multiple languages).

<input id='submit_tea'    type='submit' name = 'submit_tea'    value = 'Tea' />
<input id='submit_coffee' type='submit' name = 'submit_coffee' value = 'Coffee' />

and in your php script

if( array_key_exists( 'submit_tea', $_POST ) )
{
  // handle tea
}
if( array_key_exists( 'submit_coffee', $_POST ) )
{
  // handle coffee
}

Additionally, you can add something like if( 'POST' == $_SERVER[ 'REQUEST_METHOD' ] ) if you want to check if data was acctually posted.

Access-Control-Allow-Origin and Angular.js $http

I've had success with express and editing the res.header. Mine matches yours pretty closely but I have a different Allow-Headers as noted below:

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

I'm also using Angular and Node/Express, but I don't have the headers called out in the Angular code only the node/express

How to create separate AngularJS controller files?

What about this solution? Modules and Controllers in Files (at the end of the page) It works with multiple controllers, directives and so on:

app.js

var app = angular.module("myApp", ['deps']);

myCtrl.js

app.controller("myCtrl", function($scope) { ..});

html

<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

Google has also a Best Practice Recommendations for Angular App Structure I really like to group by context. Not all the html in one folder, but for example all files for login (html, css, app.js,controller.js and so on). So if I work on a module, all the directives are easier to find.

Bootstrap 3.0 Popovers and tooltips

You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.

<script type="text/javascript">

    $(document).ready(function() {

        $('.btn-danger').tooltip();

    }); //END $(document).ready()

</script>

Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup".

Npm install failed with "cannot run in wd"

!~~ For Docker ~~!

@Alexander Mills answer - just to make it easier to find:

RUN npm set unsafe-perm true

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

placeholder for select tag

<select>

    <option selected="selected" class="Country">Country Name</option>

    <option value="1">India</option>

    <option value="2">us</option>

</select>

.country
{


    display:none;
}

</style>

Is it possible to run a .NET 4.5 app on XP?

I hesitate to post this answer, it is actually technically possible but it doesn't work that well in practice. The version numbers of the CLR and the core framework assemblies were not changed in 4.5. You still target v4.0.30319 of the CLR and the framework assembly version numbers are still 4.0.0.0. The only thing that's distinctive about the assembly manifest when you look at it with a disassembler like ildasm.exe is the presence of a [TargetFramework] attribute that says that 4.5 is needed, that would have to be altered. Not actually that easy, it is emitted by the compiler.

The biggest difference is not that visible, Microsoft made a long-overdue change in the executable header of the assemblies. Which specifies what version of Windows the executable is compatible with. XP belongs to a previous generation of Windows, started with Windows 2000. Their major version number is 5. Vista was the start of the current generation, major version number 6.

.NET compilers have always specified the minimum version number to be 4.00, the version of Windows NT and Windows 9x. You can see this by running dumpbin.exe /headers on the assembly. Sample output looks like this:

OPTIONAL HEADER VALUES
             10B magic # (PE32)
            ...
            4.00 operating system version
            0.00 image version
            4.00 subsystem version              // <=== here!!
               0 Win32 version
            ...

What's new in .NET 4.5 is that the compilers change that subsystem version to 6.00. A change that was over-due in large part because Windows pays attention to that number, beyond just checking if it is small enough. It also turns on appcompat features since it assumes that the program was written to work on old versions of Windows. These features cause trouble, particularly the way Windows lies about the size of a window in Aero is troublesome. It stops lying about the fat borders of an Aero window when it can see that the program was designed to run on a Windows version that has Aero.

You can alter that version number and set it back to 4.00 by running Editbin.exe on your assemblies with the /subsystem option. This answer shows a sample postbuild event.

That's however about where the good news ends, a significant problem is that .NET 4.5 isn't very compatible with .NET 4.0. By far the biggest hang-up is that classes were moved from one assembly to another. Most notably, that happened for the [Extension] attribute. Previously in System.Core.dll, it got moved to Mscorlib.dll in .NET 4.5. That's a kaboom on XP if you declare your own extension methods, your program says to look in Mscorlib for the attribute, enabled by a [TypeForwardedTo] attribute in the .NET 4.5 version of the System.Core reference assembly. But it isn't there when you run your program on .NET 4.0

And of course there's nothing that helps you stop using classes and methods that are only available on .NET 4.5. When you do, your program will fail with a TypeLoadException or MissingMethodException when run on 4.0

Just target 4.0 and all of these problems disappear. Or break that logjam and stop supporting XP, a business decision that programmers cannot often make but can certainly encourage by pointing out the hassles that it is causing. There is of course a non-zero cost to having to support ancient operating systems, just the testing effort is substantial. A cost that isn't often recognized by management, Windows compatibility is legendary, unless it is pointed out to them. Forward that cost to the client and they tend to make the right decision a lot quicker :) But we can't help you with that.

How to get the selected date value while using Bootstrap Datepicker?

Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date.
https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html#getdate

getDate: Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected.

$('.datepicker').datepicker("getDate")

or

$('.datepicker').datepicker("getDate").valueOf() 

Can't install any package with node npm

This worked for me (not using proxy):

  1. set registry mirror for npm..

    npm config set registry http://skimdb.npmjs.com/registry

found mirror from docs:https://docs.npmjs.com/misc/registry

  1. after this try npm install if it works then try to install whatever you want otherwise follow below steps as well

3.npm install -g handlebar //i did because it was showing error in npm log but you can skip

4.after that try to set again official registry

npm config set registry http://registry.npmjs.org

5.now try to install whatever package you want :-)

How to fix SSL certificate error when running Npm on Windows?

If you have control over the proxy server or can convince your IT admins you could try to explicitly exclude registry.npmjs.org from SSL inspection. This should avoid users of the proxy server from having to either disable strict-ssl checking or installing a new root CA.

NPM global install "cannot find module"

For Windows, from Nodejs cannot find installed module on Windows? what worked for me is running npm link as in

npm link wisp

Failure during conversion to COFF: file invalid or corrupt

I had this issue after installing dotnetframework4.5.
Open path below:
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin" ( in 64 bits machine)
or
"C:\Program Files\Microsoft Visual Studio 10.0\VC\bin" (in 32 bits machine)
In this path find file cvtres.exe and rename it to cvtres1.exe then compile your project again.

Determine command line working directory when running node bin script

  • process.cwd() returns directory where command has been executed (not directory of the node package) if it's has not been changed by 'process.chdir' inside of application.
  • __filename returns absolute path to file where it is placed.
  • __dirname returns absolute path to directory of __filename.

If you need to load files from your module directory you need to use relative paths.

require('../lib/test');

instead of

var lib  = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');

require(lib + '/test');

It's always relative to file where it called from and don't depend on current work dir.

is there a post render callback for Angular JS directive?

I had the same issue, but using Angular + DataTable with a fnDrawCallback + row grouping + $compiled nested directives. I placed the $timeout in my fnDrawCallback function to fix pagination rendering.

Before example, based on row_grouping source:

var myDrawCallback = function myDrawCallbackFn(oSettings){
  var nTrs = $('table#result>tbody>tr');
  for(var i=0; i<nTrs.length; i++){
     //1. group rows per row_grouping example
     //2. $compile html templates to hook datatable into Angular lifecycle
  }
}

After example:

var myDrawCallback = function myDrawCallbackFn(oSettings){
  var nTrs = $('table#result>tbody>tr');
  $timeout(function requiredRenderTimeoutDelay(){
    for(var i=0; i<nTrs.length; i++){
       //1. group rows per row_grouping example
       //2. $compile html templates to hook datatable into Angular lifecycle
    }
  ,50); //end $timeout
}

Even a short timeout delay was enough to allow Angular to render my compiled Angular directives.

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

To find the HSV value of Green, try following commands in Python terminal

green = np.uint8([[[0,255,0 ]]])
hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
print hsv_green
[[[ 60 255 255]]]

Run parallel multiple commands at once in the same terminal

I am suggesting a much simpler utility I just wrote. It's currently called par, but will be renamed soon to either parl or pll, haven't decided yet.

https://github.com/k-bx/par

API is as simple as:

par "script1.sh" "script2.sh" "script3.sh"

Prefixing commands can be done via:

par "PARPREFIX=[script1] script1.sh" "script2.sh" "script3.sh"

Using fonts with Rails asset pipeline

You need to use font-url in your @font-face block, not url

@font-face {
font-family: 'Inconsolata';
src:font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}

as well as this line in application.rb, as you mentioned (for fonts in app/assets/fonts

config.assets.paths << Rails.root.join("app", "assets", "fonts")

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

Reinstalling CMake worked for me. The new copy of CMake figured out that it should use Visual Studio 11 instead of 10.

apache not accepting incoming connections from outside of localhost

this would work: -- for REDHAT use : cat "/etc/sysconfig/iptables"

iptables -I  RH-Firewall-1-INPUT -s 192.168.1.3  -p tcp -m tcp --dport 80 -j ACCEPT

followed by

sudo /etc/init.d/iptables save

Exec : display stdout "live"

child_process.spawn returns an object with stdout and stderr streams. You can tap on the stdout stream to read data that the child process sends back to Node. stdout being a stream has the "data", "end", and other events that streams have. spawn is best used to when you want the child process to return a large amount of data to Node - image processing, reading binary data etc.

so you can solve your problem using child_process.spawn as used below.

var spawn = require('child_process').spawn,
ls = spawn('coffee -cw my_file.coffee');

ls.stdout.on('data', function (data) {
  console.log('stdout: ' + data.toString());
});

ls.stderr.on('data', function (data) {
  console.log('stderr: ' + data.toString());
});

ls.on('exit', function (code) {
  console.log('code ' + code.toString());
});

Ternary operation in CoffeeScript

CoffeeScript has no ternary operator. That's what the docs say.

You can still use a syntax like

a = true then 5 else 10

It's way much clearer.

bundle install returns "Could not locate Gemfile"

I had this problem on Ubuntu 18.04. I updated the gem

sudo gem install rails
sudo gem install jekyll
sudo gem install jekyll bundler
cd ~/desiredFolder
jekyll new <foldername>
cd <foldername> OR 
bundle init
bundle install
bundle add jekyll
bundle exec jekyll serve

All worked and goto your browser just go to http://127.0.0.1:4000/ and it really should be running

What is an example of the simplest possible Socket.io example?

i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpage? here is the absolute easiest and smallest example i could come up with.

this just returns a string passed from the console UPPERCASED.

app.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

var io = require('socket.io').listen(app);


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

to run:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

use something like this port test to ensure your port is open.

now browse to http://localhost/index.html and use your browser console to send messages back to the server.

at best guess, when using http.createServer, it changes the following two lines for you:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

Git stash pop- needs merge, unable to refresh index

Well, initially, we should know what caused the error to happen, then the solution will be easy. The reason have already been pointed out by the accepted answer, but it is somehow incomplete (also the solution).

The problem is, one or more files had conflict(s) previously, but Git sees them as unresolved. Yes, you might already edited those files and resolved the conflicts, but Git does not know about that. You should tell Git "Hey, there are no more conflicts from the previous merge!". Note that, the merge is not necessarily caused by a git merge, but also by a git stash pop, for example.

Remember, git status can tell you what Git knows now. If there are some unresolved merge conflicts to Git, then it is shown in a separated Unmerged paths section, with the files marked as both modified (always?). If you have noticed, this section is between two staged and unstaged sections. From this, I personally understand that, "Unmerged paths are those you should either move into staged or unstaged areas, as Git can work only with these two areas".

So, to tell Git the conflicts have been resolved, you should either move these changes to staged or unstaged areas. In recent versions of Git, when you do a git status, it tells you how (woah! You should ask yourself how you haven't seen this yet?):

$ git status
...
Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
        both modified:   path/to/file.txt
...

So, to stage it (and maybe commit it):

$ git add path/to/file.txt

And to make it unstaged (e.g. you don't want to commit it now):

$ git restore --staged path/to/file.txt

Note: Forgetting to write --staged option possibly could spawn a super-hungry dragon to eat your past two days, in the case of not using a good text-editor or IDE.

Note: While git restore command is experimental yet, it should be stable enough to be used (thanks to a comment by @VonC, refer to it for more details on that).

How to use executables from a package installed locally in node_modules?

Use the npm bin command to get the node modules /bin directory of your project

$ $(npm bin)/<binary-name> [args]

e.g.

$ $(npm bin)/bower install

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

If you have already installed all your dependencies, and you want to avoid having to download your production packages from NPM again, you can simply type:

npm prune --production

This will remove your dev dependencies from your node_modules folder, which is helpful if you're trying to automate a two step process like

  1. Webpack my project, using dev dependencies
  2. Build a Docker image using only production modules

Running npm prune in between will save you from having to reinstall everything!

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

In my case running the bundle command did the trick. I trust they find each other then.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

Here's the quick fix:

If you're using capistrano do this add this to your deploy.rb:

after 'deploy:update_code' do
  run "cd #{release_path}; RAILS_ENV=production rake assets:precompile"
end

cap deploy

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Can refer the code below for the same. Source: Academind/node-restful-api

const express = require('express');
const app = express();

//acts as a middleware
//to handle CORS Errors
app.use((req, res, next) => { //doesn't send response just adjusts it
    res.header("Access-Control-Allow-Origin", "*") //* to give access to any origin
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization" //to give access to all the headers provided
    );
    if(req.method === 'OPTIONS'){
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET'); //to give access to all the methods provided
        return res.status(200).json({});
    }
    next(); //so that other routes can take over
})

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

Indent List in HTML and CSS

It sounds like some of your styles are being reset.

By default in most browsers, uls and ols have margin and padding added to them.

You can override this (and many do) by adding a line to your css like so

ul, ol {  //THERE MAY BE OTHER ELEMENTS IN THE LIST
    margin:0;
    padding:0;
}

In this case, you would remove the element from this list or add a margin/padding back, like so

ul{
    margin:1em;
}

Example: http://jsfiddle.net/jasongennaro/vbMbQ/1/

Case Function Equivalent in Excel

The Switch function is now available, in Excel 2016 / Office 365

SWITCH(expression, value1, result1, [default or value2, result2],…[default or value3, result3])

example:
=SWITCH(A1,0,"FALSE",-1,"TRUE","Maybe")

Microsoft -Office Support

Note: MS has updated that page to only document the behavior of Excel 2019. Eventually, they will probably remove references to 2019 as well... To see what the page looked like in 2016, use the wayback machine: https://web.archive.org/web/20161010180642/https://support.office.com/en-us/article/SWITCH-function-47ab33c0-28ce-4530-8a45-d532ec4aa25e

JavaScript variable assignments from tuples

As an update to The Minister's answer, you can now do this with es2015:

function Tuple(...args) {
  args.forEach((val, idx) => 
    Object.defineProperty(this, "item"+idx, { get: () => val })
  )
}


var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"

https://jsbin.com/fubaluwimo/edit?js,console

How do I define global variables in CoffeeScript?

I think what you are trying to achieve can simply be done like this :

While you are compiling the coffeescript, use the "-b" parameter.

-b / --bare Compile the JavaScript without the top-level function safety wrapper.

So something like this : coffee -b --compile somefile.coffee whatever.js

This will output your code just like in the CoffeeScript.org site.

Reload chart data via JSON with Highcharts

You can always load a json data

here i defined Chart as namespace

 $.getJSON('data.json', function(data){
                Chart.options.series[0].data = data[0].data;
                Chart.options.series[1].data = data[1].data;
                Chart.options.series[2].data = data[2].data;

                var chart = new Highcharts.Chart(Chart.options);

            });

JavaScript validation for empty input field

An input field can have whitespaces, we want to prevent that.
Use String.prototype.trim():

function isEmpty(str) {
    return !str.trim().length;
}

Example:

_x000D_
_x000D_
const isEmpty = str => !str.trim().length;_x000D_
_x000D_
document.getElementById("name").addEventListener("input", function() {_x000D_
  if( isEmpty(this.value) ) {_x000D_
    console.log( "NAME is invalid (Empty)" )_x000D_
  } else {_x000D_
    console.log( `NAME value is: ${this.value}` );_x000D_
  }_x000D_
});
_x000D_
<input id="name" type="text">
_x000D_
_x000D_
_x000D_

Using prepared statements with JDBCTemplate

I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):

private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
    if (updateSales == null) {
        updateSales = con.prepareStatement(
            "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    }
    updateSales.setInt(1, sales);
    updateSales.setString(2, cof_name);
    updateSales.executeUpdate();
}

At that point, it is then just a matter of calling:

updateSales(75, "Colombian");

Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...

Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

My problem was one of my elements had the xmlns attribute:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE xmlns="blahblah">
        ...
    </RETS-RESPONSE>
</RETS>

No matter what I tried the xmlns attribute seemed to be breaking the serializer, so I removed any trace of xmlns="..." from the xml file:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE>
        ...
    </RETS-RESPONSE>
</RETS>

and voila! Everything worked.

I now parse the xml file to remove this attribute before deserializing. Not sure why this works, maybe my case is different since the element containing the xmlns attribute is not the root element.

What is unit testing and how do you do it?

Unit testing involves breaking your program into pieces, and subjecting each piece to a series of tests.

Usually tests are run as separate programs, but the method of testing varies, depending on the language, and type of software (GUI, command-line, library).

Most languages have unit testing frameworks, you should look into one for yours.

Tests are usually run periodically, often after every change to the source code. The more often the better, because the sooner you will catch problems.

How do I change the default application icon in Java?

    /** Creates new form Java Program1*/
    public Java Program1() 


    Image im = null;
    try {
    im = ImageIO.read(getClass().getResource("/image location"));
    } catch (IOException ex) {
    Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);
    }
    setIconImage(im);

This is what I used in the GUI in netbeans and it worked perfectly

Understanding REST: Verbs, error codes, and authentication

re 1: This looks fine so far. Remember to return the URI of the newly created user in a "Location:" header as part of the response to POST, along with a "201 Created" status code.

re 2: Activation via GET is a bad idea, and including the verb in the URI is a design smell. You might want to consider returning a form on a GET. In a Web app, this would be an HTML form with a submit button; in the API use case, you might want to return a representation that contains a URI to PUT to to activate the account. Of course you can include this URI in the response on POST to /users, too. Using PUT will ensure your request is idempotent, i.e. it can safely be sent again if the client isn't sure about success. In general, think about what resources you can turn your verbs into (sort of "nounification of verbs"). Ask yourself what method your specific action is most closely aligned with. E.g. change_password -> PUT; deactivate -> probably DELETE; add_credit -> possibly POST or PUT. Point the client to the appropriate URIs by including them in your representations.

re 3. Don't invent new status codes, unless you believe they're so generic they merit being standardized globally. Try hard to use the most appropriate status code available (read about all of them in RFC 2616). Include additional information in the response body. If you really, really are sure you want to invent a new status code, think again; if you still believe so, make sure to at least pick the right category (1xx -> OK, 2xx -> informational, 3xx -> redirection; 4xx-> client error, 5xx -> server error). Did I mention that inventing new status codes is a bad idea?

re 4. If in any way possible, use the authentication framework built into HTTP. Check out the way Google does authentication in GData. In general, don't put API keys in your URIs. Try to avoid sessions to enhance scalability and support caching - if the response to a request differs because of something that has happened before, you've usually tied yourself to a specific server process instance. It's much better to turn session state into either client state (e.g. make it part of subsequent requests) or make it explicit by turning it into (server) resource state, i.e. give it its own URI.

How do I list all files of a directory?

I really liked adamk's answer, suggesting that you use glob(), from the module of the same name. This allows you to have pattern matching with *s.

But as other people pointed out in the comments, glob() can get tripped up over inconsistent slash directions. To help with that, I suggest you use the join() and expanduser() functions in the os.path module, and perhaps the getcwd() function in the os module, as well.

As examples:

from glob import glob

# Return everything under C:\Users\admin that contains a folder called wlp.
glob('C:\Users\admin\*\wlp')

The above is terrible - the path has been hardcoded and will only ever work on Windows between the drive name and the \s being hardcoded into the path.

from glob    import glob
from os.path import join

# Return everything under Users, admin, that contains a folder called wlp.
glob(join('Users', 'admin', '*', 'wlp'))

The above works better, but it relies on the folder name Users which is often found on Windows and not so often found on other OSs. It also relies on the user having a specific name, admin.

from glob    import glob
from os.path import expanduser, join

# Return everything under the user directory that contains a folder called wlp.
glob(join(expanduser('~'), '*', 'wlp'))

This works perfectly across all platforms.

Another great example that works perfectly across platforms and does something a bit different:

from glob    import glob
from os      import getcwd
from os.path import join

# Return everything under the current directory that contains a folder called wlp.
glob(join(getcwd(), '*', 'wlp'))

Hope these examples help you see the power of a few of the functions you can find in the standard Python library modules.

Adding elements to object

Try this:

var data = [{field:"Data",type:"date"},  {field:"Numero",type:"number"}];

var columns = {};

var index = 0;

$.each(data, function() {

    columns[index] = {
        field : this.field,
        type : this.type
    };

    index++;
});

console.log(columns);

Is there a C++ gdb GUI for Linux?

I've tried a couple of different guis for gdb and have found DDD to be the better of them. And while I can't comment on other, non-gdb offerings for linux I've used a number of other debuggers on other platforms.

gdb does the majority of the things that you have in your wish list. DDD puts a nicer front on them. For example thread switching is made simpler. Setting breakpoints is as simple as you would expect.

You also get a cli window in case there is something obscure that you want to do.

The one feature of DDD that stands out above any other debugger that I've used is the data "graphing". This allows you to display and arrange structures, objects and memory as draggable boxes. Double clicking a pointer will open up the dereferenced data with visual links back to the parent.

How can I compare two lists in python and return matches

Also you can try this,by keeping common elements in a new list.

new_list = []
for element in a:
    if element in b:
        new_list.append(element)

How to perform element-wise multiplication of two lists?

Yet another answer:

-1 ... requires import
+1 ... is very readable

import operator
a = [1,2,3,4]
b = [10,11,12,13]

list(map(operator.mul, a, b))

outputs [10, 22, 36, 52]

Deleting multiple elements from a list

I can actually think of two ways to do it:

  1. slice the list like (this deletes the 1st,3rd and 8th elements)

    somelist = somelist[1:2]+somelist[3:7]+somelist[8:]

  2. do that in place, but one at a time:

    somelist.pop(2) somelist.pop(0)

QUERY syntax using cell reference

none of the above answers worked for me. This one did:

=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)

VMWare Player vs VMWare Workstation

VM Player runs a virtual instance, but can't create the vm. [Edit: Now it can.] Workstation allows for the creation and administration of virtual machines. If you have a second machine, you can create the vm on one and run it with the player the other machine. I bought Workstation and I use it setup testing vms that the player runs. Hope this explains it for you.

Edit: According to the FAQ:

VMware Workstation is much more advanced and comes with powerful features including snapshots, cloning, remote connections to vSphere, sharing VMs, advanced Virtual Machines settings and much more. Workstation is designed to be used by technical professionals such as developers, quality assurance engineers, systems engineers, IT administrators, technical support representatives, trainers, etc.

npm ERR! network getaddrinfo ENOTFOUND

I also faced this error but I was not working behind a proxy server at the moment so using npm config set proxy=http://address:8080 couldn't help and ~/.npmrc didn't contain any proxy setting either. The solution in my case was just to restart my computer.

Convert/cast an stdClass object to another class

BTW: Converting is highly important if you are serialized, mainly because the de-serialization breaks the type of objects and turns into stdclass, including DateTime objects.

I updated the example of @Jadrovski, now it allows objects and arrays.

example

$stdobj=new StdClass();
$stdobj->field=20;
$obj=new SomeClass();
fixCast($obj,$stdobj);

example array

$stdobjArr=array(new StdClass(),new StdClass());
$obj=array(); 
$obj[0]=new SomeClass(); // at least the first object should indicates the right class.
fixCast($obj,$stdobj);

code: (its recursive). However, i don't know if its recursive with arrays. May be its missing an extra is_array

public static function fixCast(&$destination,$source)
{
    if (is_array($source)) {
        $getClass=get_class($destination[0]);
        $array=array();
        foreach($source as $sourceItem) {
            $obj = new $getClass();
            fixCast($obj,$sourceItem);
            $array[]=$obj;
        }
        $destination=$array;
    } else {
        $sourceReflection = new \ReflectionObject($source);
        $sourceProperties = $sourceReflection->getProperties();
        foreach ($sourceProperties as $sourceProperty) {
            $name = $sourceProperty->getName();
            if (is_object(@$destination->{$name})) {
                fixCast($destination->{$name}, $source->$name);
            } else {
                $destination->{$name} = $source->$name;
            }
        }
    }
}

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

What dependency is missing for org.springframework.web.bind.annotation.RequestMapping?

I was using spring-web version 4.3.7

Changing it to a working 4.1.7 immediately solved it.

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>

Create random list of integers in Python

Firstly, you should use randrange(0,1000) or randint(0,999), not randint(0,1000). The upper limit of randint is inclusive.

For efficiently, randint is simply a wrapper of randrange which calls random, so you should just use random. Also, use xrange as the argument to sample, not range.

You could use

[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]

to generate 10,000 numbers in the range using sample 10 times.

(Of course this won't beat NumPy.)

$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop

$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]' 
100 loops, best of 3: 9.24 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop

$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
>   a = range(x)
>   shuffle(a)
>   return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop

$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop

But since you don't care about the distribution of numbers, why not just use:

range(1000)*(10000/1000)

?

Scheduling Python Script to run every hour accurately

   #For scheduling task execution
import schedule
import time

def job():
    print("I'm working...")

schedule.every(1).minutes.do(job)
#schedule.every().hour.do(job)
#schedule.every().day.at("10:30").do(job)
#schedule.every(5).to(10).minutes.do(job)
#schedule.every().monday.do(job)
#schedule.every().wednesday.at("13:15").do(job)
#schedule.every().minute.at(":17").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

Using SUMIFS with multiple AND OR conditions

You can use DSUM, which will be more flexible. Like if you want to change the name of Salesman or the Quote Month, you need not change the formula, but only some criteria cells. Please see the link below for details...Even the criteria can be formula to copied from other sheets

http://office.microsoft.com/en-us/excel-help/dsum-function-HP010342460.aspx?CTT=1

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

How do I use Safe Area Layout programmatically?

Use constraints with visual format and you get respect for the safe area for free.

class ViewController: UIViewController {

    var greenView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        greenView.backgroundColor = .green
        view.addSubview(greenView)
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        greenView.translatesAutoresizingMaskIntoConstraints = false
        let views : [String:Any] = ["greenView":greenView]
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[greenView]-|", options: [], metrics: nil, views: views))
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[greenView]-|", options: [], metrics: nil, views: views))
    }
}

result

.append(), prepend(), .after() and .before()

There is no extra advantage for each of them. It totally depends on your scenario. Code below shows their difference.

    Before inserts your html here
<div id="mainTabsDiv">
    Prepend inserts your html here
    <div id="homeTabDiv">
        <span>
            Home
        </span>
    </div>
    <div id="aboutUsTabDiv">
        <span>
            About Us
        </span>
    </div>
    <div id="contactUsTabDiv">
        <span>
            Contact Us
        </span>
    </div>
    Append inserts your html here
</div>
After inserts your html here

How to use If Statement in Where Clause in SQL?

Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement

Evaluates a list of conditions and returns one of multiple possible result expressions.

The CASE expression has two formats:

The simple CASE expression compares an expression to a set of simple expressions to determine the result.

The searched CASE expression evaluates a set of Boolean expressions to determine the result.

Both formats support an optional ELSE argument.

Resize UIImage and change the size of UIImageView

Use the category below and then apply border from Quartz into your image:

[yourimage.layer setBorderColor:[[UIColor whiteColor] CGColor]];
[yourimage.layer setBorderWidth:2];

The category: UIImage+AutoScaleResize.h

#import <Foundation/Foundation.h>

@interface UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize;

@end

UIImage+AutoScaleResize.m

#import "UIImage+AutoScaleResize.h"

@implementation UIImage (AutoScaleResize)

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize
{
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor)
        {
            scaleFactor = widthFactor; // scale to fit height
        }
        else
        {
            scaleFactor = heightFactor; // scale to fit width
        }

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
        {
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
    }

    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    return newImage;
}

@end

Trim spaces from end of a NSString

In Swift

To trim space & newline from both side of the String:

var url: String = "\n   http://example.com/xyz.mp4   "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

What does "static" mean in C?

Multi-file variable scope example

Here I illustrate how static affects the scope of function definitions across multiple files.

a.c

#include <stdio.h>

/*
Undefined behavior: already defined in main.
Binutils 2.24 gives an error and refuses to link.
https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
*/
/*int i = 0;*/

/* Works in GCC as an extension: https://stackoverflow.com/a/3692486/895245 */
/*int i;*/

/* OK: extern. Will use the one in main. */
extern int i;

/* OK: only visible to this file. */
static int si = 0;

void a() {
    i++;
    si++;
    puts("a()");
    printf("i = %d\n", i);
    printf("si = %d\n", si);
    puts("");
}

main.c

#include <stdio.h>

int i = 0;
static int si = 0;

void a();    

void m() {
    i++;
    si++;
    puts("m()");
    printf("i = %d\n", i);
    printf("si = %d\n", si);
    puts("");
}

int main() {
    m();
    m();
    a();
    a();
    return 0;
}

GitHub upstream.

Compile and run:

gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o

Output:

m()
i = 1
si = 1

m()
i = 2
si = 2

a()
i = 3
si = 1

a()
i = 4
si = 2

Interpretation

  • there are two separate variables for si, one for each file
  • there is a single shared variable for i

As usual, the smaller the scope, the better, so always declare variables static if you can.

In C programming, files are often used to represent "classes", and static variables represent private static members of the class.

What standards say about it

C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static is a "storage-class specifier".

6.2.2/3 "Linkages of identifiers" says static implies internal linkage:

If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

and 6.2.2/2 says that internal linkage behaves like in our example:

In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.

where "translation unit is a source file after preprocessing.

How GCC implements it for ELF (Linux)?

With the STB_LOCAL binding.

If we compile:

int i = 0;
static int si = 0;

and disassemble the symbol table with:

readelf -s main.o

the output contains:

Num:    Value          Size Type    Bind   Vis      Ndx Name
  5: 0000000000000004     4 OBJECT  LOCAL  DEFAULT    4 si
 10: 0000000000000000     4 OBJECT  GLOBAL DEFAULT    4 i

so the binding is the only significant difference between them. Value is just their offset into the .bss section, so we expect it to differ.

STB_LOCAL is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:

STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other

which makes it a perfect choice to represent static.

Variables without static are STB_GLOBAL, and the spec says:

When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.

which is coherent with the link errors on multiple non static definitions.

If we crank up the optimization with -O3, the si symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static variables on the symbol table at all when there is no optimization? Can they be used for anything? Maybe for debugging.

See also

C++ anonymous namespaces

In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions

Fitting iframe inside a div

I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:

div {
    width: 100%;
    height: 0;
    padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
    position: relative;
}

div iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    display: block;
    top: 0;
    left: 0;
}

Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/

"java.lang.OutOfMemoryError : unable to create new native Thread"

To find which processes are creating threads try:

ps huH

I normally redirect output to a file and analysis the file offline (is thread count for each process is as expected or not)

How do I pass an object from one activity to another on Android?

This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,

class Myclass    {
  int a;
  class SubClass    {
       int b;
  }
}

With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,

MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String

Now you can pass this String across activities as a StringExtra with the activity intent.

Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);

Then in the receiving activity, create the original object from the string representation.

String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object

It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.

UPDATE


While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.

  1. Eventbus
  2. Otto

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

For me it was just a matter of changing the path variable to: 'C:\Program Files\Mozilla Firefox' instead of 'C:\Program Files (x86)\Mozilla Firefox'

SQLAlchemy IN clause

Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.

import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]   
query = sa.text(""" 
                SELECT *
                FROM my_table
                WHERE col1 IN :values; 
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

Javascript swap array elements

According to some random person on Metafilter, "Recent versions of Javascript allow you to do swaps (among other things) much more neatly:"

[ list[x], list[y] ] = [ list[y], list[x] ];

My quick tests showed that this Pythonic code works great in the version of JavaScript currently used in "Google Apps Script" (".gs"). Alas, further tests show this code gives a "Uncaught ReferenceError: Invalid left-hand side in assignment." in whatever version of JavaScript (".js") is used by Google Chrome Version 24.0.1312.57 m.

Jquery-How to grey out the background while showing the loading icon over it

I reworked the example you provided in the js fiddle : http://jsfiddle.net/zravs3hp/

Step 1 :

I renamed your container div to overlay, as semantically this div is not a container, but an overlay. I also placed the loader div as a child of this overlay div.

The resulting html is :

<div class="overlay">
    <div id="loading-img"></div>
</div>


<div class="content">
    <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea velit provident sint aliquid eos omnis aperiam officia architecto error incidunt nemo obcaecati adipisci doloremque dicta neque placeat natus beatae cupiditate minima ipsam quaerat explicabo non reiciendis qui sit. ...</div>
    <button id="button">Submit</button>
</div>

The css of the overlay is the following

.overlay {
    background: #e9e9e9;  <- I left your 'gray' background
    display: none;        <- Not displayed by default
    position: absolute;   <- This and the following properties will
    top: 0;                  make the overlay, the element will expand
    right: 0;                so as to cover the whole body of the page
    bottom: 0;
    left: 0;
    opacity: 0.5;
}

Step 2 :

I added some dummy text so as to have something to overlay.

Step 3 :

Then, in the click handler we just need to show the overlay :

$("#button").click(function () {
    $(".overlay").show();
});

Adding/removing items from a JavaScript object with jQuery

First off, your quoted code is not JSON. Your code is JavaScript object literal notation. JSON is a subset of that designed for easier parsing.

Your code defines an object (data) containing an array (items) of objects (each with an id, name, and type).

You don't need or want jQuery for this, just JavaScript.

Adding an item:

data.items.push(
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

That adds to the end. See below for adding in the middle.

Removing an item:

There are several ways. The splice method is the most versatile:

data.items.splice(1, 3); // Removes three items starting with the 2nd,
                         // ("Witches of Eastwick", "X-Men", "Ordinary People")

splice modifies the original array, and returns an array of the items you removed.

Adding in the middle:

splice actually does both adding and removing. The signature of the splice method is:

removed_items = arrayObject.splice(index, num_to_remove[, add1[, add2[, ...]]]);
  • index - the index at which to start making changes
  • num_to_remove - starting with that index, remove this many entries
  • addN - ...and then insert these elements

So I can add an item in the 3rd position like this:

data.items.splice(2, 0,
    {id: "7", name: "Douglas Adams", type: "comedy"}
);

What that says is: Starting at index 2, remove zero items, and then insert this following item. The result looks like this:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "2", name: "Witches of Eastwick", type: "comedy"},
    {id: "7", name: "Douglas Adams", type: "comedy"},     // <== The new item
    {id: "3", name: "X-Men", type: "action"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

You can remove some and add some at once:

data.items.splice(1, 3,
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"}
);

...which means: Starting at index 1, remove three entries, then add these two entries. Which results in:

var data = {items: [
    {id: "1", name: "Snatch", type: "crime"},
    {id: "7", name: "Douglas Adams", type: "comedy"},
    {id: "8", name: "Dick Francis", type: "mystery"},
    {id: "4", name: "Ordinary People", type: "drama"},
    {id: "5", name: "Billy Elliot", type: "drama"},
    {id: "6", name: "Toy Story", type: "children"}
]};

Infinity symbol with HTML

According to this page, it's &infin;.

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows OS

For Uppercase CTRL + K + U

For Lowercase CTRL + K + L

What are examples of TCP and UDP in real life?

TCP guarantees packet delivery AND order. Order is almost as important as the delivery in the first place when reconstructing data for files such as executables, etc.

UDP does not guarantee delivery NOR order. Packets can arrive (or not!) in any order.

Common uses for TCP include file transfer where the integrity of the packets is paramount. Voice/video applications can afford to lose some data while still maintaining acceptable quality, and so usually use UDP.

Properties private set;

Maybe I'm misunderstanding, but if you want truly readonly Ids why not use an actual readonly field?

public class Person
{
   public Person(int id)
   {
      m_id = id;
   }

   readonly int m_id;
   public int Id { get { return m_id; } }
}

Create JPA EntityManager without persistence.xml configuration file

I was able to create an EntityManager with Hibernate and PostgreSQL purely using Java code (with a Spring configuration) the following:

@Bean
public DataSource dataSource() {
    final PGSimpleDataSource dataSource = new PGSimpleDataSource();

    dataSource.setDatabaseName( "mytestdb" );
    dataSource.setUser( "myuser" );
    dataSource.setPassword("mypass");

    return dataSource;
}

@Bean
public Properties hibernateProperties(){
    final Properties properties = new Properties();

    properties.put( "hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect" );
    properties.put( "hibernate.connection.driver_class", "org.postgresql.Driver" );
    properties.put( "hibernate.hbm2ddl.auto", "create-drop" );

    return properties;
}

@Bean
public EntityManagerFactory entityManagerFactory( DataSource dataSource, Properties hibernateProperties ){
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource( dataSource );
    em.setPackagesToScan( "net.initech.domain" );
    em.setJpaVendorAdapter( new HibernateJpaVendorAdapter() );
    em.setJpaProperties( hibernateProperties );
    em.setPersistenceUnitName( "mytestdomain" );
    em.setPersistenceProviderClass(HibernatePersistenceProvider.class);
    em.afterPropertiesSet();

    return em.getObject();
}

The call to LocalContainerEntityManagerFactoryBean.afterPropertiesSet() is essential since otherwise the factory never gets built, and then getObject() returns null and you are chasing after NullPointerExceptions all day long. >:-(

It then worked with the following code:

PageEntry pe = new PageEntry();
pe.setLinkName( "Google" );
pe.setLinkDestination( new URL( "http://www.google.com" ) );

EntityTransaction entTrans = entityManager.getTransaction();
entTrans.begin();
entityManager.persist( pe );
entTrans.commit();

Where my entity was this:

@Entity
@Table(name = "page_entries")
public class PageEntry {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String linkName;
    private URL linkDestination;

    // gets & setters omitted
}

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

You have just add FormsModule and import the FormsModule in your app.module.ts file.

import { FormsModule } from '@angular/forms';

imports: [
    BrowserModule, FormsModule 
],

Just add the above two lines in your app.module.ts. It's working fine.

function declaration isn't a prototype

In C int foo() and int foo(void) are different functions. int foo() accepts an arbitrary number of arguments, while int foo(void) accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void consistently when you mean no arguments.

If you have a variable a, extern int a; is a way to tell the compiler that a is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern, static) only affects its visibility and extern is the default, so extern is actually unnecessary.

I suggest removing the extern, it is extraneous and is usually omitted.

How do you install Boost on MacOS?

Try +universal

One thing to note: in order for that to make a difference you need to have built python with +universal, if you haven't or you're not sure you can just rebuild python +universal. This applies to both brew as well as macports.

$ brew reinstall python
$ brew install boost

OR

$ sudo port -f uninstall python
$ sudo port install python +universal
$ sudo port install boost +universal

Simplest SOAP example

Thomas:

JSON is preferred for front end use because we have easy lookups. Therefore you have no XML to deal with. SOAP is a pain without using a library because of this. Somebody mentioned SOAPClient, which is a good library, we started with it for our project. However it had some limitations and we had to rewrite large chunks of it. It's been released as SOAPjs and supports passing complex objects to the server, and includes some sample proxy code to consume services from other domains.

How to get domain root url in Laravel 4?

In Laravel 5.1 and later you can use

request()->getHost();

or

request()->getHttpHost();

(the second one will add port if it's not standard one)

How can I determine if an image has loaded, using Javascript/jQuery?

Try something like:

$("#photo").load(function() {
    alert("Hello from Image");
});

Calling a function on bootstrap modal open

will not work.. use $(window) instead

For Showing

$(window).on('shown.bs.modal', function() { 
    $('#code').modal('show');
    alert('shown');
});

For Hiding

$(window).on('hidden.bs.modal', function() { 
    $('#code').modal('hide');
    alert('hidden');
});

What to do on TransactionTooLargeException

Also i was facing this issue for Bitmap data passing from one activity to another but i make a solution by making my data as static data and this is working perfect for me

In activity first :

public static Bitmap bitmap_image;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);
   bitmap_image=mybitmap;
}

and in second activity :

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
   Bitmap mybitmap=first.bitmap_image;
}

How to establish ssh key pair when "Host key verification failed"

Its means your remote host key was changed (May be host password change),

Your terminal suggested to execute this command as root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231

You have to remove that host name from hosts list on your pc/server. Copy that suggested command and execute as a root user.

$ sudo su                                                            // Login as a root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231   // Terminal suggested command execute here
Host [www.website.net]:4231 found: line 16 type ECDSA
/root/.ssh/known_hosts updated.
Original contents retained as /root/.ssh/known_hosts.old

$ exit                                                               // Exist from root user

$ sudo ssh [email protected] -p 4231                              // Try again

I Hope this works.

Convert a video to MP4 (H.264/AAC) with ffmpeg

Software patents led Debian/Ubuntu to disable the H.264 and AAC encoders in ffmpeg. See /usr/share/doc/ffmpeg/README.Debian.gz.

So go install x264, mplayer/mencoder, and Nero's AAC encoder. (Or, if you want to use all Free software, and don't care so much about audio quality, then sudo aptitude install faac.)

I don't remember if the medibuntu package of mencoder includes x264 vid encoding, since I build my own from git x264 and svn mplayer sources. (x264 is very actively developed, with significant quality and speed improvements frequently added.) http://git.videolan.org/?p=x264.git;a=summary

x264 is also packaged, but you should check that it's up to date enough to include weightp with recent bugfixes, and even more recent speed improvements...

Or if you're already willing to convert from .flv, instead of going from the high-quality source the flv was made from, then probably whatever recent version of x264 you can find will be fine.

How do I convert from a string to an integer in Visual Basic?

You can try these:

Dim valueStr as String = "10"

Dim valueIntConverted as Integer = CInt(valueStr)

Another example:

Dim newValueConverted as Integer = Val("100")

How do I make flex box work in safari?

Just tRy this

display: -webkit-box;   /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox;  /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

this worked for me

Detecting iOS / Android Operating system

This issue has already been resolved here : What is the best way to detect a mobile device in jQuery?.

On the accepted answer, they basically test if it's an iPhone, an iPod, an Android device or whatever to return true. Just keep the ones you want for instance if( /Android/i.test(navigator.userAgent) ) { // some code.. } will return true only for Android user-agents.

However, user-agents are not really reliable since they can be changed. The best thing is still to develop something universal for all mobile platforms.

MongoDB vs Firebase

After using Firebase a considerable amount I've come to find something.

If you intend to use it for large, real time apps, it isn't the best choice. It has its own wide array of problems including a bad error handling system and limitations. You will spend significant time trying to understand Firebase and it's kinks. It's also quite easy for a project to become a monolithic thing that goes out of control. MongoDB is a much better choice as far as a backend for a large app goes.

However, if you need to make a small app or quickly prototype something, Firebase is a great choice. It'll be incredibly easy way to hit the ground running.

Anaconda Navigator won't launch (windows 10)

This helped to me:

conda install anaconda-navigator

In Python, how do you convert seconds since epoch to a `datetime` object?

Seconds since epoch to datetime to strftime:

>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'

Insert/Update Many to Many Entity Framework . How do I do it?

In terms of entities (or objects) you have a Class object which has a collection of Students and a Student object that has a collection of Classes. Since your StudentClass table only contains the Ids and no extra information, EF does not generate an entity for the joining table. That is the correct behaviour and that's what you expect.

Now, when doing inserts or updates, try to think in terms of objects. E.g. if you want to insert a class with two students, create the Class object, the Student objects, add the students to the class Students collection add the Class object to the context and call SaveChanges:

using (var context = new YourContext())
{
    var mathClass = new Class { Name = "Math" };
    mathClass.Students.Add(new Student { Name = "Alice" });
    mathClass.Students.Add(new Student { Name = "Bob" });

    context.AddToClasses(mathClass);
    context.SaveChanges();
}

This will create an entry in the Class table, two entries in the Student table and two entries in the StudentClass table linking them together.

You basically do the same for updates. Just fetch the data, modify the graph by adding and removing objects from collections, call SaveChanges. Check this similar question for details.

Edit:

According to your comment, you need to insert a new Class and add two existing Students to it:

using (var context = new YourContext())
{
    var mathClass= new Class { Name = "Math" };
    Student student1 = context.Students.FirstOrDefault(s => s.Name == "Alice");
    Student student2 = context.Students.FirstOrDefault(s => s.Name == "Bob");
    mathClass.Students.Add(student1);
    mathClass.Students.Add(student2);

    context.AddToClasses(mathClass);
    context.SaveChanges();
}

Since both students are already in the database, they won't be inserted, but since they are now in the Students collection of the Class, two entries will be inserted into the StudentClass table.

What's the best way to set a single pixel in an HTML5 canvas?

To complete Phrogz very thorough answer, there is a critical difference between fillRect() and putImageData().
The first uses context to draw over by adding a rectangle (NOT a pixel), using the fillStyle alpha value AND the context globalAlpha and the transformation matrix, line caps etc..
The second replaces an entire set of pixels (maybe one, but why ?)
The result is different as you can see on jsperf.


Nobody wants to set one pixel at a time (meaning drawing it on screen). That is why there is no specific API to do that (and rightly so).
Performance wise, if the goal is to generate a picture (for example a ray-tracing software), you always want to use an array obtained by getImageData() which is an optimized Uint8Array. Then you call putImageData() ONCE or a few times per second using setTimeout/seTInterval.

Regular expression which matches a pattern, or is an empty string

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use

^$|^[^@\s]+@[^@\s]+$

meaning

^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
@         
[^@\s]+
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

How to parse unix timestamp to time.Time

I do a lot of logging where the timestamps are float64 and use this function to get the timestamps as string:

func dateFormat(layout string, d float64) string{
    intTime := int64(d)
    t := time.Unix(intTime, 0)
    if layout == "" {
        layout = "2006-01-02 15:04:05"
    }
    return t.Format(layout)
}

submit the form using ajax

It's much easier to just use jQuery, since this is just a task for university and you do not need to save code.

So, your code will look like:

function sendMyComment() {
    $('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
    $.ajax({
        type: 'POST',
        url: $('#addComment').attr('action'),
        data: $('form').serialize(), 
        success: function(response) { ... },
    });

}

Why is width: 100% not working on div {display: table-cell}?

How about this? (jsFiddle link)

CSS

ul {
    background: #CCC;
    height: 1000%;
    width: 100%;
    list-style-position: outside;
    margin: 0; padding: 0;
    position: absolute;
}
li {
 background-color: #EBEBEB;
    border-bottom: 1px solid #CCCCCC;
    border-right: 1px solid #CCCCCC;
    display: table;
    height: 180px;
    overflow: hidden;
    width: 200px;
}
.divone{
    display: table-cell;
    margin: 0 auto;
    text-align: center;
    vertical-align: middle;
    width: 100%; 

}
img {
    width: 100%;
    height: 410px;
}
.wrapper {
  position: absolute;
}

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

jQuery get content between <div> tags

Give the div a class or id and do something like this:

$("#example").get().innerHTML;

That works at the DOM level.

Laravel - Return json along with http status code

return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity

Hope my answer was helpful.

How to split() a delimited string to a List<String>

Either use:

List<string> list = new List<string>(array);

or from LINQ:

List<string> list = array.ToList();

Or change your code to not rely on the specific implementation:

IList<string> list = array; // string[] implements IList<string>

Fastest way to convert an iterator to a list

@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:

  1. by type constructor

list(my_iterator)

  1. by unpacking

[*my_iterator]

  1. using list comprehension

[e for e in my_iterator]

I have been using simple_bechmark library

from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest

b = BenchmarkBuilder()

@b.add_function()
def convert_by_type_constructor(size):
    list(iter(range(size)))

@b.add_function()
def convert_by_list_comprehension(size):
    [e for e in iter(range(size))]

@b.add_function()
def convert_by_unpacking(size):
    [*iter(range(size))]


@b.add_arguments('Convert an iterator to a list')
def argument_provider():
    for exp in range(2, 22):
        size = 2**exp
        yield size, size

r = b.run()
r.plot()

enter image description here

As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.


I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:

import argparse
import timeit

parser = argparse.ArgumentParser(
    description='Test convert iterator to list')
parser.add_argument(
    '--size', help='The number of elements from iterator')

args = parser.parse_args()

size = int(args.size)
repeat_number = 10000

# do not wait too much if the size is too big
if size > 10000:
    repeat_number = 100


def test_convert_by_type_constructor():
    list(iter(range(size)))


def test_convert_by_list_comprehension():
    [e for e in iter(range(size))]


def test_convert_by_unpacking():
    [*iter(range(size))]


def get_avg_time_in_ms(func):
    avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
    return round(avg_time, 6)


funcs = [test_convert_by_type_constructor,
         test_convert_by_unpacking, test_convert_by_list_comprehension]

print(*map(get_avg_time_in_ms, funcs))

The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.

from subprocess import PIPE, run

import pandas

simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
        'size': [], 'python version': []}


size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
    print('test for python', version)
    for size in size_test:
        command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        constructor, unpacking,  comprehension = result.stdout.split()
        
        simple_data['constructor'].append(float(constructor))
        simple_data['unpacking'].append(float(unpacking))
        simple_data['comprehension'].append(float(comprehension))
        simple_data['python version'].append(version)
        simple_data['size'].append(size)

df_ = pandas.DataFrame(simple_data)
df_

enter image description here

You can get my full notebook from here.

In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.

How can I force component to re-render with hooks in React?

Alternative to @MinhKha's answer:

It can be much cleaner with useReducer:

const [, forceUpdate] = useReducer(x => x + 1, 0);

Usage: forceUpdate() - cleaner without params

How to go to a specific element on page?

If the element is currently not visible on the page, you can use the native scrollIntoView() method.

$('#div_' + element_id)[0].scrollIntoView( true );

Where true means align to the top of the page, and false is align to bottom.

Otherwise, there's a scrollTo() plugin for jQuery you can use.

Or maybe just get the top position()(docs) of the element, and set the scrollTop()(docs) to that position:

var top = $('#div_' + element_id).position().top;
$(window).scrollTop( top );

Extract filename and extension in Bash

Here are some alternative suggestions (mostly in awk), including some advanced use cases, like extracting version numbers for software packages.

f='/path/to/complex/file.1.0.1.tar.gz'

# Filename : 'file.1.0.x.tar.gz'
    echo "$f" | awk -F'/' '{print $NF}'

# Extension (last): 'gz'
    echo "$f" | awk -F'[.]' '{print $NF}'

# Extension (all) : '1.0.1.tar.gz'
    echo "$f" | awk '{sub(/[^.]*[.]/, "", $0)} 1'

# Extension (last-2): 'tar.gz'
    echo "$f" | awk -F'[.]' '{print $(NF-1)"."$NF}'

# Basename : 'file'
    echo "$f" | awk '{gsub(/.*[/]|[.].*/, "", $0)} 1'

# Basename-extended : 'file.1.0.1.tar'
    echo "$f" | awk '{gsub(/.*[/]|[.]{1}[^.]+$/, "", $0)} 1'

# Path : '/path/to/complex/'
    echo "$f" | awk '{match($0, /.*[/]/, a); print a[0]}'
    # or 
    echo "$f" | grep -Eo '.*[/]'

# Folder (containing the file) : 'complex'
    echo "$f" | awk -F'/' '{$1=""; print $(NF-1)}'

# Version : '1.0.1'
    # Defined as 'number.number' or 'number.number.number'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?'

    # Version - major : '1'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?' | cut -d. -f1

    # Version - minor : '0'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?' | cut -d. -f2

    # Version - patch : '1'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?' | cut -d. -f3

# All Components : "path to complex file 1 0 1 tar gz"
    echo "$f" | awk -F'[/.]' '{$1=""; print $0}'

# Is absolute : True (exit-code : 0)
    # Return true if it is an absolute path (starting with '/' or '~/'
    echo "$f" | grep -q '^[/]\|^~/'

All use cases are using the original full path as input, without depending on intermediate results.

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

How to write loop in a Makefile?

The following will do it if, as I assume by your use of ./a.out, you're on a UNIX-type platform.

for number in 1 2 3 4 ; do \
    ./a.out $$number ; \
done

Test as follows:

target:
    for number in 1 2 3 4 ; do \
        echo $$number ; \
    done

produces:

1
2
3
4

For bigger ranges, use:

target:
    number=1 ; while [[ $$number -le 10 ]] ; do \
        echo $$number ; \
        ((number = number + 1)) ; \
    done

This outputs 1 through 10 inclusive, just change the while terminating condition from 10 to 1000 for a much larger range as indicated in your comment.

Nested loops can be done thus:

target:
    num1=1 ; while [[ $$num1 -le 4 ]] ; do \
        num2=1 ; while [[ $$num2 -le 3 ]] ; do \
            echo $$num1 $$num2 ; \
            ((num2 = num2 + 1)) ; \
        done ; \
        ((num1 = num1 + 1)) ; \
    done

producing:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3

REST API error code 500 handling

You suggested "Catching any unexpected errors and return some error code signaling "unexpected situation" " but couldn't find an appropriate error code.

Guess what: That's what 5xx is there for.

Duplicate keys in .NET dictionaries?

The NameValueCollection supports multiple string values under one key (which is also a string), but it is the only example I am aware of.

I tend to create constructs similar to the one in your example when I run into situations where I need that sort of functionality.

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

Use this:

plt.figure(figsize=(width,height))

The width and height are in inches.
If not provided, defaults to rcParams["figure.figsize"] = [6.4, 4.8]. See more here.

Python: Is there an equivalent of mid, right, and left from BASIC?

Thanks Andy W

I found that the mid() did not quite work as I expected and I modified as follows:

def mid(s, offset, amount):
    return s[offset-1:offset+amount-1]

I performed the following test:

print('[1]23', mid('123', 1, 1))
print('1[2]3', mid('123', 2, 1))
print('12[3]', mid('123', 3, 1))
print('[12]3', mid('123', 1, 2))
print('1[23]', mid('123', 2, 2))

Which resulted in:

[1]23 1
1[2]3 2
12[3] 3
[12]3 12
1[23] 23

Which was what I was expecting. The original mid() code produces this:

[1]23 2
1[2]3 3
12[3] 
[12]3 23
1[23] 3

But the left() and right() functions work fine. Thank you.

What is default list styling (CSS)?

I think this is actually what you're looking for:

.my_container ul
{
    list-style: initial;
    margin: initial;
    padding: 0 0 0 40px;
}

.my_container li
{
    display: list-item;
}

Variable length (Dynamic) Arrays in Java

I disagree with the previous answers suggesting ArrayList, because ArrayList is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:

ArrayList list = new ArrayList(4);
list.put(3,"Test");

It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance

How to wait until WebBrowser is completely loaded in VB.NET?

I made similar function (only that works to me); sorry it is in C# but easy to translate...

private void WaitForPageLoad () {

     while (pageReady == false)
         Application.DoEvents();

     while (webBrowser1.IsBusy || webBrowser1.ReadyState != WebBrowserReadyState.Complete)
         Application.DoEvents();
}

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

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

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

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

What's the complete range for Chinese characters in Unicode?

To summarize, it sounds like these are them:

var blocks = [
  [0x3400, 0x4DB5],
  [0x4E00, 0x62FF],
  [0x6300, 0x77FF],
  [0x7800, 0x8CFF],
  [0x8D00, 0x9FCC],
  [0x2e80, 0x2fd5],
  [0x3190, 0x319f],
  [0x3400, 0x4DBF],
  [0x4E00, 0x9FCC],
  [0xF900, 0xFAAD],
  [0x20000, 0x215FF],
  [0x21600, 0x230FF],
  [0x23100, 0x245FF],
  [0x24600, 0x260FF],
  [0x26100, 0x275FF],
  [0x27600, 0x290FF],
  [0x29100, 0x2A6DF],
  [0x2A700, 0x2B734],
  [0x2B740, 0x2B81D]
]

CSS change button style after click

Each link has five different states: link, hover, active, focus and visited.

Link is the normal appearance, hover is when you mouse over, active is the state when it's clicked, focus follows active and visited is the state you end up when you unfocus the recently clicked link.

I'm guessing you want to achieve a different style on either focus or visited, then you can add the following CSS:

a { color: #00c; }
a:visited { #ccc; }
a:focus { #cc0; }

A recommended order in your CSS to not cause any trouble is the following:

a
a:visited { ... }
a:focus { ... }
a:hover { ... }
a:active { ... }

You can use your web browser's developer tools to force the states of the element like this (Chrome->Developer Tools/Inspect Element->Style->Filter :hov): Force state in Chrome Developer Tools

How to convert Java String into byte[]?

Simply:

String abc="abcdefghight";

byte[] b = abc.getBytes();

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

To demonstrate how this works--

CREATE TABLE T1 (ID INT NOT NULL, SomeVal CHAR(1));
ALTER TABLE T1 ADD CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED (ID);

CREATE TABLE T2 (FKID INT, SomeOtherVal CHAR(2));

INSERT T1 (ID, SomeVal) SELECT 1, 'A';
INSERT T1 (ID, SomeVal) SELECT 2, 'B';

INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A1';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A2';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B1';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B2';
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C1';  --orphan
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C2';  --orphan

--Add the FK CONSTRAINT will fail because of existing orphaned records
ALTER TABLE T2 ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID);   --fails

--Same as ADD above, but explicitly states the intent to CHECK the FK values before creating the CONSTRAINT
ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID);    --fails

--Add the CONSTRAINT without checking existing values
ALTER TABLE T2 WITH NOCHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID);  --succeeds
ALTER TABLE T2 CHECK CONSTRAINT FK_T2_T1;   --succeeds since the CONSTRAINT is attributed as NOCHECK

--Attempt to enable CONSTRAINT fails due to orphans
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1;    --fails

--Remove orphans
DELETE FROM T2 WHERE FKID NOT IN (SELECT ID FROM T1);

--Enabling the CONSTRAINT succeeds
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1;    --succeeds; orphans removed

--Clean up
DROP TABLE T2;
DROP TABLE T1;

int to hex string

Try the following:

ToString("X4")

See The X format specifier on MSDN.

Change the color of a bullet in a html list?

<ul>
<li style="color:#ddd;"><span style="color:#000;">List Item</span></li>
</ul>

Excel VBA Password via Hex Editor

If you deal with .xlsm file instead of .xls you can use the old method. I was trying to modify vbaProject.bin in .xlsm several times using DBP->DBx method by it didn't work, also changing value of DBP didn't. So I was very suprised that following worked :
1. Save .xlsm as .xls.
2. Use DBP->DBx method on .xls.
3. Unfortunately some erros may occur when using modified .xls file, I had to save .xls as .xlsx and add modules, then save as .xlsm.

HTML5 Canvas Resize (Downscale) Image High Quality?

Suggestion 1 - extend the process pipe-line

You can use step-down as I describe in the links you refer to but you appear to use them in a wrong way.

Step down is not needed to scale images to ratios above 1:2 (typically, but not limited to). It is where you need to do a drastic down-scaling you need to split it up in two (and rarely, more) steps depending on content of the image (in particular where high-frequencies such as thin lines occur).

Every time you down-sample an image you will loose details and information. You cannot expect the resulting image to be as clear as the original.

If you are then scaling down the images in many steps you will loose a lot of information in total and the result will be poor as you already noticed.

Try with just one extra step, or at tops two.

Convolutions

In case of Photoshop notice that it applies a convolution after the image has been re-sampled, such as sharpen. It's not just bi-cubic interpolation that takes place so in order to fully emulate Photoshop we need to also add the steps Photoshop is doing (with the default setup).

For this example I will use my original answer that you refer to in your post, but I have added a sharpen convolution to it to improve quality as a post process (see demo at bottom).

Here is code for adding sharpen filter (it's based on a generic convolution filter - I put the weight matrix for sharpen inside it as well as a mix factor to adjust the pronunciation of the effect):

Usage:

sharpen(context, width, height, mixFactor);

The mixFactor is a value between [0.0, 1.0] and allow you do downplay the sharpen effect - rule-of-thumb: the less size the less of the effect is needed.

Function (based on this snippet):

function sharpen(ctx, w, h, mix) {

    var weights =  [0, -1, 0,  -1, 5, -1,  0, -1, 0],
        katet = Math.round(Math.sqrt(weights.length)),
        half = (katet * 0.5) |0,
        dstData = ctx.createImageData(w, h),
        dstBuff = dstData.data,
        srcBuff = ctx.getImageData(0, 0, w, h).data,
        y = h;
        
    while(y--) {

        x = w;

        while(x--) {

            var sy = y,
                sx = x,
                dstOff = (y * w + x) * 4,
                r = 0, g = 0, b = 0, a = 0;

            for (var cy = 0; cy < katet; cy++) {
                for (var cx = 0; cx < katet; cx++) {

                    var scy = sy + cy - half;
                    var scx = sx + cx - half;

                    if (scy >= 0 && scy < h && scx >= 0 && scx < w) {

                        var srcOff = (scy * w + scx) * 4;
                        var wt = weights[cy * katet + cx];

                        r += srcBuff[srcOff] * wt;
                        g += srcBuff[srcOff + 1] * wt;
                        b += srcBuff[srcOff + 2] * wt;
                        a += srcBuff[srcOff + 3] * wt;
                    }
                }
            }

            dstBuff[dstOff] = r * mix + srcBuff[dstOff] * (1 - mix);
            dstBuff[dstOff + 1] = g * mix + srcBuff[dstOff + 1] * (1 - mix);
            dstBuff[dstOff + 2] = b * mix + srcBuff[dstOff + 2] * (1 - mix)
            dstBuff[dstOff + 3] = srcBuff[dstOff + 3];
        }
    }

    ctx.putImageData(dstData, 0, 0);
}

The result of using this combination will be:

ONLINE DEMO HERE

Result downsample and sharpen convolution

Depending on how much of the sharpening you want to add to the blend you can get result from default "blurry" to very sharp:

Variations of sharpen

Suggestion 2 - low level algorithm implementation

If you want to get the best result quality-wise you'll need to go low-level and consider to implement for example this brand new algorithm to do this.

See Interpolation-Dependent Image Downsampling (2011) from IEEE.
Here is a link to the paper in full (PDF).

There are no implementations of this algorithm in JavaScript AFAIK of at this time so you're in for a hand-full if you want to throw yourself at this task.

The essence is (excerpts from the paper):

Abstract

An interpolation oriented adaptive down-sampling algorithm is proposed for low bit-rate image coding in this paper. Given an image, the proposed algorithm is able to obtain a low resolution image, from which a high quality image with the same resolution as the input image can be interpolated. Different from the traditional down-sampling algorithms, which are independent from the interpolation process, the proposed down-sampling algorithm hinges the down-sampling to the interpolation process. Consequently, the proposed down-sampling algorithm is able to maintain the original information of the input image to the largest extent. The down-sampled image is then fed into JPEG. A total variation (TV) based post processing is then applied to the decompressed low resolution image. Ultimately, the processed image is interpolated to maintain the original resolution of the input image. Experimental results verify that utilizing the downsampled image by the proposed algorithm, an interpolated image with much higher quality can be achieved. Besides, the proposed algorithm is able to achieve superior performance than JPEG for low bit rate image coding.

Snapshot from paper

(see provided link for all details, formulas etc.)

Node.js global proxy setting

replace {userid} and {password} with your id and password in your organization or login to your machine.

npm config set proxy http://{userid}:{password}@proxyip:8080/
npm config set https-proxy http://{userid}:{password}@proxyip:8080/
npm config set http-proxy http://{userid}:{password}@proxyip:8080/
strict-ssl=false

Making a triangle shape using xml definitions?

You can add following triangle in background using following xml

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="100dp"
    android:width="100dp"
    android:viewportHeight="100"
    android:viewportWidth="100" >
    <group
        android:name="triableGroup">
        <path
            android:name="triangle"
            android:fillColor="#848af8"
            android:pathData="M 0,20 L 0,0 L 100,0 L 100,20 L 54,55  l -1,0.6  l -1,0.4  l -1,0.2  l -1,0   l -1,-0  l -1,-0.2  l -1,-0.4  l -1,-0.6    L 46,55   L 0,20 -100,-100 Z" />
    </group>
</vector>

The whole logic to customize xml design is in pathData. Consider top-left as (0,0) and design the layout as per your requirement. Check this answer.

ng-if check if array is empty

To overcome the null / undefined issue, try using the ? operator to check existence:

<p ng-if="post?.capabilities?.items?.length > 0">
  • Sidenote, if anyone got to this page looking for an Ionic Framework answer, ensure you use *ngIf:

    <p *ngIf="post?.capabilities?.items?.length > 0">
    

How to remove RVM (Ruby Version Manager) from my system

There's a simple command built-in that will pull it:

rvm implode

This will remove the rvm/ directory and all the rubies built within it. In order to remove the final trace of rvm, you need to remove the rvm gem, too:

gem uninstall rvm

If you've made modifications to your PATH you might want to pull those, too. Check your .bashrc, .profile and .bash_profile files, among other things.

You may also have an /etc/rvmrc file, or one in your home directory ~/.rvmrc that may need to be removed as well.

Error: allowDefinition='MachineToApplication' beyond application level

This error occurs when you attempt to open a project as a website. The easiest way to determine if you've created a website or a project is to check your solution folder (i.e. where you saved your code) and see if you have a *.sln file in the root directory, if you do then you've created a project.

Just to add, I encountered this error just now when I attempted to open a project I created a while back by selecting "File", "Open Website" from the Visual Studio menus whereas I should have selected "File", "Open Project" instead. I facepalmed as soon as I realised :)

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

BASH Syntax error near unexpected token 'done'

Edit your code in any linux environment then you won't face this problem. If edit in windows notepad any space take it as ^M.

Node.js Error: connect ECONNREFUSED

People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:

ps aux | grep node

This will print something along the lines of:

user    7668  4.3  1.0  42060 10708 pts/1    Sl+  20:36   0:00 node server
user    7749  0.0  0.0   4384   832 pts/8    S+   20:37   0:00 grep --color=auto node

In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668.

How to show all of columns name on pandas dataframe?

To obtain all the column names of a DataFrame, df_data in this example, you just need to use the command df_data.columns.values. This will show you a list with all the Column names of your Dataframe

Code:

df_data=pd.read_csv('../input/data.csv')
print(df_data.columns.values)

Output:

['PassengerId' 'Survived' 'Pclass' 'Name' 'Sex' 'Age' 'SibSp' 'Parch' 'Ticket' 'Fare' 'Cabin' 'Embarked']

Django, creating a custom 500/404 error page

Official answer:

Here is the link to the official documentation on how to set up custom error views:

https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views

It says to add lines like these in your URLconf (setting them anywhere else will have no effect):

handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'

You can also customise the CSRF error view by modifying the setting CSRF_FAILURE_VIEW.

Default error handlers:

It's worth reading the documentation of the default error handlers, page_not_found, server_error, permission_denied and bad_request. By default, they use these templates if they can find them, respectively: 404.html, 500.html, 403.html, and 400.html.

So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS directory, you don't need to edit URLConf at all. Read the documentation to see which context variables are available.

In Django 1.10 and later, the default CSRF error view uses the template 403_csrf.html.

Gotcha:

Don't forget that DEBUG must be set to False for these to work, otherwise, the normal debug handlers will be used.

Camera access through browser

You could try this:

<input type="file" capture="camera" accept="image/*" id="cameraInput" name="cameraInput">

but it has to be iOS 6+ to work. That will give you a nice dialogue for you to choose either to take a picture or to upload one from your album i.e.

Screenhot

An example can be found here: Capturing camera/picture data without PhoneGap

Select records from NOW() -1 Day

Sure you can:

SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)

indexOf method in an object array?

I did some performance testing of various answers here, which anyone can run them self:

https://jsperf.com/find-index-of-object-in-array-by-contents

Based on my initial tests in Chrome, the following method (using a for loop set up inside a prototype) is the fastest:

Array.prototype.indexOfObject = function (property, value) {
    for (var i = 0, len = this.length; i < len; i++) {
        if (this[i][property] === value) return i;
    }
    return -1;
}

myArray.indexOfObject("hello", "stevie");

This code is a slightly modified version of Nathan Zaetta's answer.

In the performance benchmarks I tried it with both the target being in the middle (index 500) and very end (index 999) of a 1000 object array, and even if I put the target in as the very last item in the array (meaning that it it has to loop through every single item in the array before it's found) it still ends up the fastest.

This solution also has the benefit of being one of the most terse for repeatedly executing, since only the last line needs to be repeated:

myArray.indexOfObject("hello", "stevie");

Section vs Article HTML5

Article and Section are both semantic elements of HTML5. Section is block level generic section of a webpage, but relevant to our webpage content. Article is also block level, but article refers to an individual blog post, a comment, of a webpage.

Both Article and Section should include an heading elements h2-h6.

For a blog post, use following syntax for article and section.

<article role="main">
         <h1>Heading 1</h1>
         <p>Article Description</p>
         <section id="sec1">
                <h2>Section Heading</h2>
                <p>Section Description</p>
         </section>
         <section id="sec2">
                <h2>Section Heading</h2>
                <p>Section Description</p>
         </section>
</article>

How to align the checkbox and label in same line in html?

Use below css to align Label with Checkbox

    .chkbox label
            {
                position: relative;
                top: -2px;
            }

<div class="chkbox">
<asp:CheckBox ID="Ckbox" runat="server" Text="Check Box Alignment"/>
</div>

Counting words in string

function totalWordCount() {
  var str ="My life is happy"
  var totalSoFar = 0;

  for (var i = 0; i < str.length; i++)
    if (str[i] === " ") { 
     totalSoFar = totalSoFar+1;
  }
  totalSoFar = totalSoFar+ 1; 
  return totalSoFar
}

console.log(totalWordCount());

Check if datetime instance falls in between other two datetime objects

Write yourself a Helper function:

public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
    return dt >= start && dt <= end;
}

Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));

Difference between jQuery .hide() and .css("display", "none")

Difference between show() and css({'display':'block'})

Assuming you have this at the beginning:

<span id="thisElement" style="display: none;">Foo</span>

when you call:

$('#thisElement').show();

you will get:

<span id="thisElement" style="">Foo</span>

while:

$('#thisElement').css({'display':'block'});

does:

<span id="thisElement" style="display: block;">Foo</span>

so, yes there's a difference.

Difference between hide() and css({'display':'none'})

same as above but change these into hide() and display':'none'......

Another difference When .hide() is called the value of the display property is saved in jQuery's data cache, so when .show() is called, the initial display value is restored!

Readably print out a python dict() sorted by key

Actually pprint seems to sort the keys for you under python2.5

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}

But not always under python 2.4

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}
>>> 

Reading the source code of pprint.py (2.5) it does sort the dictionary using

items = object.items()
items.sort()

for multiline or this for single line

for k, v in sorted(object.items()):

before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.

So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.

Python3 Update

Pretty print by sorted keys (lambda x: x[0]):

for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
    print("{} : {}".format(key, value))

Pretty print by sorted values (lambda x: x[1]):

for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
    print("{} : {}".format(key, value))

how to convert from int to char*?

C-style solution could be to use itoa, but better way is to print this number into string by using sprintf / snprintf. Check this question: How to convert an integer to a string portably?

Note that itoa function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. It's a non-standard function, thus you should avoid using it. Check this question too: Alternative to itoa() for converting integer to string C++?

Also note that writing C-style code while programming in C++ is considered bad practice and sometimes referred as "ghastly style". Do you really want to convert it into C-style char* string? :)

Install msi with msiexec in a Specific Directory

This should work:

msiexec /i "msi path" TARGETDIR="C:\myfolder" /qb

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

Excel function to make SQL-like queries on worksheet data?

If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools

Example, function BS_SQL("SELECT ..."):

enter image description here

How do you attach and detach from Docker's process?

If you just want to make some modification to files or inspect processes, here's one another solution you probably want.

You could run the following command to execute a new process from the existing container:

sudo docker exec -ti [CONTAINER-ID] bash

will start a new process with bash shell, and you could escape from it by Ctrl+C directly, it won't affect the original process.

What's the difference between 'r+' and 'a+' when open file in python?

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : -

  • r+ : - Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ : - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

Unzipping files

I wrote an unzipper in Javascript. It works.

It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet. I added the ZipFile class.

working example:
http://cheeso.members.winisp.net/Unzip-Example.htm (dead link)

The source:
http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link)

NB: the links are dead; I'll find a new host soon.

Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there.


Here's what the application code looks like in Javascript:

// In my demo, this gets attached to a click event.
// it instantiates a ZipFile, and provides a callback that is
// invoked when the zip is read.  This can take a few seconds on a
// large zip file, so it's asynchronous. 
var readFile = function(){
    $("#status").html("<br/>");
    var url= $("#urlToLoad").val();
    var doneReading = function(zip){
        extractEntries(zip);
    };

    var zipFile = new ZipFile(url, doneReading);
};


// this function extracts the entries from an instantiated zip
function extractEntries(zip){
    $('#report').accordion('destroy');

    // clear
    $("#report").html('');

    var extractCb = function(id) {
        // this callback is invoked with the entry name, and entry text
        // in my demo, the text is just injected into an accordion panel.
        return (function(entryName, entryText){
            var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>");
            $("#"+id).html(content);
            $("#status").append("extract cb, entry(" + entryName + ")  id(" + id + ")<br/>");
            $('#report').accordion('destroy');
            $('#report').accordion({collapsible:true, active:false});
        });
    }

    // for each entry in the zip, extract it. 
    for (var i=0; i<zip.entries.length;  i++) {
        var entry = zip.entries[i];

        var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>";

        // contrive an id for the entry, make it unique
        var randomId = "id-"+ Math.floor((Math.random() * 1000000000));

        entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId +
            "'></span></span></div>\n";

        // insert the info for one entry as the last child within the report div
        $("#report").append(entryInfo);

        // extract asynchronously
        entry.extract(extractCb(randomId));
    }
}

The demo works in a couple of steps: The readFile fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries, which just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc).

The extractEntries fn iterates over all entries, and calls extract() on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown).


It works, but I think that the utility is somewhat limited.

For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT: The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage.

For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file.

Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. (EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser.

I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too.


EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things.

So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Get HTML inside iframe using jQuery

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

Is Python interpreted, or compiled, or both?

For newbies

Python automatically compiles your script to compiled code, so called byte code, before running it.

Running a script is not considered an import and no .pyc will be created.

For example, if you have a script file abc.py that imports another module xyz.py, when you run abc.py, xyz.pyc will be created since xyz is imported, but no abc.pyc file will be created since abc.py isn’t being imported.

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

The answers are provided here amazing, but if you are new in that and you don't realize full error then you may see at the end of that error net/http: TLS handshake timeout. message means that you have a slow internet connection. So it can be only that problem that's it. Toodles

PPT to PNG with transparent background

I just tried to make a transparent image with powerpoint after failing miserably with other online systems. I was successful. Amazing.

First I used word art to give me typefaces which convert well to PNG or JPEG. The ordinary text in powerpoint does not convert well. It gets fuzzy. Anyway, I typed in my words in white (my choice of colour as i wanted it against a navy blue background), arranged it how i wanted, then right clicked and selected format shape to remove lines, then shadow to set the transparency.

I took the transparency to 100%. It came out fine. i then right clicked to save as png. Opened the image with MS Picture manager and resized the image to my suiting. It did not come out with the powerpoint white background at all. Once resized, i dropped the image against my navy blue background and it was like magic.

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

Regular Expression to match every new line character (\n) inside a <content> tag

Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:

<!-- <content> blah </content> -->

You can take two approaches here:

  1. Strip all comments out first. Then use the regex approach.
  2. Do not use regular expressions and use a context sensitive parsing approach that can keep track of whether or not you are nested in a comment.

Be careful.

I am also not so sure you can match all new lines at once. @Quartz suggested this one:

<content>([^\n]*\n+)+</content>

This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:

<content>.*</content>

BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.

I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.

I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...

UPDATE 1:

Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):

To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.

Similarly, to search for content tags, use: .*?

Also, You may be able to try this out, and access each newline character with the match objects groups():

<content>(.*?(\n))+.*?</content>

I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.

UPDATE 2:

So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:

#!/usr/bin/python

import re

def FindContentNewlines(xml_text):
    # May want to compile these regexes elsewhere, but I do it here for brevity
    comments = re.compile(r"<!--.*?-->", re.DOTALL)
    content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
    newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)

    # strip comments: this actually may not be reliable for "nested comments"
    # How does xml handle <!--  <!-- --> -->. I am not sure. But that COULD
    # be trouble.
    xml_text = re.sub(comments, "", xml_text)

    result = []
    all_contents = re.findall(content, xml_text)
    for c in all_contents:
        result.extend(re.findall(newlines, c))

    return result

if __name__ == "__main__":
    example = """

<!-- This stuff
ought to be omitted
<content>
  omitted
</content>
-->

This stuff is good
<content>
<p>
  haha!
</p>
</content>

This is not found
"""
    print FindContentNewlines(example)

This program prints the result:

 ['', '<p>', '  haha!', '</p>', '']

The first and last empty strings come from the newline chars immediately preceeding the first <p> and the one coming right after the </p>. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.

Hope this helps :-).

PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.

How to Set a Custom Font in the ActionBar Title?

I agree that this isn't completely supported, but here's what I did. You can use a custom view for your action bar (it will display between your icon and your action items). I'm using a custom view and I have the native title disabled. All of my activities inherit from a single activity, which has this code in onCreate:

this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);

LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);

//if you need to customize anything else about the text, do it here.
//I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());

//assign the view to the actionbar
this.getActionBar().setCustomView(v);

And my layout xml (R.layout.titleview in the code above) looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

<com.your.package.CustomTextView
        android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp"
            android:maxLines="1"
            android:ellipsize="end"
            android:text="" />
</RelativeLayout>

Match two strings in one line with grep

grep ‘string1\|string2’ FILENAME 

GNU grep version 3.1

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

How to keep keys/values in same order as declared?

I came across this post while trying to figure out how to get OrderedDict to work. PyDev for Eclipse couldn't find OrderedDict at all, so I ended up deciding to make a tuple of my dictionary's key values as I would like them to be ordered. When I needed to output my list, I just iterated through the tuple's values and plugged the iterated 'key' from the tuple into the dictionary to retrieve my values in the order I needed them.

example:

test_dict = dict( val1 = "hi", val2 = "bye", val3 = "huh?", val4 = "what....")
test_tuple = ( 'val1', 'val2', 'val3', 'val4')
for key in test_tuple: print(test_dict[key])

It's a tad cumbersome, but I'm pressed for time and it's the workaround I came up with.

note: the list of lists approach that somebody else suggested does not really make sense to me, because lists are ordered and indexed (and are also a different structure than dictionaries).

C - casting int to char and append char to char

Casting int to char is done simply by assigning with the type in parenthesis:

int i = 65535;
char c = (char)i;

Note: I thought that you might be losing data (as in the example), because the type sizes are different.

Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h> functions like strcat or sprintf.

Playing a MP3 file in a WinForm application

You can do it using old DirectShow functionality.

This answer teaches you how to create QuartzTypeLib.dll:

  1. Run tlbimp tool (in your case path will be different):

  2. Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll

Alternatively, this project contains the library interop.QuartzTypeLib.dll, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:

  1. Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")

  2. In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).

  3. In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266

  4. Use this class to play your favorite MP3 file:

    using QuartzTypeLib;
    
    public sealed class DirectShowPlayer
    {
        private FilgraphManager FilterGraph;
    
        public void Play(string path)
        {
            FilgraphManager = new FilgraphManager();
            FilterGraph.RenderFile(path);
            FilterGraph.Run();
        }
    
        public void Stop()
        {
            FilterGraph?.Stop();
        }
    }
    

PS: TlbImp.exe can be found here: "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin", or in "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"

How to implement a Navbar Dropdown Hover in Bootstrap v4?

Google brought me here but... The examples provided work if the dropdown menu is overlaping (at least by 1px) with its parent when show. If not, it loses focus and nothing works as intended.

Here is a working solution with jQuery and Bootstrap 4.5.2 :

$('li.nav-item').mouseenter(function (e) {

        e.stopImmediatePropagation();

        if ($(this).hasClass('dropdown')) {

            // target element containing dropdowns, show it
            $(this).addClass('show');
            $(this).find('.dropdown-menu').addClass('show');

            // Close dropdown on mouseleave
            $('.dropdown-menu').mouseleave(function (e) {
                e.stopImmediatePropagation();
                $(this).removeClass('show');
            });

            // If you have a prenav above, this clears open dropdowns (since you probably will hover the nav-item going up and it will reopen its dropdown otherwise)
            $('#prenav').off().mouseenter(function (e) {
                e.stopImmediatePropagation();
                $('.dropdown-menu').removeClass('show');
            });

        } else {
            // unset open dropdowns if hover is on simple nav element
            $('.dropdown-menu').removeClass('show');
        }
    });

Change <select>'s option and trigger events with JavaScript

The whole creating and dispatching events works, but since you are using the onchange attribute, your life can be a little simpler:

http://jsfiddle.net/xwywvd1a/3/

var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();

If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

If you're targeting HTML5 only you can use:

<input type="text" id="firstname" placeholder="First Name:" />

For non HTML5 browsers, I would build upon Floern's answer by using jQuery and make the javascript non-obtrusive. I would also use a class to define the blurred properties.

$(document).ready(function () {

    //Set the initial blur (unless its highlighted by default)
    inputBlur($('#Comments'));

    $('#Comments').blur(function () {
        inputBlur(this);
    });
    $('#Comments').focus(function () {
        inputFocus(this);
    });

})

Functions:

function inputFocus(i) {
    if (i.value == i.defaultValue) {
        i.value = "";
        $(i).removeClass("blurredDefaultText");
    }
}
function inputBlur(i) {
    if (i.value == "" || i.value == i.defaultValue) {
        i.value = i.defaultValue;
        $(i).addClass("blurredDefaultText");
    }
}

CSS:

.blurredDefaultText {
    color:#888 !important;
}

How do I exit a WPF application programmatically?

From xaml code you can call a predefined SystemCommand:

Command="SystemCommands.MinimizeWindowCommand"

I think this should be the prefered way...

Starting iPhone app development in Linux?

You're right non-jailbroken phones are limited to Apple's App store and Apple "has the right" to enforce whatever rule, it's totally nonfree territory. However while developing, one won't have to deal with Apple at all. You can use e.g. rsync to upload the code to the device and test it.

Using SELECT result in another SELECT

You are missing table NewScores, so it can't be found. Just join this table.

If you really want to avoid joining it directly you can replace NewScores.NetScore with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}

Update index after sorting data-frame

Since pandas 1.0.0 df.sort_values has a new parameter ignore_index which does exactly what you need:

In [1]: df2 = df.sort_values(by=['x','y'],ignore_index=True)

In [2]: df2
Out[2]:
   x  y
0  0  0
1  0  1
2  0  2
3  1  0
4  1  1
5  1  2
6  2  0
7  2  1
8  2  2

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

Understanding the Gemfile.lock file

It seems no clear document talking on the Gemfile.lock format. Maybe it's because Gemfile.lock is just used by bundle internally.

However, since Gemfile.lock is a snapshot of Gemfile, which means all its information should come from Gemfile (or from default value if not specified in Gemfile).

For GEM, it lists all the dependencies you introduce directly or indirectly in the Gemfile. remote under GEM tells where to get the gems, which is specified by source in Gemfile.

If a gem is not fetch from remote, PATH tells the location to find it. PATH's info comes from path in Gemfile when you declare a dependency.

And PLATFORM is from here.

For DEPENDENCIES, it's the snapshot of dependencies resolved by bundle.

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

How do I check for vowels in JavaScript?

This is a rough RegExp function I would have come up with (it's untested)

function isVowel(char) {
    return /^[aeiou]$/.test(char.toLowerCase());
}

Which means, if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true.

Parse large JSON file in Nodejs

If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:

[
   {"key": value},
   {"key": value},
   ...

This is still valid JSON.

Then, use the node.js readline module to process them one line at a time.

var fs = require("fs");

var lineReader = require('readline').createInterface({
    input: fs.createReadStream("input.txt")
});

lineReader.on('line', function (line) {
    line = line.trim();

    if (line.charAt(line.length-1) === ',') {
        line = line.substr(0, line.length-1);
    }

    if (line.charAt(0) === '{') {
        processRecord(JSON.parse(line));
    }
});

function processRecord(record) {
    // Process the records one at a time here! 
}

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Try writting the lambda with the same conditions as the delegate. like this:

  List<AnalysisObject> analysisObjects = 
    analysisObjectRepository.FindAll().Where(
    (x => 
       (x.ID == packageId)
    || (x.Parent != null && x.Parent.ID == packageId)
    || (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
    ).ToList();

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

Scroll to bottom of div with Vue.js

For those that haven't found a working solution above, I believe I have a working one. My specific use case was that I wanted to scroll to the bottom of a specific div - in my case a chatbox - whenever a new message was added to the array.

const container = this.$el.querySelector('#messagesCardContent');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });

I have to use nextTick as we need to wait for the dom to update from the data change before doing the scroll!

I just put the above code in a watcher for the messages array, like so:

messages: {
      handler() {
        // this scrolls the messages to the bottom on loading data
        const container = this.$el.querySelector('#messagesCard');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });
      },
      deep: true,
    }, 

Test file upload using HTTP PUT method

In my opinion the best tool for such testing is curl. Its --upload-file option uploads a file by PUT, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):

curl http://myservice --upload-file file.txt

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

apache server reached MaxClients setting, consider raising the MaxClients setting

Here's an approach that could resolve your problem, and if not would help with troubleshooting.

  1. Create a second Apache virtual server identical to the current one

  2. Send all "normal" user traffic to the original virtual server

  3. Send special or long-running traffic to the new virtual server

Special or long-running traffic could be report-generation, maintenance ops or anything else you don't expect to complete in <<1 second. This can happen serving APIs, not just web pages.

If your resource utilization is low but you still exceed MaxClients, the most likely answer is you have new connections arriving faster than they can be serviced. Putting any slow operations on a second virtual server will help prove if this is the case. Use the Apache access logs to quantify the effect.

Structs data type in php?

A public class is one option, if you want something more encapsulated you can use an abstract/anonymous class combination. My favorite part is that autocomplete still works (for PhpStorm) for this but I don't have a public class sitting around.

<?php

final class MyParentClass
{
    /**
     * @return MyStruct[]
     */
    public function getData(): array
    {
        return array(
            $this->createMyObject("One", 1.0, new DateTime("now")),
            $this->createMyObject("Two", 2.0, new DateTime("tommorow"))
        );
    }

    private function createMyObject(string $description, float $magnitude, DateTime $timeStamp): MyStruct
    {
        return new class(func_get_args()) extends MyStruct {
            protected function __construct(array $args)
            {
                $this->description = $args[0];
                $this->magnitude = $args[1];
                $this->timeStamp = $args[2];
            }
        };
    }
}

abstract class MyStruct
{
    public string $description;
    public float $magnitude;
    public DateTime $timeStamp;
}

Sort a two dimensional array based on one column

Arrays.sort(yourarray, new Comparator() {
    public int compare(Object o1, Object o2) {
        String[] elt1 = (String[])o1;
        String[] elt2 = (String[])o2;
        return elt1[0].compareTo(elt2[0]);
    }
});

How to change the text of a button in jQuery?

You need to do .button("refresh")

HTML :

<button id='btnviewdetails' type='button'>SET</button>

JS :

$('#btnviewdetails').text('Save').button("refresh");

Do copyright dates need to be updated?

There is no reason at all for an individual to update the copyright year, because in the U.S. and Europe the life of copyright is the life of the author plus 70 years (50 years in some other countries like Canada and Australia). Extending the date does not extend the copyright. This also applies when a page has multiple contributors none of which are corporations.

As for corporations, Google doesn't update their copyright dates because they don't care whether some page they started in 1999 and updated this year falls into the public domain in 2094 or 2109. And if they don't, why should you? (As a Googler, now an ex-Googler, I was told this was the policy for internal source code as well.)

Can I have multiple :before pseudo-elements for the same element?

In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

As a result, when you have multiple :before rules matching the same element, they will all cascade and apply to a single :before pseudo-element, as with a normal element. In your example, the end result looks like this:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}

As you can see, only the content declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.

This behavior is described in the Selectors section of CSS2.1:

Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.

This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.

If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before or .now.circle:before — whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content property that you will need to define yourself.

If you still need a concrete example, see my answer to this similar question.

The legacy css3-content specification contains a section on inserting multiple ::before and ::after pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.

data.map is not a function

The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):

     $.getJSON("json/products.json").done(function (data) {

         var allProducts = [data].map(function (item) {
             return new getData(item);
         });

     });

Here, [data] is an array, and the ".map" method can be used on it. It works for me! enter image description here

System.Security.SecurityException when writing to Event Log

Same issue on Windows 7 64bits. Run as administrator solved the problem.

How to drop a unique constraint from table column?

SKINDER, your code does not use column name. Correct script is:

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

set @table_name = N'users'
set @col_name = N'login'

select @Command = 'ALTER TABLE ' + @table_name + ' drop constraint ' + d.name
    from sys.tables t 
    join sys.indexes d on d.object_id = t.object_id  and d.type=2 and d.is_unique=1
    join sys.index_columns ic on d.index_id=ic.index_id and ic.object_id=t.object_id
    join sys.columns c on ic.column_id = c.column_id  and c.object_id=t.object_id
    where t.name = @table_name and c.name=@col_name

print @Command

--execute (@Command)

How to set focus on a view when a layout is created and displayed?

Set

 android:focusable="true"

in your <EditText/>

How do I use ROW_NUMBER()?

Though I agree with others that you could use count() to get the total number of rows, here is how you can use the row_count():

  1. To get the total no of rows:

    with temp as (
        select row_number() over (order by id) as rownum
        from table_name 
    )
    select max(rownum) from temp
  2. To get the row numbers where name is Matt:

    with temp as (
        select name, row_number() over (order by id) as rownum
        from table_name
    )
    select rownum from temp where name like 'Matt'

You can further use min(rownum) or max(rownum) to get the first or last row for Matt respectively.

These were very simple implementations of row_number(). You can use it for more complex grouping. Check out my response on Advanced grouping without using a sub query

How can I use regex to get all the characters after a specific character, e.g. comma (",")

This should work

preg_match_all('@.*\,(.*)@', '{{your data}}', $arr, PREG_PATTERN_ORDER);

You can test it here: http://www.spaweditor.com/scripts/regex/index.php

RegEx: .*\,(.*)

Same RegEx test here for JavaScript: http://www.regular-expressions.info/javascriptexample.html

How can I display a pdf document into a Webview?

This is the actual usage limit that google allows before you get the error mentioned in the comments, if it's a once in a lifetime pdf that the user will open in app then i feel its completely safe. Although it is advised to to follow the the native approach using the built in framework in Android from Android 5.0 / Lollipop, it's called PDFRenderer.

How can I calculate the number of years between two dates?

Using pure javascript Date(), we can calculate the numbers of years like below

_x000D_
_x000D_
document.getElementById('getYearsBtn').addEventListener('click', function () {_x000D_
  var enteredDate = document.getElementById('sampleDate').value;_x000D_
  // Below one is the single line logic to calculate the no. of years..._x000D_
  var years = new Date(new Date() - new Date(enteredDate)).getFullYear() - 1970;_x000D_
  console.log(years);_x000D_
});
_x000D_
<input type="text" id="sampleDate" value="1980/01/01">_x000D_
<div>Format: yyyy-mm-dd or yyyy/mm/dd</div><br>_x000D_
<button id="getYearsBtn">Calculate Years</button>
_x000D_
_x000D_
_x000D_

How to get HTTP Response Code using Selenium WebDriver

Not sure this is what you're looking for, but I had a bit different goal is to check if remote image exists and I will not have 403 error, so you could use something like below:

public static boolean linkExists(String URLName){
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

Remove Last Comma from a string

First, one should check if the last character is a comma. If it exists, remove it.

if (str.indexOf(',', this.length - ','.length) !== -1) {
    str = str.substring(0, str.length - 1);
}

NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)

Professional jQuery based Combobox control?

I'm looking for the same. The one I liked most till now is this one for ExtJs - except I havent tested it with large Lists: www.sencha.com/deploy/dev/examples/form/combos.html

Here is another really(!) fast one: http://jsearchdropdown.sourceforge.net/

For example the SexyCombo works quite fantastic but is way to slow for longer lists. The SexyCombo folk UFD is a lot faster, but initialization time is still quite slow for really huge lists. Besides I get sometimes some little! "flashing". But I guess there will be some updates in the near future.

VIM Disable Automatic Newline At End Of File

OK, you being on Windows complicates things ;)

As the 'binary' option resets the 'fileformat' option (and writing with 'binary' set always writes with unix line endings), let's take out the big hammer and do it externally!

How about defining an autocommand (:help autocommand) for the BufWritePost event? This autocommand is executed after every time you write a whole buffer. In this autocommand call a small external tool (php, perl or whatever script) that strips off the last newline of the just written file.

So this would look something like this and would go into your .vimrc file:

autocmd!   "Remove all autocmds (for current group), see below"
autocmd BufWritePost *.php !your-script <afile>

Be sure to read the whole vim documentation about autocommands if this is your first time dealing with autocommands. There are some caveats, e.g. it's recommended to remove all autocmds in your .vimrc in case your .vimrc might get sourced multiple times.

Programmatically navigate using React router

Here's how you do this with react-router v2.0.0 with ES6. react-router has moved away from mixins.

import React from 'react';

export default class MyComponent extends React.Component {
  navigateToPage = () => {
    this.context.router.push('/my-route')
  };

  render() {
    return (
      <button onClick={this.navigateToPage}>Go!</button>
    );
  }
}

MyComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
}

How to load json into my angular.js ng-model?

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

It returns some JSON data which looks like this:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

Prevent multiple instances of a given app in .NET?

After trying multiple solutions i the question. I ended up using the example for WPF here: http://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/

public partial class App : Application  
{  
    private static Mutex _mutex = null;  

    protected override void OnStartup(StartupEventArgs e)  
    {  
        const string appName = "MyAppName";  
        bool createdNew;  

        _mutex = new Mutex(true, appName, out createdNew);  

        if (!createdNew)  
        {  
            //app is already running! Exiting the application  
            Application.Current.Shutdown();  
        }  

    }          
}  

In App.xaml:

x:Class="*YourNameSpace*.App"
StartupUri="MainWindow.xaml"
Startup="App_Startup"

Returning IEnumerable<T> vs. IQueryable<T>

There is a blog post with brief source code sample about how misuse of IEnumerable<T> can dramatically impact LINQ query performance: Entity Framework: IQueryable vs. IEnumerable.

If we dig deeper and look into the sources, we can see that there are obviously different extension methods are perfomed for IEnumerable<T>:

// Type: System.Linq.Enumerable
// Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll
public static class Enumerable
{
    public static IEnumerable<TSource> Where<TSource>(
        this IEnumerable<TSource> source, 
        Func<TSource, bool> predicate)
    {
        return (IEnumerable<TSource>) 
            new Enumerable.WhereEnumerableIterator<TSource>(source, predicate);
    }
}

and IQueryable<T>:

// Type: System.Linq.Queryable
// Assembly: System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Core.dll
public static class Queryable
{
    public static IQueryable<TSource> Where<TSource>(
        this IQueryable<TSource> source, 
        Expression<Func<TSource, bool>> predicate)
    {
        return source.Provider.CreateQuery<TSource>(
            Expression.Call(
                null, 
                ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(
                    new Type[] { typeof(TSource) }), 
                    new Expression[] 
                        { source.Expression, Expression.Quote(predicate) }));
    }
}

The first one returns enumerable iterator, and the second one creates query through the query provider, specified in IQueryable source.

Options for HTML scraping?

Python has several options for HTML scraping in addition to Beatiful Soup. Here are some others:

  • mechanize: similar to perl WWW:Mechanize. Gives you a browser like object to ineract with web pages
  • lxml: Python binding to libwww. Supports various options to traverse and select elements (e.g. XPath and CSS selection)
  • scrapemark: high level library using templates to extract informations from HTML.
  • pyquery: allows you to make jQuery like queries on XML documents.
  • scrapy: an high level scraping and web crawling framework. It can be used to write spiders, for data mining and for monitoring and automated testing

How to get the entire document HTML as a string?

I just need doctype html and should work fine in IE11, Edge and Chrome. I used below code it works fine.

function downloadPage(element, event) {
    var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
        document.execCommand('SaveAs', '1', 'page.html');
        event.preventDefault();
    } else {
        if(isChrome) {
            element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));
        }
        element.setAttribute('download', 'page.html');
    }
}

and in your anchor tag use like this.

<a href="#" onclick="downloadPage(this,event);" download>Download entire page.</a>

Example

_x000D_
_x000D_
    function downloadPage(element, event) {_x000D_
     var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);_x000D_
    _x000D_
     if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {_x000D_
      document.execCommand('SaveAs', '1', 'page.html');_x000D_
      event.preventDefault();_x000D_
     } else {_x000D_
      if(isChrome) {_x000D_
                element.setAttribute('href','data:text/html;charset=UTF-8,'+encodeURIComponent('<!doctype html>' + document.documentElement.outerHTML));_x000D_
      }_x000D_
      element.setAttribute('download', 'page.html');_x000D_
     }_x000D_
    }
_x000D_
I just need doctype html and should work fine in IE11, Edge and Chrome. _x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
_x000D_
<p>_x000D_
<a href="#" onclick="downloadPage(this,event);"  download><h2>Download entire page.</h2></a></p>_x000D_
_x000D_
<p>Some image here</p>_x000D_
_x000D_
<p><img src="https://placeimg.com/250/150/animals"/></p>
_x000D_
_x000D_
_x000D_

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

Check the answer how to implement headers with StoryBoard: Table Header Views in StoryBoards

Also notice that if you don't implement

viewForHeaderInSection:(NSInteger)section

it will not float which is exactly what you want.

Pagination using MySQL LIMIT, OFFSET

Use .. LIMIT :pageSize OFFSET :pageStart

Where :pageStart is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize is bound to number_of_items_per_pages.

To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1 and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.

If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET item.

How to uncheck a radio button?

function clearForm(){
  $('#frm input[type="text"]').each(function(){
      $(this).val("");  
  });
  $('#frm input[type="radio":checked]').each(function(){
      $(this).attr('checked', false);  
  });
 }

The correct selector is: #frm input[type="radio"]:checked not #frm input[type="radio":checked]

T-SQL substring - separating first and last name

You could do this if firstname and surname are separated by space:

SELECT SUBSTRING(FirstAndSurnameCol, 0, CHARINDEX(' ', FirstAndSurnameCol)) Firstname,
SUBSTRING(FirstAndSurnameCol, CHARINDEX(' ', FirstAndSurnameCol)+1, LEN(FirstAndSurnameCol)) Surname FROM ...

How can I join on a stored procedure?

I hope your stored procedure is not doing a cursor loop!

If not, take the query from your stored procedure and integrate that query within the query you are posting here:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
        u.UnitNumber,
        p.PropertyName
        ,dt.TenantBalance
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty   p ON u.PropertyID = p.ID
    LEFT JOIN (SELECT ID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
                   FROM tblTransaction
                   GROUP BY tenant.ID
              ) dt ON t.ID=dt.ID
ORDER BY p.PropertyName, t.CarPlateNumber

If you are doing something more than a query in your stored procedure, create a temp table and execute the stored procedure into this temp table and then join to that in your query.

create procedure test_proc
as
  select 1 as x, 2 as y
  union select 3,4 
  union select 5,6 
  union select 7,8 
  union select 9,10
  return 0
go 

create table #testing
(
  value1   int
  ,value2  int
)

INSERT INTO #testing
exec test_proc


select
  *
  FROM #testing

How to run a method every X seconds

Here maybe helpful answer for your problem using Rx Java & Rx Android.

Populating a razor dropdownlist from a List<object> in MVC

I'm going to approach this as if you have a Users model:

Users.cs

public class Users
{
    [Key]
    public int UserId { get; set; }

    [Required]
    public string UserName { get; set; }

    public int RoleId { get; set; }

    [ForeignKey("RoleId")]
    public virtual DbUserRoles DbUserRoles { get; set; }
}

and a DbUserRoles model that represented a table by that name in the database:

DbUserRoles.cs

public partial class DbUserRoles
{
    [Key]
    public int UserRoleId { get; set; }

    [Required]
    [StringLength(30)]
    public string UserRole { get; set; }
}

Once you had that cleaned up, you should just be able to create and fill a collection of UserRoles, like this, in your Controller:

var userRoleList = GetUserRolesList();
ViewData["userRoles"] = userRolesList;

and have these supporting functions:

private static SelectListItem[] _UserRolesList;

/// <summary>
/// Returns a static category list that is cached
/// </summary>
/// <returns></returns>
public SelectListItem[] GetUserRolesList()
{
    if (_UserRolesList == null)
    {
        var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
         {
             Text = a.UserRole,
             Value = a.UserRoleId.ToString()
         }).ToList();
         userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });

        _UserRolesList = userRoles.ToArray();
    }

    // Have to create new instances via projection
    // to avoid ModelBinding updates to affect this
    // globally
    return _UserRolesList
        .Select(d => new SelectListItem()
    {
         Value = d.Value,
         Text = d.Text
    })
     .ToArray();
}

Repository.cs

My Repository function GetAllUserRoles() for the function, above:

public class Repository
{
    Model1 db = new Model1(); // Entity Framework context

    // User Roles
    public IList<DbUserRoles> GetAllUserRoles()
    {
        return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
    }
}

AddNewUser.cshtml

Then do this in your View:

<table>
    <tr>
        <td>
            @Html.EditorFor(model => model.UserName,
                  htmlAttributes: new { @class = "form-control" }
                  )
        </td>
        <td>
            @Html.DropDownListFor(model => model.RoleId,
                  new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
                  htmlAttributes: new { @class = "form-control" }
                  )
         </td>
     </tr>
 </table>

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

You could unregister the control with

regsvr32 /u badboy.ocx

at the command line. Though i would suggest testing these things in a vmware.

How to check if a file exists in Ansible?

If you just want to make sure a certain file exists (f.ex. because it shoud be created in a different way than via ansible) and fail if it doesn't, then you can do this:

- name: sanity check that /some/path/file exists
  command: stat /some/path/file
  check_mode: no # always run
  changed_when: false # doesn't change anything

Normalizing images in OpenCV

When you normalize a matrix using NORM_L1, you are dividing every pixel value by the sum of absolute values of all the pixels in the image. As a result, all pixel values become much less than 1 and you get a black image. Try NORM_MINMAX instead of NORM_L1.

Passing multiple argument through CommandArgument of Button in Asp.net

A little more elegant way of doing the same adding on to the above comment ..

<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
                           AutoGenerateColumns="false"
                            OnRowDeleting="deleteRow"
                         GridLines="Vertical">
      <asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
      <asp:BoundField DataField="EntityId" HeaderText="EntityId"  />
    <asp:TemplateField ShowHeader="false">
        <ItemTemplate>
           <asp:LinkButton ID="lnkCustomize" Text="Delete"  CommandName="Delete"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
           </asp:LinkButton>   
        </ItemTemplate>   
    </asp:TemplateField>
     </asp:GridView>

And on the server side:

protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
    string IdTemplate= e.Values["IdTemplate"].ToString();
    string EntityId = e.Values["EntityId"].ToString();

   // Do stuff..
}

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

alert() not working in Chrome

I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.

The solution was as simple as closing the tab and opening a fresh one!

AngularJS : The correct way of binding to a service properties

Consider some pros and cons of the second approach:

  • 0 {{lastUpdated}} instead of {{timerData.lastUpdated}}, which could just as easily be {{timer.lastUpdated}}, which I might argue is more readable (but let's not argue... I'm giving this point a neutral rating so you decide for yourself)

  • +1 It may be convenient that the controller acts as a sort of API for the markup such that if somehow the structure of the data model changes you can (in theory) update the controller's API mappings without touching the html partial.

  • -1 However, theory isn't always practice and I usually find myself having to modify markup and controller logic when changes are called for, anyway. So the extra effort of writing the API negates it's advantage.

  • -1 Furthermore, this approach isn't very DRY.

  • -1 If you want to bind the data to ng-model your code become even less DRY as you have to re-package the $scope.scalar_values in the controller to make a new REST call.

  • -0.1 There's a tiny performance hit creating extra watcher(s). Also, if data properties are attached to the model that don't need to be watched in a particular controller they will create additional overhead for the deep watchers.

  • -1 What if multiple controllers need the same data models? That means that you have multiple API's to update with every model change.

$scope.timerData = Timer.data; is starting to sound mighty tempting right about now... Let's dive a little deeper into that last point... What kind of model changes were we talking about? A model on the back-end (server)? Or a model which is created and lives only in the front-end? In either case, what is essentially the data mapping API belongs in the front-end service layer, (an angular factory or service). (Note that your first example--my preference-- doesn't have such an API in the service layer, which is fine because it's simple enough it doesn't need it.)

In conclusion, everything does not have to be decoupled. And as far as decoupling the markup entirely from the data model, the drawbacks outweigh the advantages.


Controllers, in general shouldn't be littered with $scope = injectable.data.scalar's. Rather, they should be sprinkled with $scope = injectable.data's, promise.then(..)'s, and $scope.complexClickAction = function() {..}'s

As an alternative approach to achieve data-decoupling and thus view-encapsulation, the only place that it really makes sense to decouple the view from the model is with a directive. But even there, don't $watch scalar values in the controller or link functions. That won't save time or make the code any more maintainable nor readable. It won't even make testing easier since robust tests in angular usually test the resulting DOM anyway. Rather, in a directive demand your data API in object form, and favor using just the $watchers created by ng-bind.


Example http://plnkr.co/edit/MVeU1GKRTN4bqA3h9Yio

<body ng-app="ServiceNotification">
    <div style="border-style:dotted" ng-controller="TimerCtrl1">
        TimerCtrl1<br/>
        Bad:<br/>
        Last Updated: {{lastUpdated}}<br/>
        Last Updated: {{calls}}<br/>
        Good:<br/>
        Last Updated: {{data.lastUpdated}}<br/>
        Last Updated: {{data.calls}}<br/>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
    <script type="text/javascript">
        var app = angular.module("ServiceNotification", []);

        function TimerCtrl1($scope, Timer) {
            $scope.data = Timer.data;
            $scope.lastUpdated = Timer.data.lastUpdated;
            $scope.calls = Timer.data.calls;
        };

        app.factory("Timer", function ($timeout) {
            var data = { lastUpdated: new Date(), calls: 0 };

            var updateTimer = function () {
                data.lastUpdated = new Date();
                data.calls += 1;
                console.log("updateTimer: " + data.lastUpdated);

                $timeout(updateTimer, 500);
            };
            updateTimer();

            return {
                data: data
            };
        });
    </script>
</body>

UPDATE: I've finally come back to this question to add that I don't think that either approach is "wrong". Originally I had written that Josh David Miller's answer was incorrect, but in retrospect his points are completely valid, especially his point about separation of concerns.

Separation of concerns aside (but tangentially related), there's another reason for defensive copying that I failed to consider. This question mostly deals with reading data directly from a service. But what if a developer on your team decides that the controller needs to transform the data in some trivial way before the view displays it? (Whether controllers should transform data at all is another discussion.) If she doesn't make a copy of the object first she might unwittingly cause regressions in another view component which consumes the same data.

What this question really highlights are architectural shortcomings of the typical angular application (and really any JavaScript application): tight coupling of concerns, and object mutability. I have recently become enamored with architecting application with React and immutable data structures. Doing so solves the following two problems wonderfully:

  1. Separation of concerns: A component consumes all of it's data via props and has little-to-no reliance on global singletons (such as Angular services), and knows nothing about what happened above it in the view hierarchy.

  2. Mutability: All props are immutable which eliminates the risk of unwitting data mutation.

Angular 2.0 is now on track to borrow heavily from React to achieve the two points above.

How can I display a list view in an Android Alert Dialog?

This is too simple

final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};

AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);

builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int item) {
        if (items[item].equals("Take Photo")) {
            getCapturesProfilePicFromCamera();
        } else if (items[item].equals("Choose from Library")) {
            getProfilePicFromGallery();
        } else if (items[item].equals("Cancel")) {
            dialog.dismiss();
        }
    }
});
builder.show();

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

boolean in an if statement

In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-

    Argument Type   Result

    Undefined       false
    Null            false
    Boolean         The result equals the input argument (no conversion).
    Number          The result is false if the argument is +0, -0, or NaN;
                    otherwise the result is true.
    String          The result is false if the argument is the empty 
                    String (its length is zero); otherwise the result is true.
    Object          true.

But comparison with === does not have any type coercion, so they must be equal without coercion.

If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.

if(x===true){
...
} else if(x===false){
....
} else {
....
}

How do I copy a string to the clipboard?

In addition to Mark Ransom's answer using ctypes: This does not work for (all?) x64 systems since the handles seem to be truncated to int-size. Explicitly defining args and return values helps to overcomes this problem.

import ctypes
import ctypes.wintypes as w

CF_UNICODETEXT = 13

u32 = ctypes.WinDLL('user32')
k32 = ctypes.WinDLL('kernel32')

OpenClipboard = u32.OpenClipboard
OpenClipboard.argtypes = w.HWND,
OpenClipboard.restype = w.BOOL

GetClipboardData = u32.GetClipboardData
GetClipboardData.argtypes = w.UINT,
GetClipboardData.restype = w.HANDLE

EmptyClipboard = u32.EmptyClipboard
EmptyClipboard.restype = w.BOOL

SetClipboardData = u32.SetClipboardData
SetClipboardData.argtypes = w.UINT, w.HANDLE,
SetClipboardData.restype = w.HANDLE

CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL

GHND = 0x0042

GlobalAlloc = k32.GlobalAlloc
GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t,
GlobalAlloc.restype = w.HGLOBAL

GlobalLock = k32.GlobalLock
GlobalLock.argtypes = w.HGLOBAL,
GlobalLock.restype = w.LPVOID

GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = w.HGLOBAL,
GlobalUnlock.restype = w.BOOL

GlobalSize = k32.GlobalSize
GlobalSize.argtypes = w.HGLOBAL,
GlobalSize.restype = w.ctypes.c_size_t

unicode_type = type(u'')

def get():
    text = None
    OpenClipboard(None)
    handle = GetClipboardData(CF_UNICODETEXT)
    pcontents = GlobalLock(handle)
    size = GlobalSize(handle)
    if pcontents and size:
        raw_data = ctypes.create_string_buffer(size)
        ctypes.memmove(raw_data, pcontents, size)
        text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
    GlobalUnlock(handle)
    CloseClipboard()
    return text

def put(s):
    if not isinstance(s, unicode_type):
        s = s.decode('mbcs')
    data = s.encode('utf-16le')
    OpenClipboard(None)
    EmptyClipboard()
    handle = GlobalAlloc(GHND, len(data) + 2)
    pcontents = GlobalLock(handle)
    ctypes.memmove(pcontents, data, len(data))
    GlobalUnlock(handle)
    SetClipboardData(CF_UNICODETEXT, handle)
    CloseClipboard()

#Test run
paste = get
copy = put
copy("Hello World!")
print(paste())

Python Flask, how to set content type

Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

If you use Response directly, you lose the chance to customize the responses by setting app.response_class. The make_response method uses the app.responses_class to make the response object. In this you can create your own class, add make your application uses it globally:

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse  

Best way to use multiple SSH private keys on one client

On Ubuntu 18.04 (Bionic Beaver) there is nothing to do.

After having created an second SSH key successfully the system will try to find a matching SSH key for each connection.

Just to be clear you can create a new key with these commands:

# Generate key make sure you give it a new name (id_rsa_server2)
ssh-keygen

# Make sure ssh agent is running
eval `ssh-agent`

# Add the new key
ssh-add ~/.ssh/id_rsa_server2

# Get the public key to add it to a remote system for authentication
cat ~/.ssh/id_rsa_server2.pub

Get Image Height and Width as integer values?

getimagesize('image.jpg') function works only if allow_url_fopen is set to 1 or On inside php.ini file on the server, if it is not enabled, one should use ini_set('allow_url_fopen',1); on top of the file where getimagesize() function is used.

How to include css files in Vue 2

As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them

You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built

How to create a JPA query with LEFT OUTER JOIN

Write this;

 SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc'

Because your Student entity has One To Many relationship with ClassTbl entity.

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:

this.Controls.Add(this.reportViewer1);

or

[ContainerControl].Controls.Add(this.reportViewer1);

You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

How to set the UITableView Section title programmatically (iPhone/iPad)?

If you are writing code in Swift it would look as an example like this

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
    switch section
    {
        case 0:
            return "Apple Devices"
        case 1:
            return "Samsung Devices"
        default:
            return "Other Devices"
    }
}