Programs & Examples On #Page break

Page breaks indicate the position at which one page should end and another should begin

CSS Printing: Avoiding cut-in-half DIVs between pages?

In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:

@media print{
* {
    display:inline;
}
script, style { 
    display:none; 
}
div {
    page-break-inside:avoid;
}

}

It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.

Maybe someone could expand on this.

How to apply CSS page-break to print a table with lots of rows?

Here is an example:

Via css:

<style>
  .my-table {
    page-break-before: always;
    page-break-after: always;
  }
  .my-table tr {
    page-break-inside: avoid;
  }
</style>

or directly on the element:

<table style="page-break-before: always; page-break-after: always;">
  <tr style="page-break-inside: avoid;">
    ..
  </tr>
</table>

Can I force a page break in HTML printing?

Just wanted to put an update. page-break-after is a legacy property now.

Official page states

This property has been replaced by the break-after property.

Git: force user and password prompt

Add a -v flag with your git command . e.g. git pull -v

v stands for verify .

Hiding user input on terminal in Linux script

A bit different from (but mostly like) @lesmana's answer

stty -echo
read password
stty echo

simply: hide echo do your stuff show echo

find difference between two text files with one item per line

You can try

grep -f file1 file2

or

grep -v -F -x -f file1 file2

Switch statement: must default be the last case?

yes, this is valid, and under some circumstances it is even useful. Generally, if you don't need it, don't do it.

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I solved this problem by adding following code into my /etc/my.cnf file -

enter image description here

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8


[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

After saving that,I went into my system settings and stopped MYSQL server and started again, and it worked.

Bitbucket git credentials if signed up with Google

Update as at September, 2019:

This whole process is now way easier than it used to be. It doesn't matter if your auth style is regular or Google-dependent, it works regardless. Follow these four easy steps:

  • Visit this link and enter your email.
  • Check your mail for the reactivation email and click the big blue button therein.
  • Change your password!

I hope this helps. Merry coding!

How do I POST an array of objects with $.ajax (jQuery or Zepto)

Be sure to stringify before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.

Works:

$.ajax({
    url: _saveAllDevicesUrl
,   type: 'POST'
,   contentType: 'application/json'
,   data: JSON.stringify(postData) //stringify is important
,   success: _madeSave.bind(this)
});

I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.

Scanner is never closed

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

Scanner scanner = null;
try {
    scanner = new Scanner(System.in);
    //rest of the code
}
finally {
    if(scanner!=null)
        scanner.close();
}

Or even better: use the new Try with resource statement:

try(Scanner scanner = new Scanner(System.in)){
    //rest of your code
}

JSHint and jQuery: '$' is not defined

You can also add two lines to your .jshintrc

  "globals": {
    "$": false,
    "jQuery": false
  }

This tells jshint that there are two global variables.

How to launch Safari and open URL from iOS app

In SWIFT 3.0

               if let url = URL(string: "https://www.google.com") {
                 UIApplication.shared.open(url, options: [:])
               }

Excel VBA - select a dynamic cell range

I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.

Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column

Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range

Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")

'Find Last Row and Column
  LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
  LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column

'Select Range
  sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select

End Sub

How to print time in format: 2009-08-10 18:17:54.811

None of the solutions on this page worked for me, I mixed them up and made them working with Windows and Visual Studio 2019, Here's How :

#include <Windows.h>
#include <time.h> 
#include <chrono>

static int gettimeofday(struct timeval* tp, struct timezone* tzp) {
    namespace sc = std::chrono;
    sc::system_clock::duration d = sc::system_clock::now().time_since_epoch();
    sc::seconds s = sc::duration_cast<sc::seconds>(d);
    tp->tv_sec = s.count();
    tp->tv_usec = sc::duration_cast<sc::microseconds>(d - s).count();
    return 0;
}

static char* getFormattedTime() {
    static char buffer[26];

    // For Miliseconds
    int millisec;
    struct tm* tm_info;
    struct timeval tv;

    // For Time
    time_t rawtime;
    struct tm* timeinfo;

    gettimeofday(&tv, NULL);

    millisec = lrint(tv.tv_usec / 1000.0);
    if (millisec >= 1000) 
    {
        millisec -= 1000;
        tv.tv_sec++;
    }

    time(&rawtime);
    timeinfo = localtime(&rawtime);

    strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", timeinfo);
    sprintf_s(buffer, 26, "%s.%03d", buffer, millisec);

    return buffer;
}

Result :

2020:08:02 06:41:59.107

2020:08:02 06:41:59.196

Set transparent background using ImageMagick and commandline prompt

This works for me:

convert original.png -fuzz 10% -transparent white transparent.png

where the smaller the fuzz %, the closer to true white or conversely, the larger the %, the more variation from white is allowed to become transparent

Can we pass model as a parameter in RedirectToAction?

Using TempData

Represents a set of data that persists only from one request to the next

[HttpPost]
public ActionResult FillStudent(Student student1)
{
    TempData["student"]= new Student();
    return RedirectToAction("GetStudent","Student");
}

[HttpGet]
public ActionResult GetStudent(Student passedStd)
{
    Student std=(Student)TempData["student"];
    return View();
}

Alternative way Pass the data using Query string

return RedirectToAction("GetStudent","Student", new {Name="John", Class="clsz"});

This will generate a GET Request like Student/GetStudent?Name=John & Class=clsz

Ensure the method you want to redirect to is decorated with [HttpGet] as the above RedirectToAction will issue GET Request with http status code 302 Found (common way of performing url redirect)

Python: Assign print output to a variable

Please note, I wrote this answer based on Python 3.x. No worries you can assign print() statement to the variable like this.

>>> var = print('some text')
some text
>>> var
>>> type(var)
<class 'NoneType'>

According to the documentation,

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

That's why we cannot assign print() statement values to the variable. In this question you have ask (or any function). So print() also a function with the return value with None. So the return value of python function is None. But you can call the function(with parenthesis ()) and save the return value in this way.

>>> var = some_function()

So the var variable has the return value of some_function() or the default value None. According to the documentation about print(), All non-keyword arguments are converted to strings like str() does and written to the stream. Lets look what happen inside the str().

Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

So we get a string object, then you can modify the below code line as follows,

>>> var = str(some_function())

or you can use str.join() if you really have a string object.

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

change can be as follows,

>>> var = ''.join(some_function())  # you can use this if some_function() really returns a string value

PHP Composer update "cannot allocate memory" error (using Laravel 4)

composer update

Loading composer repositories with package information
Updating dependencies (including require-dev)

> mmap() failed: [12] Cannot allocate memory

Update memory on Server and require '4G' Change 4GB Ram [try to change server type or add more ram]

2 Files We need to edit


on command

# cd /var/www/html
# nano .htaccess

and edit "memory_limit 756M” to 4G


Php ini on php 7.0

# cd ~
# php –-ini
# sudo nano /etc/php-7.0.ini

memory_limit = 128M to 4G

#AWS #AMAZONLINUX #MAGENTO2 #PHP7.0

Radio Buttons ng-checked with ng-model

[Personal Option] Avoiding using $scope, based on John Papa Angular Style Guide

so my idea is take advantage of the current model:

_x000D_
_x000D_
(function(){_x000D_
  'use strict';_x000D_
  _x000D_
   var app = angular.module('way', [])_x000D_
   app.controller('Decision', Decision);_x000D_
_x000D_
   Decision.$inject = [];     _x000D_
_x000D_
   function Decision(){_x000D_
     var vm = this;_x000D_
     vm.checkItOut = _register;_x000D_
_x000D_
     function _register(newOption){_x000D_
       console.log('should I stay or should I go');_x000D_
       console.log(newOption);  _x000D_
     }_x000D_
   }_x000D_
_x000D_
     _x000D_
     _x000D_
})();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div ng-app="way">_x000D_
  <div ng-controller="Decision as vm">_x000D_
    <form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">_x000D_
 <label class="radio-inline">_x000D_
  <input type="radio" name="option" ng-model="decision.myWay"_x000D_
                           ng-value="false" ng-checked="!decision.myWay"> Should I stay?_x000D_
                </label>_x000D_
                <label class="radio-inline">_x000D_
                    <input type="radio" name="option" ng-value="true"_x000D_
                           ng-model="decision.myWay" > Should I go?_x000D_
                </label>_x000D_
  _x000D_
</form>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

I hope I could help ;)

Git - How to close commit editor?

Alternatives to Nano (might make your life easier):

On Windows, use notepad. In command prompt type:

git config core.editor notepad

On Ubuntu / Linux, use text editor (gedit). In terminal window type:

git config core.editor gedit

RESTful API methods; HEAD & OPTIONS

OPTIONS method returns info about API (methods/content type)

HEAD method returns info about resource (version/length/type)

Server response

OPTIONS

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
  • OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?
  • HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource
  • HEAD Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval
  • HEAD, OPTIONS Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application

Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.

JSON Array iteration in Android/Java

If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:

@Override
public Iterator iterator() {
    return this.myArrayList.iterator();
}

This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.

React ignores 'for' attribute of the label element

both for and class are reserved words in JavaScript this is why when it comes to HTML attributes in JSX you need to use something else, React team decided to use htmlFor and className respectively

How do I create a singleton service in Angular 2?

I know angular has hierarchical injectors like Thierry said.

But I have another option here in case you find a use-case where you don't really want to inject it at the parent.

We can achieve that by creating an instance of the service, and on provide always return that.

import { provide, Injectable } from '@angular/core';
import { Http } from '@angular/core'; //Dummy example of dependencies

@Injectable()
export class YourService {
  private static instance: YourService = null;

  // Return the instance of the service
  public static getInstance(http: Http): YourService {
    if (YourService.instance === null) {
       YourService.instance = new YourService(http);
    }
    return YourService.instance;
  }

  constructor(private http: Http) {}
}

export const YOUR_SERVICE_PROVIDER = [
  provide(YourService, {
    deps: [Http],
    useFactory: (http: Http): YourService => {
      return YourService.getInstance(http);
    }
  })
];

And then on your component you use your custom provide method.

@Component({
  providers: [YOUR_SERVICE_PROVIDER]
})

And you should have a singleton service without depending on the hierarchical injectors.

I'm not saying this is a better way, is just in case someone has a problem where hierarchical injectors aren't possible.

Standard deviation of a list

Since Python 3.4 / PEP450 there is a statistics module in the standard library, which has a method stdev for calculating the standard deviation of iterables like yours:

>>> A_rank = [0.8, 0.4, 1.2, 3.7, 2.6, 5.8]
>>> import statistics
>>> statistics.stdev(A_rank)
2.0634114147853952

Cannot connect to repo with TortoiseSVN

Try clearing the settings under "Saved Data" - refer to:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html

This worked for me with Windows 7.

Eric

Retrieve filename from file descriptor in C

Before writing this off as impossible I suggest you look at the source code of the lsof command.

There may be restrictions but lsof seems capable of determining the file descriptor and file name. This information exists in the /proc filesystem so it should be possible to get at from your program.

When to use CouchDB over MongoDB and vice versa

Very old question but it's on top of Google and I don't quite like the answers I see so here's my own.

There's much more to Couchdb than the ability to develop CouchApps. Most people use CouchDb in a classical 3-tiers web architecture.

In practice the deciding factor for most people will be the fact that MongoDb allows ad-hoc querying with a SQL like syntax while CouchDb doesn't (you've got to create map/reduce views which turns some people off even though creating these views is Rapid Application Development friendly - they have nothing to do with stored procedures).

To address points raised in the accepted answer : CouchDb has a great versionning system, but it doesn't mean that it is only suited (or more suited) for places where versionning is important. Also, couchdb is heavy-write friendly thanks to its append-only nature (writes operations return in no time while guaranteeing that no data will ever be lost).

One very important thing that is not mentioned by anyone is the fact that CouchDb relies on b-tree indexes. This means that whether you have 1 "row" or 20 billions, the querying time will always remain below 10ms. This is a game changer which makes CouchDb a low-latency and read-friendly database, and this really shouldn't be overlooked.

To be fair and exhaustive the advantage MongoDb has over CouchDb is tooling and marketing. They have first-class citizen tools for all major languages and platforms making the on-boarding easy and this added to their adhoc querying makes the transition from SQL even easier.

CouchDb doesn't have this level of tooling - even though there are many libraries available today - but CouchDb is exposed as an HTTP API and it is therefore quite easy to create a wrapper in your favorite language to talk with it. I personally like this approach as it avoids bloat and allows you to only take what you want (interface segregation principle).

So I'd say using one or the other is largely a matter of comfort and preference with their paradigms. CouchDb approach "just fits", for certain people, but if after learning about the database features (in the exhaustive official guide) you don't have your "hell yeah" moment, you should probably move on.

I'd discourage using CouchDb if you just want to use "the right tool for the right job". because you'll find out that you can't just use it that way and you'll end up being pissed and writing blog posts such as "Where are joins in CouchDb ?" and "Where is transaction management ?". Indeed Couchdb is - paradoxically - very transparent but at the same time requires a paradigm shift and a change in the way you approach problems to really shine (and really work).

But once you've done that it really pays off. I'd personally need very strong reasons or a major deal breaker on a project to choose another database, but so far I haven't met any.

Setting max width for body using Bootstrap

You don't have to modify bootstrap-responsive by removing @media (max-width:1200px) ...

My application has a max-width of 1600px. Here's how it worked for me:

  1. Create bootstrap-custom.css - As much as possible, I don't want to override my original bootstrap css.

  2. Inside bootstrap-custom.css, override the container-fluid by including this code:

Like this:

/* set a max-width for horizontal fluid layout and make it centered */
.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 1600px; /* or 950px */
}

MySQL: Invalid use of group function

First, the error you're getting is due to where you're using the COUNT function -- you can't use an aggregate (or group) function in the WHERE clause.

Second, instead of using a subquery, simply join the table to itself:

SELECT a.pid 
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid

Which I believe should return only rows where at least two rows exist with the same pid but there is are at least 2 sids. To make sure you get back only one row per pid I've applied a grouping clause.

Create the perfect JPA entity

My 2 cents addition to the answers here are:

  1. With reference to Field or Property access (away from performance considerations) both are legitimately accessed by means of getters and setters, thus, my model logic can set/get them in the same manner. The difference comes to play when the persistence runtime provider (Hibernate, EclipseLink or else) needs to persist/set some record in Table A which has a foreign key referring to some column in Table B. In case of a Property access type, the persistence runtime system uses my coded setter method to assign the cell in Table B column a new value. In case of a Field access type, the persistence runtime system sets the cell in Table B column directly. This difference is not of importance in the context of a uni-directional relationship, yet it is a MUST to use my own coded setter method (Property access type) for a bi-directional relationship provided the setter method is well designed to account for consistency. Consistency is a critical issue for bi-directional relationships refer to this link for a simple example for a well-designed setter.

  2. With reference to Equals/hashCode: It is impossible to use the Eclipse auto-generated Equals/hashCode methods for entities participating in a bi-directional relationship, otherwise they will have a circular reference resulting in a stackoverflow Exception. Once you try a bidirectional relationship (say OneToOne) and auto-generate Equals() or hashCode() or even toString() you will get caught in this stackoverflow exception.

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

edit the ".classpath" and include below tag

<classpathentry kind="con" path="org.testng.TESTNG_CONTAINER"/>

this could solve your problem.

How to create a file on Android Internal Storage?

I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.

If you execute the following statement:

File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();

It will resolve the path to the root /data/ somewhere higher up in Android.

I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.

File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();

A quick fix would be to change your following code:

File f = new File(getLocalPath().replace("/data/data/", "/"));

Hope this helps

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Conversation> conversations = **jdbcTemplate**.**queryForList**(
            **SQL_QUERY**,
            new Object[] {userId, dateFrom, dateTo});  //placeholders values

Suppose the sql query is like

SQL_QUERY = "**select** info,count(*),IF(info is null , 'DATA' , 'NO DATA') **from** table where userId=? , dateFrom=? , dateTo=?";

**HERE userId=? , dateFrom=? , dateTo=?**

the question marks are place holders

**SQL_QUERY**,
            new Object[] {userId, dateFrom, dateTo});

It will go as an object array along with the sql query

SFTP Libraries for .NET

Check this out: http://www.tamirgal.com/home/dev.aspx?Item=sharpSsh

SharpSSH is a pure .NET implementation of the SSH2 client protocol suite. It provides an API for communication with SSH servers and can be integrated into any .NET application.

The library is a C# port of the JSch project from JCraft Inc. and is released under BSD style license.

SharpSSH allows you to read/write data and transfer files over SSH channels using an API similar to JSch's API. In addition, it provides some additional wrapper classes which offer even simpler abstraction for SSH communication.

SharpSSH project page at source forge: http://sourceforge.net/projects/sharpssh

MVC ajax post to controller action method

Your Action is expecting string parameters, but you're sending a composite object.

You need to create an object that matches what you're sending.

public class Data
{
    public string username { get;set; }
    public string password { get;set; }
}

public JsonResult Login(Data data)
{
}

EDIT

In addition, toStringify() is probably not what you want here. Just send the object itself.

data: data,

Java Scanner class reading strings

This because in.nextInt() only receive a int number, doesn't receive a new line. So you input 3 and press "Enter", the end of line is read by in.nextline().

Here is my code:

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];

for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

Dynamic Web Module 3.0 -- 3.1

I had the same problem and fixed this by editing org.eclipse.wst.common.project.facet.core.xml.

In this file, I was able to change the following line

<installed facet="jst.web" version="3.1"/>

back to

<installed facet="jst.web" version="3.0"/>

That seemed to fix the problem for me.

Update a submodule to the latest commit

Since git 1.8 you can do

git submodule update --remote --merge

This will update the submodule to the latest remote commit. You will then need to commit the change so the gitlink in the parent repository is updated

git commit

And then push the changes as without this, the SHA-1 identity the pointing to the submodule won't be updated and so the change won't be visible to anyone else.

Custom Date/Time formatting in SQL Server

Yes Depart is a solution for that but I think this kind of methods are long trips!

SQL SERVER:

SELECT CAST(DATEPART(DD,GETDATE()) AS VARCHAR)+'/'
+CAST(DATEPART(MM,GETDATE()) AS VARCHAR)
+'/'+CAST(DATEPART(YYYY,GETDATE()) AS VARCHAR)
+' '+CAST(DATEPART(HH,GETDATE()) AS VARCHAR)
+':'+CAST(DATEPART(MI,GETDATE()) AS VARCHAR)

Oracle:

Select to_char(sysdate,'DD/MM/YYYY HH24:MI') from dual

You may write your own function by this way you can get rid of this mess;

http://sql.dzone.com/news/custom-date-formatting-sql-ser

select myshortfun(getdate(),myformat)
GO

Mockito: List Matchers with generics

Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:

import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;

verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());

What are unit tests, integration tests, smoke tests, and regression tests?

Everyone will have slightly different definitions, and there are often grey areas. However:

  • Unit test: does this one little bit (as isolated as possible) work?
  • Integration test: do these two (or more) components work together?
  • Smoke test: does this whole system (as close to being a production system as possible) hang together reasonably well? (i.e. are we reasonably confident it won't create a black hole?)
  • Regression test: have we inadvertently re-introduced any bugs we'd previously fixed?

Converting String to Int using try/except in Python

Firstly, try / except are not functions, but statements.

To convert a string (or any other type that can be converted) to an integer in Python, simply call the int() built-in function. int() will raise a ValueError if it fails and you should catch this specifically:

In Python 2.x:

>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print '%s as an int is %d' % (str(value), int(value))
...     except ValueError as ex:
...         print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

In Python 3.x

the syntax has changed slightly:

>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print('%s as an int is %d' % (str(value), int(value)))
...     except ValueError as ex:
...         print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

CAST to DECIMAL in MySQL

If you need a lot of decimal numbers, in this example 17, I share with you MySql code:

This is the calculate:

=(9/1147)*100

SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);

base_url() function not working in codeigniter

Check if you have something configured inside the config file /application/config/config.php e.g.

$config['base_url'] = 'http://example.com/';

MetadataException when using Entity Framework Entity Connection

I had the same error message, and the problem was also the metadata part of the connection string, but I had to dig a little deeper to solve it and wanted to share this little nugget:

The metadata string is made up of three sections that each look like this:

res://
      (assembly)/
      (model name).(ext)

Where ext is "csdl", "ssdl", and "msl".

For most people, assembly can probably be "*", which seems to indicate that all loaded assemblies will be searched (I haven't done a huge amount of testing of this). This part wasn't an issue for me, so I can't comment on whether you need the assembly name or file name (i.e., with or without ".dll"), though I have seen both suggested.

The model name part should be the name and namespace of your .edmx file, relative to your assembly. So if you have a My.DataAccess assembly and you create DataModels.edmx in a Models folder, its full name is My.DataAccess.Models.DataModels. In this case, you would have "Models.DataModels.(ext)" in your metadata.

If you ever move or rename your .edmx file, you will need to update your metadata string manually (in my experience), and remembering to change the relative namespace will save a few headaches.

Tests not running in Test Explorer

I had the same problem in VS 2017. In my case it solved by restarting VS.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

This problem often happens when a django project deploys using Apache. Because Apache sets environment variable LANG=C in /etc/sysconfig/httpd. Just open the file and comment (or change to your flavior) this setting. Or use the lang option of the WSGIDaemonProcess command, in this case you will be able to set different LANG environment variable to different virtualhosts.

AttributeError: Can only use .dt accessor with datetimelike values

When you write

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')

It can fixed

How to properly and completely close/reset a TcpClient connection?

Have you tried calling TcpClient.Dispose() explicitly?

And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?

Remove rows not .isin('X')

You can use the DataFrame.select method:

In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])

In [2]: df
Out[2]: 
   0  1
A  1  2
B  3  4

In [3]: L = ['A']

In [4]: df.select(lambda x: x in L)
Out[4]: 
   0  1
A  1  2

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

move_uploaded_file gives "failed to open stream: Permission denied" error

The solution is so easy. Only right click the IMAGE (destination) folder, go to properties, click the permission tab, and change others access to Create and delete files.

Adding a new SQL column with a default value

Try this:

ALTER TABLE table1 ADD COLUMN foo INT DEFAULT 0;

From the documentation that you linked to:

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name
   alter_specification [, alter_specification] ...

alter_specification:
    ...
    ADD [COLUMN] (col_name column_definition,...)
    ...

To find the syntax for column_definition search a bit further down the page:

column_definition clauses use the same syntax for ADD and CHANGE as for CREATE TABLE. See Section 12.1.17, “CREATE TABLE Syntax”.

And from the linked page:

column_definition:  
   data_type [NOT NULL | NULL] [DEFAULT default_value]
   [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]  
   [COMMENT 'string']  
   [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]  
   [STORAGE {DISK|MEMORY|DEFAULT}]  
   [reference_definition]  

Notice the word DEFAULT there.

Vue is not defined

I got this error but as undefined due to the way I included js files

Initailly i had

<script src="~/vue/blade-account-update-credit-card-vue.js" asp-append-version="true"></script>
<script src="~/lib/vue/vue_v2.5.16.js"></script>

in the end of my .cshtml page GOT Error Vue not Defined but later I changed it to

<script src="~/lib/vue/vue_v2.5.16.js"></script> 
<script src="~/vue/blade-account-update-credit-card-vue.js" asp-append-version="true"></script>

and magically it worked. So i assume that vue js needs to be loaded on top of the .vue

Correct way to pause a Python program

By this method, you can resume your program just by pressing any specified key you've specified that:

import keyboard
while True:
    key = keyboard.read_key()
    if key == 'space':  # You can put any key you like instead of 'space'
        break

The same method, but in another way:

import keyboard
while True:
    if keyboard.is_pressed('space'):  # The same. you can put any key you like instead of 'space'
        break

Note: you can install the keyboard module simply by writing this in you shell or cmd:

pip install keyboard

Get environment variable value in Dockerfile

An alternative using envsubst without losing the ability to use commands like COPY or ADD, and without using intermediate files would be to use Bash's Process Substitution:

docker build -f <(envsubst < Dockerfile) -t my-target .

How do I create an .exe for a Java program?

Launch4j perhaps? Can't say I've used it myself, but it sounds like what you're after.

How to get the unique ID of an object which overrides hashCode()?

Maybe this quick, dirty solution will work?

public class A {
    static int UNIQUE_ID = 0;
    int uid = ++UNIQUE_ID;

    public int hashCode() {
        return uid;
    }
}

This also gives the number of instance of a class being initialized.

Saving binary data as file using JavaScript from a browser

To do this task download.js library can be used. Here is an example from library docs:

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

What is EOF in the C programming language?

You should change your parenthesis to

while((c = getchar()) != EOF)

Because the "=" operator has a lower precedence than the "!=" operator. Then you will get the expected results. Your expression is equal to

while (c = (getchar()!= EOF))

You are getting the two 1's as output, because you are making the comparison "c!=EOF". This will always become one for the character you entered and then the "\n" that follows by hitting return. Except for the last comparison where c really is EOF it will give you a 0.

EDIT about EOF: EOF is typically -1, but this is not guaranteed by the standard. The standard only defines about EOF in section 7.19.1:

EOF which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;

It is reasonable to assume that EOF equals -1, but when using EOF you should not test against the specific value, but rather use the macro.

Selecting a Linux I/O Scheduler

It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like

# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"

inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules). This answer is based on the debian wiki

To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:

for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done

Ant build failed: "Target "build..xml" does not exist"

  1. Probably you don't have environment variable ANT_HOME set properly
  2. It seems that you are calling Ant like this: "ant build..xml". If your ant script has name build.xml you need to specify only a target in command line. For example: "ant target1".

Content Type application/soap+xml; charset=utf-8 was not supported by service

My case had a different solution. The client was using basichttpsbinding[1] and the service was using wshttpbinding.

I resolved the problem by changing the server binding to basichttpsbinding. Also, i had to set target framework to 4.5 by adding:

  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>

[1] the comunication was over https.

How do I call the base class constructor?

Regarding the alternative to super; you'd in most cases use use the base class either in the initialization list of the derived class, or using the Base::someData syntax when you are doing work elsewhere and the derived class redefines data members.

struct Base
{
    Base(char* name) { }
    virtual ~Base();
    int d;
};

struct Derived : Base
{
    Derived() : Base("someString") { }
    int d;
    void foo() { d = Base::d; }
};

Appending a vector to a vector

a.insert(a.end(), b.begin(), b.end());

or

a.insert(std::end(a), std::begin(b), std::end(b));

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end;
a.insert(end(a), begin(b), end(b));

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

getting the screen density programmatically in android?

This should work.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; //320
int height = dm.heightPixels; //480

For div to extend full height

This is an old question. CSS has evolved. There now is the vh (viewport height) unit, also new layout options like flexbox or CSS grid to achieve classical designs in cleaner ways.

How can I convert a Timestamp into either Date or DateTime object?

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

How to get table cells evenly spaced?

You can use CSS. One way is to set table-layout to fixed, which stops the table and it's children from sizing according to their content. You can then set a fixed width on the relevant td elements. This should do the trick:

table.PerformanceTable {
    table-layout: fixed;
    width: 500px;
}
    table.PerformanceTable td.PerformanceCell {
        width: 75px;
    }

Suggestions for for tidying up? You don't need the cellpadding or cellspacing attributes, or the TableRow and TableHeader classes. You can cover those off in CSS:

table {
    /* cellspacing */
    border-collapse: collapse;
    border-spacing: 0;
}
th {
    /* This covers the th elements */
}
tr {
    /* This covers the tr elements */
}
th, td {
    /* cellpadding */
    padding: 0;
}

You should use a heading (e.g. <h2>) instead of <span class="Emphasis"> and a <p> or a table <caption> instead of the Source <span>. You wouldn't need the <br> elements either, because you'd be using proper block level elements.

Calling a particular PHP function on form submit

Write this code

<?php
    if(isset($_POST['submit'])){
        echo 'Hello World';
    } 
?>

<html>
     <body>
         <form method="post">
             <input type="text" name="studentname">
             <input type="submit" name="submit" value="click">
         </form>
     </body>
</html>

Scale Image to fill ImageView width and keep aspect ratio

try with this simple line... add this line in your xml code in image view tag with out adding any dependency android:scaleType="fitXY"

How to cast an Object to an int

I use a one-liner when processing data from GSON:

int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;

Understanding esModuleInterop in tsconfig file

Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

While it might not be the best approach the closest equivalent I can think of that works is this with the support/compatibility library

getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();

or

getActivity().getFragmentManager().beginTransaction().remove(this).commit();

otherwise.

In addition you can use the backstack and pop it. However keep in mind that the fragment might not be on the backstack (depending on the fragmenttransaction that got it there..) or it might not be the last one that got onto the stack so popping the stack could remove the wrong one...

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

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.

Java Pass Method as Parameter

Last time I checked, Java is not capable of natively doing what you want; you have to use 'work-arounds' to get around such limitations. As far as I see it, interfaces ARE an alternative, but not a good alternative. Perhaps whoever told you that was meaning something like this:

public interface ComponentMethod {
  public abstract void PerfromMethod(Container c);
}

public class ChangeColor implements ComponentMethod {
  @Override
  public void PerfromMethod(Container c) {
    // do color change stuff
  }
}

public class ChangeSize implements ComponentMethod {
  @Override
  public void PerfromMethod(Container c) {
    // do color change stuff
  }
}

public void setAllComponents(Component[] myComponentArray, ComponentMethod myMethod) {
    for (Component leaf : myComponentArray) {
        if (leaf instanceof Container) { //recursive call if Container
            Container node = (Container) leaf;
            setAllComponents(node.getComponents(), myMethod);
        } //end if node
        myMethod.PerfromMethod(leaf);
    } //end looping through components
}

Which you'd then invoke with:

setAllComponents(this.getComponents(), new ChangeColor());
setAllComponents(this.getComponents(), new ChangeSize());

Regular expression for floating point numbers

I don't think that any of the answers on this page at the time of writing are correct (also many other suggestions elsewhere on SO are wrong too). The complication is that you have to match all of the following possibilities:

  • No decimal point (i.e. an integer value)
  • Digits both before and after the decimal point (e.g. 0.35 , 22.165)
  • Digits before the decimal point only (e.g. 0. , 1234.)
  • Digits after the decimal point only (e.g. .0 , .5678)

At the same time, you must ensure that there is at least one digit somewhere, i.e. the following are not allowed:

  • a decimal point on its own
  • a signed decimal point with no digits (i.e. +. or -.)
  • + or - on their own
  • an empty string

This seems tricky at first, but one way of finding inspiration is to look at the OpenJDK source for the java.lang.Double.valueOf(String) method (start at http://hg.openjdk.java.net/jdk8/jdk8/jdk, click "browse", navigate down /src/share/classes/java/lang/ and find the Double class). The long regex that this class contains caters for various possibilities that the OP probably didn't have in mind, but ignoring for simplicity the parts of it that deal with NaN, infinity, Hexadecimal notation and exponents, and using \d rather than the POSIX notation for a single digit, I can reduce the important parts of the regex for a signed floating point number with no exponent to:

[+-]?((\d+\.?\d*)|(\.\d+))

I don't think that there is a way of avoiding the (...)|(...) construction without allowing something that contains no digits, or forbidding one of the possibilities that has no digits before the decimal point or no digits after it.

Obviously in practice you will need to cater for trailing or preceding whitespace, either in the regex itself or in the code that uses it.

Convert nullable bool? to bool

This is an interesting variation on the theme. At first and second glances you would assume the true branch is taken. Not so!

bool? flag = null;
if (!flag ?? true)
{
    // false branch
}
else
{
    // true branch
}

The way to get what you want is to do this:

if (!(flag ?? true))
{
    // false branch
}
else
{
    // true branch
}

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

Capturing TAB key in text box

The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:

document.onkeydown = TabExample;

function TabExample(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var tabKey = 9;
  if(evt.keyCode == tabKey) {
    // do work
  }
}

Build a basic Python iterator

All answers on this page are really great for a complex object. But for those containing builtin iterable types as attributes, like str, list, set or dict, or any implementation of collections.Iterable, you can omit certain things in your class.

class Test(object):
    def __init__(self, string):
        self.string = string

    def __iter__(self):
        # since your string is already iterable
        return (ch for ch in self.string)
        # or simply
        return self.string.__iter__()
        # also
        return iter(self.string)

It can be used like:

for x in Test("abcde"):
    print(x)

# prints
# a
# b
# c
# d
# e

Can I use Class.newInstance() with constructor arguments?

I think this is exactly what you want http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html

Although it seems a dead thread, someone might find it useful

Replace a value in a data frame based on a conditional (`if`) statement

The easiest way to do this in one command is to use which command and also need not to change the factors into character by doing this:

junk$nm[which(junk$nm=="B")]<-"b"

How to update the value stored in Dictionary in C#?

  1. update - modify existent only. To avoid side effect of indexer use:

    int val;
    if (dic.TryGetValue(key, out val))
    {
        // key exist
        dic[key] = val;
    }
    
  2. update or (add new if value doesn't exist in dic)

    dic[key] = val;
    

    for instance:

    d["Two"] = 2; // adds to dictionary because "two" not already present
    d["Two"] = 22; // updates dictionary because "two" is now present
    

Styling every 3rd item of a list using CSS?

You can use the :nth-child selector for that

li:nth-child(3n) {
 /* your rules here */
}

Shell script to check if file exists

for entry in "/home/loc/etc/"/*
do

   if [ -s /home/loc/etc/$entry ]
   then
       echo "$entry File is available"
   else
       echo "$entry File is not available"
fi
done

Hope it helps

Hot deploy on JBoss - how do I make JBoss "see" the change?

This worked for me in Eclipse Mars with WildFly 11. Double-click on WildFly server under Servers to open the configuration page. In the Overview tab -> Publishing, choose "Automatically publish when resources change" and set the interval to 1. Next, Overview tab -> Application Reload Behavior, uncheck the use default pattern and set the pattern to \.jar$|\.class$. In the Deployment tab, uncheck Deploy project as compressed archives. Hope this helps.

CAST DECIMAL to INT

From the article you linked to:

The type can be one of the following values:

BINARY[(N)]

CHAR[(N)]

DATE

DATETIME

DECIMAL[(M[,D])]

SIGNED [INTEGER]

TIME

UNSIGNED [INTEGER]

Try SIGNED instead of INT

How to handle the modal closing event in Twitter Bootstrap?

There are two pair of modal events, one is "show" and "shown", the other is "hide" and "hidden". As you can see from the name, hide event fires when modal is about the be close, such as clicking on the cross on the top-right corner or close button or so on. While hidden is fired after the modal is actually close. You can test these events your self. For exampel:

$( '#modal' )
   .on('hide', function() {
       console.log('hide');
   })
   .on('hidden', function(){
       console.log('hidden');
   })
   .on('show', function() {
       console.log('show');
   })
   .on('shown', function(){
      console.log('shown' )
   });

And, as for your question, I think you should listen to the 'hide' event of your modal.

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

Include jQuery in the JavaScript Console

Turnkey solution :

Put your code in yourCode_here function. And prevent HTML without HEAD tag.

_x000D_
_x000D_
(function(head) {_x000D_
  var jq = document.createElement('script');_x000D_
  jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js";_x000D_
  ((head && head[0]) || document.firstChild).appendChild(jq);_x000D_
})(document.getElementsByTagName('head'));_x000D_
_x000D_
function jQueryReady() {_x000D_
  if (window.jQuery) {_x000D_
    jQuery.noConflict();_x000D_
    yourCode_here(jQuery);_x000D_
  } else {_x000D_
    setTimeout(jQueryReady, 100);_x000D_
  }_x000D_
}_x000D_
_x000D_
jQueryReady();_x000D_
_x000D_
function yourCode_here($) {_x000D_
  console.log("OK");_x000D_
  $("body").html("<h1>Hello world !</h1>");_x000D_
}
_x000D_
_x000D_
_x000D_

How can I change a button's color on hover?

a.button a:hover means "a link that's being hovered over that is a child of a link with the class button".

Go instead for a.button:hover.

What is the difference between canonical name, simple name and class name in Java Class?

It is interesting to note that getCanonicalName() and getSimpleName() can raise InternalError when the class name is malformed. This happens for some non-Java JVM languages, e.g., Scala.

Consider the following (Scala 2.11 on Java 8):

scala> case class C()
defined class C

scala> val c = C()
c: C = C()

scala> c.getClass.getSimpleName
java.lang.InternalError: Malformed class name
  at java.lang.Class.getSimpleName(Class.java:1330)
  ... 32 elided

scala> c.getClass.getCanonicalName
java.lang.InternalError: Malformed class name
  at java.lang.Class.getSimpleName(Class.java:1330)
  at java.lang.Class.getCanonicalName(Class.java:1399)
  ... 32 elided

scala> c.getClass.getName
res2: String = C

This can be a problem for mixed language environments or environments that dynamically load bytecode, e.g., app servers and other platform software.

Split data frame string column into multiple columns

This question is pretty old but I'll add the solution I found the be the simplest at present.

library(reshape2)
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
newColNames <- c("type1", "type2")
newCols <- colsplit(before$type, "_and_", newColNames)
after <- cbind(before, newCols)
after$type <- NULL
after

How to overlay density plots in R?

use lines for the second one:

plot(density(MyData$Column1))
lines(density(MyData$Column2))

make sure the limits of the first plot are suitable, though.

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

jQuery append and remove dynamic table row

Change ID to class :

$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');

$(".remCF").on('click',function(){
            $(this).parent().parent().remove();
        });

http://jsfiddle.net/7BHDm/1/

Play an audio file using jQuery when a button is clicked

Which approach?

You can play audio with <audio> tag or <object> or <embed>. Lazy loading(load when you need it) the sound is the best approach if its size is small. You can create the audio element dynamically, when its loaded you can start it with .play() and pause it with .pause().

Things we used

We will use canplay event to detect our file is ready to be played.

There is no .stop() function for audio elements. We can only pause them. And when we want to start from the beginning of the audio file we change its .currentTime. We will use this line in our example audioElement.currentTime = 0;. To achieve .stop() function we first pause the file then reset its time.

We may want to know the length of the audio file and the current playing time. We already learnt .currentTimeabove, to learn its length we use .duration.

Example Guide

  1. When document is ready we created an audio element dynamically
  2. We set its source with the audio we want to play.
  3. We used 'ended' event to start file again.

When the currentTime is equal to its duration audio file will stop playing. Whenever you use play(), it will start from the beginning.

  1. We used timeupdate event to update current time whenever audio .currentTime changes.
  2. We used canplay event to update information when file is ready to be played.
  3. We created buttons to play, pause, restart.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var audioElement = document.createElement('audio');_x000D_
    audioElement.setAttribute('src', 'http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3');_x000D_
    _x000D_
    audioElement.addEventListener('ended', function() {_x000D_
        this.play();_x000D_
    }, false);_x000D_
    _x000D_
    audioElement.addEventListener("canplay",function(){_x000D_
        $("#length").text("Duration:" + audioElement.duration + " seconds");_x000D_
        $("#source").text("Source:" + audioElement.src);_x000D_
        $("#status").text("Status: Ready to play").css("color","green");_x000D_
    });_x000D_
    _x000D_
    audioElement.addEventListener("timeupdate",function(){_x000D_
        $("#currentTime").text("Current second:" + audioElement.currentTime);_x000D_
    });_x000D_
    _x000D_
    $('#play').click(function() {_x000D_
        audioElement.play();_x000D_
        $("#status").text("Status: Playing");_x000D_
    });_x000D_
    _x000D_
    $('#pause').click(function() {_x000D_
        audioElement.pause();_x000D_
        $("#status").text("Status: Paused");_x000D_
    });_x000D_
    _x000D_
    $('#restart').click(function() {_x000D_
        audioElement.currentTime = 0;_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
    <h2>Sound Information</h2>_x000D_
    <div id="length">Duration:</div>_x000D_
    <div id="source">Source:</div>_x000D_
    <div id="status" style="color:red;">Status: Loading</div>_x000D_
    <hr>_x000D_
    <h2>Control Buttons</h2>_x000D_
    <button id="play">Play</button>_x000D_
    <button id="pause">Pause</button>_x000D_
    <button id="restart">Restart</button>_x000D_
    <hr>_x000D_
    <h2>Playing Information</h2>_x000D_
    <div id="currentTime">0</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Can JavaScript connect with MySQL?

If you want to connect to a MySQL database using JavaScript, you can use Node.js and a library called mysql. You can create queries, and get results as an array of registers. If you want to try it, you can use my project generator to create a backend and choose MySQL as the database to connect. Then, just expose your new REST API or GraphQL endpoint to your front and start working with your MySQL database.


OLD ANSWER LEFT BY NOSTALGIA

THEN

As I understand the question and correct me if I am wrong, it refers to the classic server model with JavaScript only on the client-side. In this classic model, with LAMP servers (Linux, Apache, MySQL, PHP) the language in contact with the database was PHP, so to request data to the database you need to write PHP scripts and echo the returning data to the client. Basically, the distribution of the languages according to physical machines was:

  1. Server Side: PHP and MySQL.
  2. Client Side: HTML/CSS and JavaScript.

This answered to an MVC model (Model, View, Controller) where we had the following functionality:

  1. MODEL: The model is what deals with the data, in this case, the PHP scripts that manage variables or that access data stored, in this case in our MySQL database and send it as JSON data to the client.
  2. VIEW: The view is what we see and it should be completely independent of the model. It just needs to show the data contained in the model, but it shouldn't have relevant data on it. In this case, the view uses HTML and CSS. HTML to create the basic structure of the view, and CSS to give the shape to this basic structure.
  3. CONTROLLER: The controller is the interface between our model and our view. In this case, the language used is JavaScript and it takes the data the model send us as a JSON package and put it inside the containers that offer the HTML structure. The way the controller interacts with the model is by using AJAX. We use GET and POST methods to call PHP scripts on the server-side and to catch the returned data from the server.

For the controller, we have really interesting tools like jQuery, as "low-level" library to control the HTML structure (DOM), and then new, more high-level ones as Knockout.js that allow us to create observers that connect different DOM elements updating them when events occur. There is also Angular.js by Google that works in a similar way, but seems to be a complete environment. To help you to choose among them, here you have two excellent analyses of the two tools: Knockout vs. Angular.js and Knockout.js vs. Angular.js. I am still reading. Hope they help you.

NOW

In modern servers based in Node.js, we use JavaScript for everything. Node.js is a JavaScript environment with many libraries that work with Google V8, Chrome JavaScript engine. The way we work with these new servers is:

  1. Node.js and Express: The mainframe where the server is built. We can create a server with a few lines of code or even use libraries like Express to make even easier to create the server. With Node.js and Express, we will manage the petitions to the server from the clients and will answer them with the appropriate pages.
  2. Jade: To create the pages we use a templating language, in this case, Jade, that allow us to write web pages as we were writing HTML but with differences (it take a little time but is easy to learn). Then, in the code of the server to answer the client's petitions, we just need to render the Jade code into a "real" HTML code.
  3. Stylus: Similar to Jade but for CSS. In this case, we use a middleware function to convert the stylus file into a real CSS file for our page.

Then we have a lot of packages we can install using the NPM (Node.js package manager) and use them directly in our Node.js server just requiring it (for those of you that want to learn Node.js, try this beginner tutorial for an overview). And among these packages, you have some of them to access databases. Using this you can use JavaScript on the server-side to access My SQL databases.

But the best you can do if you are going to work with Node.js is to use the new NoSQL databases like MongoDB, based on JSON files. Instead of storing tables like MySQL, it stores the data in JSON structures, so you can put different data inside each structure like long numeric vectors instead of creating huge tables for the size of the biggest one.

I hope this brief explanation becomes useful to you, and if you want to learn more about this, here you have some resources you can use:

  • Egghead: This site is full of great short tutorials about JavaScript and its environment. It worths a try. And the make discounts from time to time.
  • Code School: With a free and very interesting course about Chrome Developer tools to help you to test the client-side.
  • Codecademy: With free courses about HTML, CSS, JavaScript, jQuery, and PHP that you can follow with online examples.
  • 10gen Education: With everything you need to know about MongoDB in tutorials for different languages.
  • W3Schools: This one has tutorials about all this and you can use it as a reference place because it has a lot of shortcode examples really useful.
  • Udacity: A place with free video courses about different subjects with a few interesting ones about web development and my preferred, an amazing WebGL course for 3D graphics with JavaScript.

I hope it helps you to start.

Have fun!

Get table name by constraint name

SELECT owner, table_name
  FROM dba_constraints
 WHERE constraint_name = <<your constraint name>>

will give you the name of the table. If you don't have access to the DBA_CONSTRAINTS view, ALL_CONSTRAINTS or USER_CONSTRAINTS should work as well.

Convert canvas to PDF

So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.

  // Download button
  $("#download-image").on('click', function () {
    let width = __CANVAS.width; 
    let height = __CANVAS.height;

    //set the orientation
    if(width > height){
      pdf = new jsPDF('l', 'px', [width, height]);
    }
    else{
      pdf = new jsPDF('p', 'px', [height, width]);
    }
    //then we get the dimensions from the 'pdf' file itself
    width = pdf.internal.pageSize.getWidth();
    height = pdf.internal.pageSize.getHeight();
    pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
    pdf.save("download.pdf");
  });

Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476

Don't reload application when orientation changes

just use : android:configChanges="keyboardHidden|orientation"

How to create a hash or dictionary object in JavaScript

if( a['desiredKey'] !== undefined )
{
   // it exists
}

Difference between PACKETS and FRAMES

Packets and Frames are the names given to Protocol data units (PDUs) at different network layers

  • Segments/Datagrams are units of data in the Transport Layer.

    In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):

    Datagram

    A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.

  • Packets are units of data in the Network Layer (IP in case of the Internet)

  • Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).

enter image description here

How to remove specific element from an array using python

The sane way to do this is to use zip() and a List Comprehension / Generator Expression:

filtered = (
    (email, other) 
        for email, other in zip(emails, other_list) 
            if email == '[email protected]')

new_emails, new_other_list = zip(*filtered)

Also, if your'e not using array.array() or numpy.array(), then most likely you are using [] or list(), which give you Lists, not Arrays. Not the same thing.

How do I check if a column is empty or null in MySQL?

If you want to have NULL values presented last when doing an ORDER BY, try this:

SELECT * FROM my_table WHERE NULLIF(some_col, '') IS NULL;

Mac OS X and multiple Java versions

First, you need to make certain you have multiple JAVA versions installed. Open a new Terminal window and input:

/usr/libexec/java_home -V

Your output should look like:

Matching Java Virtual Machines (2):
11.0.1, x86_64: "Java SE 11.0.1" /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
1.8.0_201, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home

Note that there are two JDKs available. If you don’t notice the Java version you need to switch to, download and install the appropriate one from here (JDK 8 is represented as 1.8) . Once you have installed the appropriate JDK, repeat this step.

  1. Take note of the JDK version you want to switch to. For example, “11.0” and “1.8” are the JDK versions available in the example above.

  2. Switch to the desired version. For example, if you wish to switch to JDK 8, input the following line:

    export JAVA_HOME=/usr/libexec/java_home -v 1.8

For 11.0, switch “1.8” with “11.0” 4. Check your JDK version by inputting into Terminal:

java -version

If you have followed all the steps correctly, the JDK version should correlate with the one you specified in the last step. 5. (Optional) To make this the default JDK version, input the following in Terminal:

open ~/.bash_profile

Then, add your Terminal input from step 3 to this file:

SWITCH TO JAVA VERSION 8

export JAVA_HOME=`/usr/libexec/java_home -v 1.8`

Save and close the file.

How can I easily view the contents of a datatable or dataview in the immediate window

and if you want this anywhere... to be a helper on DataTable this assumes you want to capture the output to Log4Net but the excellent starting example I worked against just dumps to the console... This one also has editable column width variable nMaxColWidth - ultimately I will pass that from whatever context...

public static class Helpers
    {
        private static ILog Log = Global.Log ?? LogManager.GetLogger("MyLogger");
        /// <summary>
        /// Dump contents of a DataTable to the log
        /// </summary>
        /// <param name="table"></param>
        public static void DebugTable(this DataTable table)
        {
            Log?.Debug("--- DebugTable(" + table.TableName + ") ---");
            var nRows = table.Rows.Count;
            var nCols = table.Columns.Count;
            var nMaxColWidth = 32;

            // Column Headers

            var sColFormat = @"{0,-" + nMaxColWidth + @"} | ";
            var sLogMessage = string.Empty;
            for (var i = 0; i < table.Columns.Count; i++)
            {
                sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, table.Columns[i].ToString()));
            }
            //Debug.Write(Environment.NewLine);
            Log?.Debug(sLogMessage);

            var sUnderScore = string.Empty;
            var sDashes = string.Empty;
            for (var j = 0; j <= nMaxColWidth; j++)
            {
                sDashes = sDashes + "-";
            }


            for (var i = 0; i < table.Columns.Count; i++)
            {
                sUnderScore = string.Concat(sUnderScore, sDashes + "|-");
            }

            sUnderScore = sUnderScore.TrimEnd('-');

            //Debug.Write(Environment.NewLine);
            Log?.Debug(sUnderScore);

            // Data
            for (var i = 0; i < nRows; i++)
            {
                DataRow row = table.Rows[i];
                //Debug.WriteLine("{0} {1} ", row[0], row[1]);
                sLogMessage = string.Empty;

                for (var j = 0; j < nCols; j++)
                {
                    string s = row[j].ToString();
                    if (s.Length > nMaxColWidth) s = s.Substring(0, nMaxColWidth - 3) + "...";
                    sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, s));
                }

                Log?.Debug(sLogMessage);
                //Debug.Write(Environment.NewLine);
            }           
            Log?.Debug(sUnderScore);
        }
}

How to remove the character at a given index from a string in C?

The following will extends the problem a bit by removing from the first string argument any character that occurs in the second string argument.

/*
 * delete one character from a string
 */
static void
_strdelchr( char *s, size_t i, size_t *a, size_t *b)
{
  size_t        j;

  if( *a == *b)
    *a = i - 1;
  else
    for( j = *b + 1; j < i; j++)
      s[++(*a)] = s[j];
  *b = i;
}

/*
 * delete all occurrences of characters in search from s
 * returns nr. of deleted characters
 */
size_t
strdelstr( char *s, const char *search)
{ 
  size_t        l               = strlen(s);
  size_t        n               = strlen(search);
  size_t        i;
  size_t        a               = 0;
  size_t        b               = 0;

  for( i = 0; i < l; i++)
    if( memchr( search, s[i], n))
      _strdelchr( s, i, &a, &b);
  _strdelchr( s, l, &a, &b);
  s[++a] = '\0';
  return l - a;
}

How to execute an oracle stored procedure?

Execute is sql*plus syntax .. try wrapping your call in begin .. end like this:

begin 
    temp_proc;
end;

(Although Jeffrey says this doesn't work in APEX .. but you're trying to get this to run in SQLDeveloper .. try the 'Run' menu there.)

Can a local variable's memory be accessed outside its scope?

That's classic undefined behaviour that's been discussed here not two days ago -- search around the site for a bit. In a nutshell, you were lucky, but anything could have happened and your code is making invalid access to memory.

Difference between Spring MVC and Struts MVC

Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that you can choose an appropriate base class: if you don't have a form, you don't need a form controller. This is a major difference to Struts

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

Add this code after sending message and before getting message from server

recyclerView.scrollToPosition(mChatList.size() - 1);

Difference between id and name attributes in HTML

Generally, it is assumed that name is always superseded by id. This is true, to some extent, but not for form fields and frame names, practically speaking. For example, with form elements the name attribute is used to determine the name-value pairs to be sent to a server-side program and should not be eliminated. Browsers do not use id in that manner. To be on the safe side, you could use name and id attributes on form elements. So, we would write the following:

<form id="myForm" name="myForm">
     <input type="text" id="userName" name="userName" />
</form>

To ensure compatibility, having matching name and id attribute values when both are defined is a good idea. However, be careful—some tags, particularly radio buttons, must have nonunique name values, but require unique id values. Once again, this should reference that id is not simply a replacement for name; they are different in purpose. Furthermore, do not discount the old-style approach, a deep look at modern libraries shows such syntax style used for performance and ease purposes at times. Your goal should always be in favor of compatibility.

Now in most elements, the name attribute has been deprecated in favor of the more ubiquitous id attribute. However, in some cases, particularly form fields (<button>, <input>, <select>, and <textarea>), the name attribute lives on because it continues to be required to set the name-value pair for form submission. Also, we find that some elements, notably frames and links, may continue to use the name attribute because it is often useful for retrieving these elements by name.

There is a clear distinction between id and name. Very often when name continues on, we can set the values the same. However, id must be unique, and name in some cases shouldn’t—think radio buttons. Sadly, the uniqueness of id values, while caught by markup validation, is not as consistent as it should be. CSS implementation in browsers will style objects that share an id value; thus, we may not catch markup or style errors that could affect our JavaScript until runtime.

This is taken from the book JavaScript- The Complete Reference by Thomas-Powell

sql insert into table with select case values

You have the alias inside of the case, it needs to be outside of the END:

Insert into TblStuff (FullName,Address,City,Zip)
Select
  Case
    When Middle is Null 
    Then Fname + LName
    Else Fname +' ' + Middle + ' '+ Lname
  End as FullName,
  Case
    When Address2 is Null Then Address1
    else Address1 +', ' + Address2 
  End as  Address,
  City as City,
  Zip as Zip
from tblImport

How to launch an EXE from Web page (asp.net)

How about something like:

<a href="\\DangerServer\Downloads\MyVirusArchive.exe" 
  type="application/octet-stream">Don't download this file!</a>

Calling C/C++ from Python?

The question is how to call a C function from Python, if I understood correctly. Then the best bet are Ctypes (BTW portable across all variants of Python).

>>> from ctypes import *
>>> libc = cdll.msvcrt
>>> print libc.time(None)
1438069008
>>> printf = libc.printf
>>> printf("Hello, %s\n", "World!")
Hello, World!
14
>>> printf("%d bottles of beer\n", 42)
42 bottles of beer
19

For a detailed guide you may want to refer to my blog article.

How can I access global variable inside class in Python

It is very simple to make a variable global in a class:

a = 0

class b():
    global a
    a = 10

>>> a
10

Why is json_encode adding backslashes?

Can anyone tell me why json_encode adds slashes?

Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.

Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.

It doesn't. In JSON "/" and "\/" are equivalent.

The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

It is a new signing mechanism introduced in Android 7.0, with additional features designed to make the APK signature more secure.

It is not mandatory. You should check BOTH of those checkboxes if possible, but if the new V2 signing mechanism gives you problems, you can omit it.

So you can just leave V2 unchecked if you encounter problems, but should have it checked if possible.

UPDATED: This is now mandatory when targeting Android 11.

Singletons vs. Application Context in Android?

My 2 cents:

I did notice that some singleton / static fields were reseted when my activity was destroyed. I noticed this on some low end 2.3 devices.

My case was very simple : I just have a private filed "init_done" and a static method "init" that I called from activity.onCreate(). I notice that the method init was re-executing itself on some re-creation of the activity.

While I cannot prove my affirmation, It may be related to WHEN the singleton/class was created/used first. When the activity get destroyed/recycled, it seem that all class that only this activity refer are recycled too.

I moved my instance of singleton to a sub class of Application. I acces them from the application instance. and, since then, did not notice the problem again.

I hope this can help someone.

delete all from table

There is a mySQL bug report from 2004 that still seems to have some validity. It seems that in 4.x, this was fastest:

DROP table_name
CREATE TABLE table_name

TRUNCATE table_name was DELETE FROM internally back then, providing no performance gain.

This seems to have changed, but only in 5.0.3 and younger. From the bug report:

[11 Jan 2005 16:10] Marko Mäkelä

I've now implemented fast TRUNCATE TABLE, which will hopefully be included in MySQL 5.0.3.

Write a mode method in Java to find the most frequently occurring element in an array

You should be able to do this in N operations, meaning in just one pass, O(n) time.

Use a map or int[] (if the problem is only for ints) to increment the counters, and also use a variable that keeps the key which has the max count seen. Everytime you increment a counter, ask what the value is and compare it to the key you used last, if the value is bigger update the key.

public class Mode {
public static int mode(final int[] n) {
    int maxKey = 0;
    int maxCounts = 0;

    int[] counts = new int[n.length];

    for (int i=0; i < n.length; i++) {
        counts[n[i]]++;
        if (maxCounts < counts[n[i]]) {
            maxCounts = counts[n[i]];
            maxKey = n[i];
        }
    }
    return maxKey;
}

public static void main(String[] args) {
    int[] n = new int[] { 3,7,4,1,3,8,9,3,7,1 };
    System.out.println(mode(n));
}
}

Escaping Double Quotes in Batch Script

Google eventually came up with the answer. The syntax for string replacement in batch is this:

set v_myvar=replace me
set v_myvar=%v_myvar:ace=icate%

Which produces "replicate me". My script now looks like this:

@echo off
set v_params=%*
set v_params=%v_params:"=\"%
call bash -c "g++-linux-4.1 %v_params%"

Which replaces all instances of " with \", properly escaped for bash.

MySQL Stored procedure variables from SELECT statements

Corrected a few things and added an alternative select - delete as appropriate.

DELIMITER |

CREATE PROCEDURE getNearestCities
(
IN p_cityID INT -- should this be int unsigned ?
)
BEGIN

DECLARE cityLat FLOAT; -- should these be decimals ?
DECLARE cityLng FLOAT;

    -- method 1
    SELECT lat,lng into cityLat, cityLng FROM cities WHERE cities.cityID = p_cityID;

    SELECT 
     b.*, 
     HAVERSINE(cityLat,cityLng, b.lat, b.lng) AS dist 
    FROM 
     cities b 
    ORDER BY 
     dist 
    LIMIT 10;

    -- method 2
    SELECT   
      b.*, 
      HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
    FROM     
      cities AS a
    JOIN cities AS b on a.cityID = p_cityID
    ORDER BY 
      dist
    LIMIT 10;

END |

delimiter ;

Using StringWriter for XML Serialization

One problem with StringWriter is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:

public sealed class StringWriterWithEncoding : StringWriter
{
    public override Encoding Encoding { get; }

    public StringWriterWithEncoding (Encoding encoding)
    {
        Encoding = encoding;
    }    
}

Or if you only need UTF-8 (which is all I often need):

public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.

Allowing Untrusted SSL Certificates with HttpClient

If you are using System.Net.Http.HttpClient I believe correct pattern is

var handler = new HttpClientHandler() 
{ 
    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};

var http = new HttpClient(handler);
var res = http.GetAsync(url);

Extreme wait-time when taking a SQL Server database offline

Closing the instance of SSMS (SQL Service Manager) from which the request was made solved the problem for me.....

How to view the list of compile errors in IntelliJ?

A more up to date answer for anyone else who comes across this:

(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)

Compile automatically:

To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option

Show all errors in one place:

The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.

Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.

While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

Refresh Part of Page (div)

Usefetch and innerHTML to load div content

_x000D_
_x000D_
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"

async function refresh() {
  btn.disabled = true;
  dynamicPart.innerHTML = "Loading..."
  dynamicPart.innerHTML = await(await fetch(url)).text();
  setTimeout(refresh,2000);
}
_x000D_
<div id="staticPart">
  Here is static part of page

  <button id="btn" onclick="refresh()">
    Click here to start refreshing every 2s
  </button>
</div>

<div id="dynamicPart">Dynamic part</div>
_x000D_
_x000D_
_x000D_

How to return 2 values from a Java method?

You don't need to create your own class to return two different values. Just use a HashMap like this:

private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
    Toy toyWithSpatial = firstValue;
    GameLevel levelToyFound = secondValue;

    HashMap<Toy,GameLevel> hm=new HashMap<>();
    hm.put(toyWithSpatial, levelToyFound);
    return hm;
}

private void findStuff()
{
    HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
    Toy firstValue = hm.keySet().iterator().next();
    GameLevel secondValue = hm.get(firstValue);
}

You even have the benefit of type safety.

What's the best way to break from nested loops in JavaScript?

Wrap that up in a function and then just return.

Executing multiple SQL queries in one statement with PHP

With mysqli you're able to use multiple statements for real using mysqli_multi_query().

Read more on multiple statements in the PHP Docs.

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Change a branch name in a Git repo

Assuming you're currently on the branch you want to rename:

git branch -m newname

This is documented in the manual for git-branch, which you can view using

man git-branch

or

git help branch

Specifically, the command is

git branch (-m | -M) [<oldbranch>] <newbranch>

where the parameters are:

   <oldbranch>
       The name of an existing branch to rename.

   <newbranch>
       The new name for an existing branch. The same restrictions as for <branchname> apply.

<oldbranch> is optional, if you want to rename the current branch.

Where is adb.exe in windows 10 located?

Since you already have Android Studio installed, and require the environment variable ANDROID_HOME to be set, the easy way to do this is to add %ANDROID_HOME%\platform-tools to your path.

Change a Django form field to a hidden field

For normal form you can do

class MyModelForm(forms.ModelForm):
    slug = forms.CharField(widget=forms.HiddenInput())

If you have model form you can do the following

class MyModelForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        fields = ('slug', 'ext')
        widgets = {'slug': forms.HiddenInput()}

You can also override __init__ method

class Myform(forms.Form):
    def __init__(self, *args, **kwargs):
        super(Myform, self).__init__(*args, **kwargs)
        self.fields['slug'].widget = forms.HiddenInput()

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

Convert an image to grayscale in HTML/CSS

For grayscale as a percent in Firefox, use saturate filter instead: (search for 'saturate')

filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='saturate'><feColorMatrix in='SourceGraphic' type='saturate' values='0.2' /></filter></svg>#saturate"

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT i.e 204 No Content as in place of HttpStatus.OK

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Any value of T will be ignored for 204, but not for 404

  public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
            LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
            final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
            LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$

            if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
                LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
                 return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
            } else {
               LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
                return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
            }

    }

How to avoid page refresh after button click event in asp.net

After button click event complete your any task...last line copy and past it...Is's Working Fine...C# in Asp.Net

Page.Header.Controls.Add(new LiteralControl(string.Format(@" <META http-equiv='REFRESH' content=3.1;url={0}> ", Request.Url.AbsoluteUri)));

NLS_NUMERIC_CHARACTERS setting for decimal

To know SESSION decimal separator, you can use following SQL command:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select SUBSTR(value,1,1) as "SEPARATOR"
      ,'using NLS-PARAMETER' as "Explanation"
  from nls_session_parameters
  where parameter = 'NLS_NUMERIC_CHARACTERS'

UNION ALL

select SUBSTR(0.5,1,1) as "SEPARATOR" 
      ,'using NUMBER IMPLICIT CASTING' as "Explanation"
  from DUAL;

The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS table. The decimal separator is the first character of the returned value.

The second SELECT command convert IMPLICITELY the 0.5 rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.

The both command return same value.

I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.

To test what I say, I have used following SQL commands:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;

DECLARE
    S VARCHAR2(10) := '?';
BEGIN

    select .5 INTO S from dual;

    DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/

The shorter command to know decimal separator is:

SELECT .5 FROM DUAL;

That return 0,5 if decimal separator is a COMMA and 0.5 if decimal separator is a POINT.

How to catch exception correctly from http.request()?

The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"

Then make sure to access the Observable class as Rx.Observable.

How do I access Configuration in any class in ASP.NET Core?

In 8-2017 Microsoft came out with System.Configuration for .NET CORE v4.4. Currently v4.5 and v4.6 preview.

For those of us, who works on transformation from .Net Framework to CORE, this is essential. It allows to keep and use current app.config files, which can be accessed from any assembly. It is probably even can be an alternative to appsettings.json, since Microsoft realized the need for it. It works same as before in FW. There is one difference:

In the web applications, [e.g. ASP.NET CORE WEB API] you need to use app.config and not web.config for your appSettings or configurationSection. You might need to use web.config but only if you deploying your site via IIS. You place IIS-specific settings into web.config

I've tested it with netstandard20 DLL and Asp.net Core Web Api and it is all working.

Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.

Check if input value is empty and display an alert

Check empty input with removing space(if user enter space) from input using trim

$(document).ready(function(){     
       $('#button').click(function(){
            if($.trim($('#fname').val()) == '')
           {
               $('#fname').css("border-color", "red");
               alert("Empty"); 
           }
     });
});

How to undo a git merge with conflicts

Assuming you are using the latest git,

git merge --abort

Python string to unicode

>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…

PHP - Move a file into a different folder on the server

Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure

How to flush output after each `echo` call?

Note if you are on certain shared hosting sites like Dreamhost you can't disable PHP output buffering at all without going through different routes:

Changing the output buffer cache If you are using PHP FastCGI, the PHP functions flush(), ob_flush(), and ob_implicit_flush() will not function as expected. By default, output is buffered at a higher level than PHP (specifically, by the Apache module mod_deflate which is similar in form/function to mod_gzip).

If you need unbuffered output, you must either use CGI (instead of FastCGI) or contact support to request that mod_deflate is disabled for your site.

https://help.dreamhost.com/hc/en-us/articles/214202188-PHP-overview

How to pass a function as a parameter in Java?

Java does not (yet) support closures. But there are other languages like Scala and Groovy which run in the JVM and do support closures.

TCP vs UDP on video stream

Drawbacks of using TCP for live video:

  1. Typically live video-streaming appliances are not designed with TCP streaming in mind. If you use TCP, the OS must buffer the unacknowledged segments for every client. This is undesirable, particularly in the case of live events; presumably your list of simultaneous clients is long due to the singularity of the event. Pre-recorded video-casts typically don't have as much of a problem with this because viewers stagger their replay activity; therefore TCP is more appropriate for replaying a video-on-demand.
  2. IP multicast significantly reduces video bandwidth requirements for large audiences; TCP prevents the use of IP multicast, but UDP is well-suited for IP multicast.
  3. Live video is normally a constant-bandwidth stream recorded off a camera; pre-recorded video streams come off a disk. The loss-backoff dynamics of TCP make it harder to serve live video when the source streams are at a constant bandwidth (as would happen for a live-event). If you buffer to disk off a camera, be sure you have enough buffer for unpredictable network events and variable TCP send/backoff rates. UDP gives you much more control for this application since UDP doesn't care about network transport layer drops.

FYI, please don't use the word "packages" when describing networks. Networks send "packets".

HttpClient 4.0.1 - how to release connection?

I've got this problem when I use HttpClient in Multithread envirnoment (Servlets). One servlet still holds connection and another one want to get connection.

Solution:

version 4.0 use ThreadSafeClientConnManager

version 4.2 use PoolingClientConnectionManager

and set this two setters:

setDefaultMaxPerRoute
setMaxTotal

docker error - 'name is already in use by container'

I was running into this issue that when I run docker rm (which usually works) I would get:

Error: No such image

The easiest solution to this is removing all stopped containers by running:

docker container prune

Run Excel Macro from Outside Excel Using VBScript From Command Line

I tried to adapt @Siddhart's code to a relative path to run my open_form macro, but it didn't seem to work. Here was my first attempt. My working solution is below.

Option Explicit

Dim xlApp, xlBook
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open(curDir & "Excels\CLIENTES.xlsb", 0, true)
xlApp.Run "open_form"
xlBook.Close
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Finished."

EDIT

I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:

Issues I was facing:

1 - I did not want to use the Workbook_Open Event as the excel is locked in read only. 2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.

I first wrote a macro to launch my userform while hiding the application:

Sub open_form()
 Application.Visible = False
 frmAddClient.Show vbModeless
End Sub

I then created a vbs to launch this macro (doing it with a relative path has been tricky):

dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing

Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"

And I finally did a batch file to execute the VBS...

@echo off
pushd %~dp0
cscript Add_Client.vbs

Note that I have also included the "Set back to visible" in my Userform_QueryClose:

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    ThisWorkbook.Close SaveChanges:=True
    Application.Visible = True
    Application.Quit
End Sub

Anyway, thanks for your help, and I hope this will help if someone needs it

Convert char array to single int?

If you are using C++11, you should probably use stoi because it can distinguish between an error and parsing "0".

try {
    int number = std::stoi("1234abc");
} catch (std::exception const &e) {
    // This could not be parsed into a number so an exception is thrown.
    // atoi() would return 0, which is less helpful if it could be a valid value.
}

It should be noted that "1234abc" is implicitly converted from a char[] to a std:string before being passed to stoi().

Replace only text inside a div using jquery

Another approach is keep that element, change the text, then append that element back

const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

I`ve written

React.component

instead of React.Component That was my issue)) and was looking for this more than half an hour.

What character represents a new line in a text area

&#10;- Line Feed and &#13; Carriage Return

These HTML entities will insert a new line or carriage return inside a text area.

Regex to match URL end-of-line or "/" character

To match either / or end of content, use (/|\z)

This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).


To put that with an updated version of what you had:

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)

Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+? ) rather than matching anything and everything ( .* )

How do I read the contents of a Node.js stream into a string variable?

I had more luck using like that :

let string = '';
readstream
    .on('data', (buf) => string += buf.toString())
    .on('end', () => console.log(string));

I use node v9.11.1 and the readstream is the response from a http.get callback.

Simple (non-secure) hash function for JavaScript?

Check out this MD5 implementation for JavaScript. Its BSD Licensed and really easy to use. Example:

md5 = hex_md5("message to digest")

Can an interface extend multiple interfaces in Java?

I think your confusion lies with multiple inheritance, in which it is bad practise to do so and in Java this is also not possible. However, implementing multiple interfaces is allowed in Java and it is also safe.

Word count from a txt file program

you can do this:

file= open(r'D:\\zzzz\\names2.txt')
file_split=set(file.read().split())
print(len(file_split))

How to install Boost on Ubuntu

Actually you don't need "install" or "compile" anything before using Boost in your project. You can just download and extract the Boost library to any location on your machine, which is usually like /usr/local/.

When you compile your code, you can just indicate the compiler where to find the libraries by -I. For example, g++ -I /usr/local/boost_1_59_0 xxx.hpp.

What is a Subclass

A subclass is a class that extends another class.

public class BaseClass{
    public String getFoo(){
        return "foo";
    }
}

public class SubClass extends BaseClass{
}

Then...

System.out.println(new SubClass().getFoo());

Will print:

foo

This works because a subclass inherits the functionality of the class it extends.

Getting the SQL from a Django QuerySet

You print the queryset's query attribute.

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"

String concatenation: concat() vs "+" operator

For the sake of completeness, I wanted to add that the definition of the '+' operator can be found in the JLS SE8 15.18.1:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).

About the implementation the JLS says the following:

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.

So judging from the 'a Java compiler may use the StringBuffer class or a similar technique to reduce', different compilers could produce different byte-code.

Microsoft.ACE.OLEDB.12.0 is not registered

Just install 32bit version of ADBE in passive mode:

run cmd in administrator mode and run this code:

AccessDatabaseEngine.exe /passive

http://www.microsoft.com/en-us/download/details.aspx?id=13255

Optimal way to concatenate/aggregate strings

Are methods using FOR XML PATH like below really that slow? Itzik Ben-Gan writes that this method has good performance in his T-SQL Querying book (Mr. Ben-Gan is a trustworthy source, in my view).

create table #t (id int, name varchar(20))

insert into #t
values (1, 'Matt'), (1, 'Rocks'), (2, 'Stylus')

select  id
        ,Names = stuff((select ', ' + name as [text()]
        from #t xt
        where xt.id = t.id
        for xml path('')), 1, 2, '')
from #t t
group by id

Application not picking up .css file (flask/python)

One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

Checking if a SQL Server login already exists

what are you exactly want check for login or user ? a login is created on server level and a user is created at database level so a login is unique in server

also a user is created against a login, a user without login is an orphaned user and is not useful as u cant carry out sql server login without a login

maybe u need this

check for login

select 'X' from master.dbo.syslogins where loginname=<username>

the above query return 'X' if login exists else return null

then create a login

CREATE LOGIN <username> with PASSWORD=<password>

this creates a login in sql server .but it accepts only strong passwords

create a user in each database you want to for login as

CREATE USER <username> for login <username>

assign execute rights to user

 GRANT EXECUTE TO <username>

YOU MUST HAVE SYSADMIN permissions or say 'sa' for short

you can write a sql procedure for that on a database

create proc createuser
(
@username varchar(50),
@password varchar(50)
)
as
begin
if not exists(select 'X' from master.dbo.syslogins where loginname=@username)
begin
 if not exists(select 'X' from sysusers where name=@username)
 begin
exec('CREATE LOGIN '+@username+' WITH PASSWORD='''+@password+'''')
exec('CREATE USER '+@username+' FOR LOGIN '+@username)
exec('GRANT EXECUTE TO '+@username)
end
end
end

Visual Studio Code pylint: Unable to import 'protorpc'

I've not played around with all possibilities, but at least I had the impression that this could be a python version related issue. No idea why, I just trusted my gut.

Thus I just changed the pythonPath to python3 (default: python):

"python.pythonPath": "python3"

I reinstalled the dependencies (including pylint!!!) with

pip3 install <package> --user

... and after restarting vs code, everything looked fine.

HTH Kai

Creating an Array from a Range in VBA

In addition to solutions proposed, and in case you have a 1D range to 1D array, i prefer to process it through a function like below. The reason is simple: If for any reason your range is reduced to 1 element range, as far as i know the command Range().Value will not return a variant array but just a variant and you will not be able to assign a variant variable to a variant array (previously declared).

I had to convert a variable size range to a double array, and when the range was of 1 cell size, i was not able to use a construct like range().value so i proceed with a function like below.

Public Function Rng2Array(inputRange As Range) As Double()

    Dim out() As Double    
    ReDim out(inputRange.Columns.Count - 1)

    Dim cell As Range
    Dim i As Long
    For i = 0 To inputRange.Columns.Count - 1
        out(i) = inputRange(1, i + 1) 'loop over a range "row"
    Next

    Rng2Array = out  
End Function

Is it possible to use argsort in descending order?

As @Kanmani hinted, an easier to interpret implementation may use numpy.flip, as in the following:

import numpy as np

avgDists = np.array([1, 8, 6, 9, 4])
ids = np.flip(np.argsort(avgDists))
print(ids)

By using the visitor pattern rather than member functions, it is easier to read the order of operations.

Convert int to ASCII and back in Python

ASCII to int:

ord('a')

gives 97

And back to a string:

  • in Python2: str(unichr(97))
  • in Python3: chr(97)

gives 'a'

How to check if a string starts with "_" in PHP?

To build on pinusnegra's answer, and in response to Gumbo's comment on that answer:

function has_leading_underscore($string) {

    return $string[0] === '_';

}

Running on PHP 5.3.0, the following works and returns the expected value, even without checking if the string is at least 1 character in length:

echo has_leading_underscore('_somestring').', ';
echo has_leading_underscore('somestring').', ';
echo has_leading_underscore('').', ';
echo has_leading_underscore(null).', ';
echo has_leading_underscore(false).', ';
echo has_leading_underscore(0).', ';
echo has_leading_underscore(array('_foo', 'bar'));

/*
 * output: true, false, false, false, false, false, false
 */

I don't know how other versions of PHP will react, but if they all work, then this method is probably more efficient than the substr route.

How to declare an array inside MS SQL Server Stored Procedure?

Great question and great idea, but in SQL you'll need to do this:

For data type datetime, something like this-

declare @BeginDate    datetime = '1/1/2016',
        @EndDate      datetime = '12/1/2016'
create table #months (dates datetime)
declare @var datetime = @BeginDate
   while @var < dateadd(MONTH, +1, @EndDate)
   Begin
          insert into #months Values(@var)
          set @var = Dateadd(MONTH, +1, @var)
   end

If all you really want is numbers, do this-

create table #numbas (digit int)
declare @var int = 1        --your starting digit
    while @var <= 12        --your ending digit
    begin
        insert into #numbas Values(@var)
        set @var = @var +1
    end

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

GoogleTest: How to skip a test?

For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.

#include <gtest/gtest.h>

const bool skip_some_test = true;

bool some_test_was_run = false;

void someTest() {
   EXPECT_TRUE(!skip_some_test);
   some_test_was_run = true;
}

TEST(BasicTest, Sanity) {
   EXPECT_EQ(1, 1);
   if(!skip_some_test) {
      someTest();
      EXPECT_TRUE(some_test_was_run);
   }
}

This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.

Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.

As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.

The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.

You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.

How to put text in the upper right, or lower right corner of a "box" using css

_x000D_
_x000D_
<div style="position: relative; width: 250px;">_x000D_
  <div style="position: absolute; top: 0; right: 0; width: 100px; text-align:right;">_x000D_
    here_x000D_
  </div>_x000D_
  <div style="position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;">_x000D_
    and here_x000D_
  </div>_x000D_
  Lorem Ipsum etc <br />_x000D_
  blah <br />_x000D_
  blah blah <br />_x000D_
  blah <br />_x000D_
  lorem ipsums_x000D_
</div>
_x000D_
_x000D_
_x000D_

Gets you pretty close, although you may need to tweak the "top" and "bottom" values.

Resizing SVG in html?

you can resize it by displaying svg in image tag and size image tag i.e.

<img width="200px" src="lion.svg"></img>

What does it mean when Statement.executeUpdate() returns -1?

As the statement executed is not actually DML (eg UPDATE, INSERT or EXECUTE), but a piece of T-SQL which contains DML, I suspect it is not treated as an update-query.

Section 13.1.2.3 of the JDBC 4.1 specification states something (rather hard to interpret btw):

When the method execute returns true, the method getResultSet is called to retrieve the ResultSet object. When execute returns false, the method getUpdateCount returns an int. If this number is greater than or equal to zero, it indicates the update count returned by the statement. If it is -1, it indicates that there are no more results.

Given this information, I guess that executeUpdate() internally does an execute(), and then - as execute() will return false - it will return the value of getUpdateCount(), which in this case - in accordance with the JDBC spec - will return -1.

This is further corroborated by the fact 1) that the Javadoc for Statement.executeUpdate() says:

Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

And 2) that the Javadoc for Statement.getUpdateCount() specifies:

the current result as an update count; -1 if the current result is a ResultSet object or there are no more results

Just to clarify: given the Javadoc for executeUpdate() the behavior is probably wrong, but it can be explained.

Also as I commented elsewhere, the -1 might just indicate: maybe something was changed, but we simply don't know, or we can't give an accurate number of changes (eg because in this example it is a piece of T-SQL that is executed).

remove duplicates from sql union

Union will remove duplicates. Union All does not.

How to check existence of user-define table type in SQL Server 2008?

You can look in sys.types or use TYPE_ID:

IF TYPE_ID(N'MyType') IS NULL ...

Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.

prevent iphone default keyboard when focusing an <input>

inputmode attribute

<input inputmode='none'>

The inputmode global attribute is an enumerated attribute that hints at the type of data that might be entered by the user while editing the element or its contents. It can have the following values:

none - No virtual keyboard. For when the page implements its own keyboard input control.


I am using this successfully (Tested on Chrome/Android)

CSS-Tricks: Everything You Ever Wanted to Know About inputmode

'this' vs $scope in AngularJS controllers

The reason 'addPane' is assigned to this is because of the <pane> directive.

The pane directive does require: '^tabs', which puts the tabs controller object from a parent directive, into the link function.

addPane is assigned to this so that the pane link function can see it. Then in the pane link function, addPane is just a property of the tabs controller, and it's just tabsControllerObject.addPane. So the pane directive's linking function can access the tabs controller object and therefore access the addPane method.

I hope my explanation is clear enough.. it's kind of hard to explain.

PHP Notice: Undefined offset: 1 with array when reading data

my quickest solution was to minus 1 to the length of the array as

  $len = count($data);

    for($i=1; $i<=$len-1;$i++){
      echo $data[$i];
    }

my offset was always the last value if the count was 140 then it will say offset 140 but after using the minus 1 everything was fine

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Using Java with Nvidia GPUs (CUDA)

Marco13 already provided an excellent answer.

In case you are in search for a way to use the GPU without implementing CUDA/OpenCL kernels, I would like to add a reference to the finmath-lib-cuda-extensions (finmath-lib-gpu-extensions) http://finmath.net/finmath-lib-cuda-extensions/ (disclaimer: I am the maintainer of this project).

The project provides an implementation of "vector classes", to be precise, an interface called RandomVariable, which provides arithmetic operations and reduction on vectors. There are implementations for the CPU and GPU. There are implementation using algorithmic differentiation or plain valuations.

The performance improvements on the GPU are currently small (but for vectors of size 100.000 you may get a factor > 10 performance improvements). This is due to the small kernel sizes. This will improve in a future version.

The GPU implementation use JCuda and JOCL and are available for Nvidia and ATI GPUs.

The library is Apache 2.0 and available via Maven Central.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

inetmgr then come to Application pool->Advanced setting of your pool-> will have the option "Enable 32-Bit Applications" set to true; and restart IIS. check again.!

How to multiply duration by integer?

You have to cast it to a correct format Playground.

yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)

If you will check documentation for sleep, you see that it requires func Sleep(d Duration) duration as a parameter. Your rand.Int31n returns int32.

The line from the example works (time.Sleep(100 * time.Millisecond)) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.