Programs & Examples On #Zen

SyntaxError: Cannot use import statement outside a module

Just I want to add something to make your import work and avoid other issues like modules not working in node js. Just note that

With ES6 modules you can not yet import directories. Your import should look like this:

import fs from './../node_modules/file-system/file-system.js'

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

I had the same error and the problem is that I had not correctly installed Composer.

I am using Windows and I installed Composer-Setup.exe from getcomposer.org and when you have more than one version of PHP installed you must select the version that you are running at this point of the installation

enter image description here

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.0 the ForeignKey field requires two positional arguments:

  1. the model to map to
  2. the on_delete argument
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)

Here are some methods can used in on_delete

  1. CASCADE

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey

  1. PROTECT

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

  1. DO_NOTHING

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

you can find more about on_delete by reading the documentation.

React-Router External link

I had luck with this:

  <Route
    path="/example"
    component={() => {
    global.window && (global.window.location.href = 'https://example.com');
    return null;
    }}
/>

How to install PHP intl extension in Ubuntu 14.04

For php 5.6 on ubuntu 16.04

sudo apt-get install php5.6-intl

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

Claiming that the C++ compiler can produce more optimal code than a competent assembly language programmer is a very bad mistake. And especially in this case. The human always can make the code better than the compiler can, and this particular situation is a good illustration of this claim.

The timing difference you're seeing is because the assembly code in the question is very far from optimal in the inner loops.

(The below code is 32-bit, but can be easily converted to 64-bit)

For example, the sequence function can be optimized to only 5 instructions:

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

The whole code looks like:

include "%lib%/freshlib.inc"
@BinaryType console, compact
options.DebugMode = 1
include "%lib%/freshlib.asm"

start:
        InitializeAll
        mov ecx, 999999
        xor edi, edi        ; max
        xor ebx, ebx        ; max i

    .main_loop:

        xor     esi, esi
        mov     eax, ecx

    .seq:
        inc     esi                 ; counter
        lea     edx, [3*eax+1]      ; edx = 3*n+1
        shr     eax, 1              ; eax = n/2
        cmovc   eax, edx            ; if CF eax = edx
        jnz     .seq                ; jmp if n<>1

        cmp     edi, esi
        cmovb   edi, esi
        cmovb   ebx, ecx

        dec     ecx
        jnz     .main_loop

        OutputValue "Max sequence: ", edi, 10, -1
        OutputValue "Max index: ", ebx, 10, -1

        FinalizeAll
        stdcall TerminateAll, 0

In order to compile this code, FreshLib is needed.

In my tests, (1 GHz AMD A4-1200 processor), the above code is approximately four times faster than the C++ code from the question (when compiled with -O0: 430 ms vs. 1900 ms), and more than two times faster (430 ms vs. 830 ms) when the C++ code is compiled with -O3.

The output of both programs is the same: max sequence = 525 on i = 837799.

Django model "doesn't declare an explicit app_label"

I've got a similar error while building an API in Django rest_framework.

RuntimeError: Model class apps.core.models.University doesn't declare an explicit > app_label and isn't in an application in INSTALLED_APPS.

luke_aus's answer helped me by correcting my urls.py

from

from project.apps.views import SurgeryView

to

from apps.views import SurgeryView

When to use React "componentDidUpdate" method?

When something in the state has changed and you need to call a side effect (like a request to api - get, put, post, delete). So you need to call componentDidUpdate() because componentDidMount() is already called.

After calling side effect in componentDidUpdate(), you can set the state to new value based on the response data in the then((response) => this.setState({newValue: "here"})). Please make sure that you need to check prevProps or prevState to avoid infinite loop because when setting state to a new value, the componentDidUpdate() will call again.

There are 2 places to call a side effect for best practice - componentDidMount() and componentDidUpdate()

PHP Deprecated: Methods with the same name

As mentioned in the error, the official manual and the comments:

Replace

public function TSStatus($host, $queryPort)

with

public function __construct($host, $queryPort)

How to set an environment variable from a Gradle build?

This one is working for me for settings environment variable for the test plugin

test {
    systemProperties = [
        'catalina.home': 'c:/test'
    ]
    println "Starting Tests"
    beforeTest { descriptor ->
       logger.lifecycle("Running test: " + descriptor)                
    }    
}

PHP 7 simpleXML

I'm using Bash on Windows (Ubuntu 16.04) and I just installed with php7.0-xml and all is working now for the Symfony 3.2.7 PHP requirements.

sudo apt-get install php7.0-xml

ActivityCompat.requestPermissions not showing dialog box

It could be not a problem with a single line of your code.

On some devices (I don't recall if it is in stock Android) the Permission dialog includes a check box labeled "Never ask again". If you click Deny with the box checked then you won't be prompted again for that permission, it will automatically be denied to the app. To revert this, you have to go into Settings -> App -> Permissions and re--enable that perm for the app. Then turn it off to deny it again. You may have to open the app before turning it off again, not sure.

I don't know if your Nexus has it. Maybe worth a try.

How can I enable the MySQLi extension in PHP 7?

The problem is that the package that used to connect PHP to MySQL is deprecated (php5-mysql). If you install the new package,

sudo apt-get install php-mysql

this will automatically update Apache and PHP 7.

How do I install the ext-curl extension with PHP 7?

We can install any PHP7 Extensions which we are needed at the time of install Magento just use related command which you get error at the time of installin Magento

sudo apt-get install php7.0-curl
sudo apt-get install php7.0-dom
sudo apt-get install php7.0-mcrypt
sudo apt-get install php7.0-simplexml
sudo apt-get install php7.0-spl
sudo apt-get install php7.0-xsl
sudo apt-get install php7.0-intl
sudo apt-get install php7.0-mbstring
sudo apt-get install php7.0-ctype
sudo apt-get install php7.0-hash
sudo apt-get install php7.0-openssl
sudo apt-get install php7.0-zip
sudo apt-get install php7.0-xmlwriter
sudo apt-get install php7.0-gd
sudo apt-get install php7.0-iconv

Thanks! Hope this will help you

TLS 1.2 in .NET Framework 4.0

The only way I have found to change this is directly on the code :

at the very beginning of your app you set

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

you should include the system.net class

I did this before calling a web service because we had to block tls1 too.

Excel doesn't update value unless I hit Enter

It sounds like your workbook got set to Manual Calculation. You can change this to Automatic by going to Formulas > Calculation > Calculation Options > Automatic.

Location in Ribbon

Manual calculation can be useful to reduce computational load and improve responsiveness in workbooks with large amounts of formulas. The idea is that you can look at data and make changes, then choose when you want to make your computer go through the effort of calculation.

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

You should try changing the value of -Xmx and -Xms.

Plotting in a non-blocking way with Matplotlib

I spent a long time looking for solutions, and found this answer.

It looks like, in order to get what you (and I) want, you need the combination of plt.ion(), plt.show() (not with block=False) and, most importantly, plt.pause(.001) (or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.

Here's an implementation that works for me on python 3.5:

import numpy as np
from matplotlib import pyplot as plt

def main():
    plt.axis([-50,50,0,10000])
    plt.ion()
    plt.show()

    x = np.arange(-50, 51)
    for pow in range(1,5):   # plot x^1, x^2, ..., x^4
        y = [Xi**pow for Xi in x]
        plt.plot(x, y)
        plt.draw()
        plt.pause(0.001)
        input("Press [enter] to continue.")

if __name__ == '__main__':
    main()

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

how to create virtual host on XAMPP

Write these codes end of the C:\xampp\apache\conf\extra\httpd-vhosts.conf file,

DocumentRoot "D:/xampp/htdocs/foldername"
ServerName www.siteurl.com
ServerAlias www.siteurl.com
ErrorLog "logs/dummy-host.example.com-error.log"
CustomLog "logs/dummy-host.example.com-access.log" common

between the virtual host tag.

and edit the file System32/Drivers/etc/hosts use notepad as administrator

add bottom of the file

127.0.0.1    www.siteurl.com

Asus Zenfone 5 not detected by computer

Settings > Storage > Click the USB Icon at the upper right corner > Check your choice

System.web.mvc missing

in VS 2017 I cleaned the solution and rebuilt it and that fixed it

Java ElasticSearch None of the configured nodes are available

You should check logs If you see like below "stacktrace": ["java.lang.IllegalStateException: Received message from unsupported version: [6.4.3] minimal compatible version is: [6.8.0]"

You can check this link https://discuss.elastic.co/t/java-client-or-spring-boot-for-elasticsearch-7-3-1/199778 You have to explicit declare es version.

Avoid dropdown menu close on click inside

$(function() {
    $('.mega-dropdown').on('hide.bs.dropdown', function(e) {
        var $target = $(e.target);
        return !($target.hasClass("keep-open") || $target.parents(".keep-open").size() > 0);
    });

    $('.mega-dropdown > ul.dropdown-menu').on('mouseenter', function() {
        $(this).parent('li').addClass('keep-open')
    }).on('mouseleave', function() {
        $(this).parent('li').removeClass('keep-open')
    });
});

Disable all dialog boxes in Excel while running VB script?

Solution: Automation Macros

It sounds like you would benefit from using an automation utility. If you were using a windows PC I would recommend AutoHotkey. I haven't used automation utilities on a Mac, but this Ask Different post has several suggestions, though none appear to be free.

This is not a VBA solution. These macros run outside of Excel and can interact with programs using keyboard strokes, mouse movements and clicks.

Basically you record or write a simple automation macro that waits for the Excel "Save As" dialogue box to become active, hits enter/return to complete the save action and then waits for the "Save As" window to close. You can set it to run in a continuous loop until you manually end the macro.

Here's a simple version of a Windows AutoHotkey script that would accomplish what you are attempting to do on a Mac. It should give you an idea of the logic involved.

Example Automation Macro: AutoHotkey

; ' Infinite loop.  End the macro by closing the program from the Windows taskbar.
Loop {

    ; ' Wait for ANY "Save As" dialogue box in any program.
    ; ' BE CAREFUL!
    ; '  Ignore the "Confirm Save As" dialogue if attempt is made
    ; '  to overwrite an existing file.
    WinWait, Save As,,, Confirm Save As
    IfWinNotActive, Save As,,, Confirm Save As
        WinActivate, Save As,,, Confirm Save As
    WinWaitActive, Save As,,, Confirm Save As

    sleep, 250 ; ' 0.25 second delay
    Send, {ENTER} ; ' Save the Excel file.

    ; ' Wait for the "Save As" dialogue box to close.
    WinWaitClose, Save As,,, Confirm Save As
}

Java Error: illegal start of expression

Declare

public static int[] locations={1,2,3};

outside of the main method.

Could not find method compile() for arguments Gradle

compile is a configuration that is usually introduced by a plugin (most likely the java plugin) Have a look at the gradle userguide for details about configurations. For now adding the java plugin on top of your build script should do the trick:

apply plugin:'java'

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

You have to play with JSFiddle loading option :

set it to "No wrap - in body" instead of "onload"

Working fiddle : http://jsfiddle.net/zQv9n/1/

Why not inherit from List<T>?

Design > Implementation

What methods and properties you expose is a design decision. What base class you inherit from is an implementation detail. I feel it's worth taking a step back to the former.

An object is a collection of data and behaviour.

So your first questions should be:

  • What data does this object comprise in the model I'm creating?
  • What behaviour does this object exhibit in that model?
  • How might this change in future?

Bear in mind that inheritance implies an "isa" (is a) relationship, whereas composition implies a "has a" (hasa) relationship. Choose the right one for your situation in your view, bearing in mind where things might go as your application evolves.

Consider thinking in interfaces before you think in concrete types, as some people find it easier to put their brain in "design mode" that way.

This isn't something everyone does consciously at this level in day to day coding. But if you're mulling this sort of topic, you're treading in design waters. Being aware of it can be liberating.

Consider Design Specifics

Take a look at List<T> and IList<T> on MSDN or Visual Studio. See what methods and properties they expose. Do these methods all look like something someone would want to do to a FootballTeam in your view?

Does footballTeam.Reverse() make sense to you? Does footballTeam.ConvertAll<TOutput>() look like something you want?

This isn't a trick question; the answer might genuinely be "yes". If you implement/inherit List<Player> or IList<Player>, you're stuck with them; if that's ideal for your model, do it.

If you decide yes, that makes sense, and you want your object to be treatable as a collection/list of players (behaviour), and you therefore want to implement ICollection or IList, by all means do so. Notionally:

class FootballTeam : ... ICollection<Player>
{
    ...
}

If you want your object to contain a collection/list of players (data), and you therefore want the collection or list to be a property or member, by all means do so. Notionally:

class FootballTeam ...
{
    public ICollection<Player> Players { get { ... } }
}

You might feel that you want people to be able to only enumerate the set of players, rather than count them, add to them or remove them. IEnumerable<Player> is a perfectly valid option to consider.

You might feel that none of these interfaces are useful in your model at all. This is less likely (IEnumerable<T> is useful in many situations) but it's still possible.

Anyone who attempts to tell you that one of these it is categorically and definitively wrong in every case is misguided. Anyone who attempts to tell you it is categorically and definitively right in every case is misguided.

Move on to Implementation

Once you've decided on data and behaviour, you can make a decision about implementation. This includes which concrete classes you depend on via inheritance or composition.

This may not be a big step, and people often conflate design and implementation since it's quite possible to run through it all in your head in a second or two and start typing away.

A Thought Experiment

An artificial example: as others have mentioned, a team is not always "just" a collection of players. Do you maintain a collection of match scores for the team? Is the team interchangable with the club, in your model? If so, and if your team isa collection of players, perhaps it also isa collection of staff and/or a collection of scores. Then you end up with:

class FootballTeam : ... ICollection<Player>, 
                         ICollection<StaffMember>,
                         ICollection<Score>
{
    ....
}

Design notwithstanding, at this point in C# you won't be able to implement all of these by inheriting from List<T> anyway, since C# "only" supports single inheritance. (If you've tried this malarky in C++, you may consider this a Good Thing.) Implementing one collection via inheritance and one via composition is likely to feel dirty. And properties such as Count become confusing to users unless you implement ILIst<Player>.Count and IList<StaffMember>.Count etc. explicitly, and then they're just painful rather than confusing. You can see where this is going; gut feeling whilst thinking down this avenue may well tell you it feels wrong to head in this direction (and rightly or wrongly, your colleagues might also if you implemented it this way!)

The Short Answer (Too Late)

The guideline about not inheriting from collection classes isn't C# specific, you'll find it in many programming languages. It is received wisdom not a law. One reason is that in practice composition is considered to often win out over inheritance in terms of comprehensibility, implementability and maintainability. It's more common with real world / domain objects to find useful and consistent "hasa" relationships than useful and consistent "isa" relationships unless you're deep in the abstract, most especially as time passes and the precise data and behaviour of objects in code changes. This shouldn't cause you to always rule out inheriting from collection classes; but it may be suggestive.

Could not open input file: composer.phar

I was trying to install YII 2.0

php composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.0-alpha

I got the same error:

Could not open input file: composer.phar

Then i gave the full path of .phar like this:

php C:\ProgramData\Composer\bin\composer.phar create-project yiisoft/yii2-app-advanced advanced 2.0.0-alpha

and it worked.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

could not extract ResultSet in hibernate

I was using Spring Data JPA with PostgreSql and during UPDATE call it was showing errors-

  • 'could not extract ResultSet' and another one.
  • org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query. (Showing Transactional required.)

Actually, I was missing two required Annotations.

  • @Transactional and
  • @Modifying

With-

@Query(vlaue = " UPDATE DB.TABLE SET Col1 = ?1 WHERE id = ?2 ", nativeQuery = true)
void updateCol1(String value, long id);

SQL Left Join first match only

Try this

 SELECT *
 FROM people P 
 where P.IDNo in (SELECT DISTINCT IDNo
              FROM people)

Is it possible to use global variables in Rust?

Look at the const and static section of the Rust book.

You can use something as follows:

const N: i32 = 5; 

or

static N: i32 = 5;

in global space.

But these are not mutable. For mutability, you could use something like:

static mut N: i32 = 5;

Then reference them like:

unsafe {
    N += 1;

    println!("N: {}", N);
}

Best practice multi language website

It depends on how much content your website has. At first I used a database like all other people here, but it can be time-consuming to script all the workings of a database. I don't say that this is an ideal method and especially if you have a lot of text, but if you want to do it fast without using a database, this method could work, though, you can't allow users to input data which will be used as translation-files. But if you add the translations yourself, it will work:

Let's say you have this text:

Welcome!

You can input this in a database with translations, but you can also do this:

$welcome = array(
"English"=>"Welcome!",
"German"=>"Willkommen!",
"French"=>"Bienvenue!",
"Turkish"=>"Hosgeldiniz!",
"Russian"=>"????? ??????????!",
"Dutch"=>"Welkom!",
"Swedish"=>"Välkommen!",
"Basque"=>"Ongietorri!",
"Spanish"=>"Bienvenito!"
"Welsh"=>"Croeso!");

Now, if your website uses a cookie, you have this for example:

$_COOKIE['language'];

To make it easy let's transform it in a code which can easily be used:

$language=$_COOKIE['language'];

If your cookie language is Welsh and you have this piece of code:

echo $welcome[$language];

The result of this will be:

Croeso!

If you need to add a lot of translations for your website and a database is too consuming, using an array can be an ideal solution.

Update MySQL using HTML Form and PHP

you have error in your sql syntax.

please use this query and checkout.

$query = mysql_query("UPDATE `anstalld` SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ");

PHP array() to javascript array()

This may be a easy solution.

var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");

Android Studio - How to increase Allocated Heap Size

-------EDIT--------

Android Studio 2.0 and above, you can create/edit this file by accessing "Edit Custom VM Options" from the Help menu.

-------ORIGINAL ANSWER--------

Open file located at

/Applications/Android\ Studio.app/Contents/bin/studio.vmoptions

Change the content to

-Xms128m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=200m
-XX:+UseCompressedOops

Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool. Your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory.

Save the studio.vmoptions file and restart Android Studio.

Note:

If you changed the heap size for the IDE, you must restart Android Studio before the new memory settings are applied. (source)

No mapping found for HTTP request with URI.... in DispatcherServlet with name

Try:

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Worked for me!  

Send email with PHP from html form on submit with the same script

You need a SMPT Server in order for

... mail($to,$subject,$message,$headers);

to work.

You could try light weight SMTP servers like xmailer

C++ String array sorting

int z = sizeof(name)/sizeof(name[0]); //Get the array size

sort(name,name+z); //Use the start and end like this

for(int y = 0; y < z; y++){
    cout << name[y] << endl;
}

Edit :

Considering all "proper" naming conventions (as per comments) :

int N = sizeof(name)/sizeof(name[0]); //Get the array size

sort(name,name+N); //Use the start and end like this

for(int i = 0; i < N; i++){
    cout << name[i] << endl;
}

Note: Dietmar Kühl's answer is best in all respect, std::begin() & std::end() should be used for std::sort like functions with C++11, else they can be defined.

PHP Fatal error: Call to undefined function json_decode()

With Ubuntu :

sudo apt-get install php5-json
sudo service php5-fpm restart

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

My problem solved with these :

1- Add this to your head :

<base href="/" />

2- Use this in app.config

$locationProvider.html5Mode(true);

RuntimeError on windows trying python multiprocessing

Try putting your code inside a main function in testMain.py

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

See the docs:

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

which say

"Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)."

... by using if __name__ == '__main__'

Toggle visibility property of div

There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.

Example:

function toggleVideo() {
     var e = document.getElementById('video-over');

     if(e.style.visibility == 'visible') {
          e.style.visibility = 'hidden';
     } else if(e.style.visibility == 'hidden') {
          e.style.visibility = 'visible';
     }
}

phpinfo() is not working on my CentOS server

It may not work for you if you use localhost/info.php.

You may be able to found the clue from the error. Find the port number in the error message. To me it was 80. I changed address as http://localhost:80/info.php, and then it worked to me.

No connection could be made because the target machine actively refused it (PHP / WAMP)

Kindly check is your mysql-service is running.

for windows user: check the services - mysql service

for Linux user: Check the mysql service/demon is running (services mysql status)

Thanks & Regards Jaiswar Vipin Kumar R

Determining the last row in a single column

Old thread but I have found a simple way that seems to work

ws.getRange("A2").getNextDataCell(SpreadsheetApp.Direction.DOWN).getLastRow()

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

I think you can use display: inline-block on the element you want to center and set text-align: center; on its parent. This definitely center the div on all screen sizes.

Here you can see a fiddle: http://jsfiddle.net/PwC4T/2/ I add the code here for completeness.

HTML

<div id="container">
    <div id="main">
        <div id="somebackground">
            Hi
        </div>
    </div>
</div>

CSS

#container
{
    text-align: center;
}
#main
{
    display: inline-block;
}
#somebackground
{
    text-align: left;
    background-color: red;
}

For vertical centering, I "dropped" support for some older browsers in favour of display: table;, which absolutely reduce code, see this fiddle: http://jsfiddle.net/jFAjY/1/

Here is the code (again) for completeness:

HTML

<body>
    <div id="table-container">
        <div id="container">
            <div id="main">
                <div id="somebackground">
                    Hi
                </div>
            </div>
        </div>
    </div>
</body>

CSS

body, html
{
    height: 100%;
}
#table-container
{
    display:    table;
    text-align: center;
    width:      100%;
    height:     100%;
}
#container
{
    display:        table-cell;
    vertical-align: middle;
}
#main
{
    display: inline-block;
}
#somebackground
{
    text-align:       left;
    background-color: red;
}

The advantage of this approach? You don't have to deal with any percantage, it also handles correctly the <video> tag (html5), which has two different sizes (one during load, one after load, you can't fetch the tag size 'till video is loaded).

The downside is that it drops support for some older browser (I think IE8 won't handle this correctly)

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Try using the QueryDefs. Create the query with parameters. Then use something like this:

Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef

Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")

qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close

Set qdf = Nothing
Set dbs = Nothing

Error: Selection does not contain a main type

Right click on the folder where you put your main class then click on Build Path --> Use as Source Folder.

Finally run your main file as java application. Hope this problem will be solved.

Refer to a cell in another worksheet by referencing the current worksheet's name?

Here is how I made monthly page in similar manner as Fernando:

  1. I wrote manually on each page number of the month and named that place as ThisMonth. Note that you can do this only before you make copies of the sheet. After copying Excel doesn't allow you to use same name, but with sheet copy it does it still. This solution works also without naming.
  2. I added number of weeks in the month to location C12. Naming is fine also.
  3. I made five weeks on every page and on fifth week I made function

      =IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
    

    that empties fifth week if this month has only four weeks. C12 holds the number of weeks.

  4. ...
  5. I created annual Excel, so I had 12 sheets in it: one for each month. In this example name of the sheet is "Month". Note that this solutions works also with the ODS file standard except you need to change all spaces as "_" characters.
  6. I renamed first "Month" sheet as "Month (1)" so it follows the same naming principle. You could also name it as "Month1" if you wish, but "January" would require a bit more work.
  7. Insert following function on the first day field starting sheet #2:

     =INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
    

    So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.

There has been an error processing your request, Error log record number

I encountered a problem like this and it turns out that I accidentally changed the permission of the var/cache folder. Just delete the cache folder so magento could automatically create the folder with the right permissions.

rm -rf root/var/cache

How to sort the letters in a string alphabetically in Python

Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().

from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])

sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']

tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')

We are selecting the last index (-1) of the tuple

jQuery set checkbox checked

Try this since your are using jQuery UI probably (if not please comment)

 $("#fModal" ).dialog({
     open: function( event, ui ) {

     if(//some hidden value check which stores the DB value==expected value for
      checking the Checkbox)

         $("div.row-form input[type='checkbox']").attr('checked','checked');

    }
   });

How to query values from xml nodes?

Try this:

SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
       RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches

AngularJS sorting by property

according to http://docs.angularjs.org/api/ng.filter:orderBy , orderBy sorts an array. In your case you're passing an object, so You'll have to implement Your own sorting function.

or pass an array -

$scope.testData = {
    C: {name:"CData", order: 1},
    B: {name:"BData", order: 2},
    A: {name:"AData", order: 3},
}

take a look at http://jsfiddle.net/qaK56/

Class 'DOMDocument' not found

For Centos 7 and php 7.1:
yum install php71w-xml
apachectl restart

How to specify function types for void (not Void) methods in Java8?

Set return type to Void instead of void and return null

// Modify existing method
public static Void displayInt(Integer i) {
    System.out.println(i);
    return null;
}

OR

// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});

You must enable the openssl extension to download files via https

I had to uncomment extension=openssl in php.ini file for everything to work!

grep from tar.gz without extracting [faster one]

Am trying to grep pattern from dozen files .tar.gz but its very slow

tar -ztf file.tar.gz | while read FILENAME
do
        if tar -zxf file.tar.gz "$FILENAME" -O | grep "string" > /dev/null
        then
                echo "$FILENAME contains string"
        fi
done

That's actually very easy with ugrep option -z:

-z, --decompress
        Decompress files to search, when compressed.  Archives (.cpio,
        .pax, .tar, and .zip) and compressed archives (e.g. .taz, .tgz,
        .tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, and .txz) are searched and
        matching pathnames of files in archives are output in braces.  If
        -g, -O, -M, or -t is specified, searches files within archives
        whose name matches globs, matches file name extensions, matches
        file signature magic bytes, or matches file types, respectively.
        Supported compression formats: gzip (.gz), compress (.Z), zip,
        bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
        lzma and xz (requires suffix .lzma, .tlz, .xz, .txz).

Which requires just one command to search file.tar.gz as follows:

ugrep -z "string" file.tar.gz

This greps each of the archived files to display matches. Archived filenames are shown in braces to distinguish them from ordinary filenames. For example:

$ ugrep -z "Hello" archive.tgz
{Hello.bat}:echo "Hello World!"
Binary file archive.tgz{Hello.class} matches
{Hello.java}:public class Hello // prints a Hello World! greeting
{Hello.java}:  { System.out.println("Hello World!");
{Hello.pdf}:(Hello)
{Hello.sh}:echo "Hello World!"
{Hello.txt}:Hello

If you just want the file names, use option -l (--files-with-matches) and customize the filename output with option --format="%z%~" to get rid of the braces:

$ ugrep -z Hello -l --format="%z%~" archive.tgz
Hello.bat
Hello.class
Hello.java
Hello.pdf
Hello.sh
Hello.txt

Exception: Serialization of 'Closure' is not allowed

Apparently anonymous functions cannot be serialized.

Example

$function = function () {
    return "ABC";
};
serialize($function); // would throw error

From your code you are using Closure:

$callback = function () // <---------------------- Issue
{
    return 'ZendMail_' . microtime(true) . '.tmp';
};

Solution 1 : Replace with a normal function

Example

function emailCallback() {
    return 'ZendMail_' . microtime(true) . '.tmp';
}
$callback = "emailCallback" ;

Solution 2 : Indirect method call by array variable

If you look at http://docs.mnkras.com/libraries_23rdparty_2_zend_2_mail_2_transport_2file_8php_source.html

   public function __construct($options = null)
   63     {
   64         if ($options instanceof Zend_Config) {
   65             $options = $options->toArray();
   66         } elseif (!is_array($options)) {
   67             $options = array();
   68         }
   69 
   70         // Making sure we have some defaults to work with
   71         if (!isset($options['path'])) {
   72             $options['path'] = sys_get_temp_dir();
   73         }
   74         if (!isset($options['callback'])) {
   75             $options['callback'] = array($this, 'defaultCallback'); <- here
   76         }
   77 
   78         $this->setOptions($options);
   79     }

You can use the same approach to send the callback

$callback = array($this,"aMethodInYourClass");

Pair/tuple data type in Go

There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

Nick's answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

These techniques have some properties of tuples, but no, they are not tuples.

Get index of selected option with jQuery

Good way to solve this in Jquery manner

$("#dropDownMenuKategorie option:selected").index()

What is .htaccess file?

Htaccess is a configuration file of apache which is used to make changes in the configuration on a directory basis. Htaccess file is used to do changes in functions and features of the apache server. Htaccess is used to rewrite the URL. It is used to make site address protected. Also to restrict IP addresses so on particular IP address site will not be opened

Installing packages in Sublime Text 2

Try using Sublime Package Control to install your packages.

Also take a look at these tips

Django: Calling .update() on a single model instance retrieved by .get()?

As of Django 1.5, there is an update_fields property on model save. eg:

obj.save(update_fields=['field1', 'field2', ...])

https://docs.djangoproject.com/en/dev/ref/models/instances/

I prefer this approach because it doesn't create an atomicity problem if you have multiple web app instances changing different parts of a model instance.

How to access route, post, get etc. parameters in Zend Framework 2

All the above methods will work fine if your content-type is "application/-www-form-urlencoded". But if your content-type is "application/json" then you will have to do the following:

$params = json_decode(file_get_contents('php://input'), true); print_r($params);

Reason : See #7 in https://www.toptal.com/php/10-most-common-mistakes-php-programmers-make

import android packages cannot be resolved

What all the others said.

Specifically, I recommend you go to Project > Properties > Java Build Path > Libraries and make sure you have exactly one copy of android.jar referenced. (Sometimes you can get two if you're importing a project.) And that its path is correct.

Sometimes you can get the system to resolve this for you by clicking a different target SDK in Project > Properties > Android, then restoring your original selection.

C# Convert List<string> to Dictionary<string, string>

By using ToDictionary:

var dictionary = list.ToDictionary(s => s);

If it is possible that any string could be repeated, either do a Distinct call first on the list (to remove duplicates), or use ToLookup which allows for multiple values per key.

Getting all request parameters in Symfony 2

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;

    class SampleController extends Controller
    {


        public function indexAction(Request $request) {

           var_dump($request->request->all());
        }

    }

How do I fix twitter-bootstrap on IE?

Please put the pages in localhost and try

Why is it bad style to `rescue Exception => e` in Ruby?

This blog post explains it perfectly: Ruby's Exception vs StandardError: What's the difference?

Why you shouldn't rescue Exception

The problem with rescuing Exception is that it actually rescues every exception that inherits from Exception. Which is....all of them!

That's a problem because there are some exceptions that are used internally by Ruby. They don't have anything to do with your app, and swallowing them will cause bad things to happen.

Here are a few of the big ones:

  • SignalException::Interrupt - If you rescue this, you can't exit your app by hitting control-c.

  • ScriptError::SyntaxError - Swallowing syntax errors means that things like puts("Forgot something) will fail silently.

  • NoMemoryError - Wanna know what happens when your program keeps running after it uses up all the RAM? Me neither.

begin
  do_something()
rescue Exception => e
  # Don't do this. This will swallow every single exception. Nothing gets past it. 
end

I'm guessing that you don't really want to swallow any of these system-level exceptions. You only want to catch all of your application level errors. The exceptions caused YOUR code.

Luckily, there's an easy way to to this.

Rescue StandardError Instead

All of the exceptions that you should care about inherit from StandardError. These are our old friends:

NoMethodError - raised when you try to invoke a method that doesn't exist

TypeError - caused by things like 1 + ""

RuntimeError - who could forget good old RuntimeError?

To rescue errors like these, you'll want to rescue StandardError. You COULD do it by writing something like this:

begin
  do_something()
rescue StandardError => e
  # Only your app's exceptions are swallowed. Things like SyntaxErrror are left alone. 
end

But Ruby has made it much easier for use.

When you don't specify an exception class at all, ruby assumes you mean StandardError. So the code below is identical to the above code:

begin
  do_something()
rescue => e
  # This is the same as rescuing StandardError
end

How to add a reference programmatically

Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.

The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.

The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).

What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?

Sub AddReferences(wbk As Workbook)
    ' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
    AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
    AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
    AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub

Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
    Dim i As Integer
    On Error GoTo EH
    With wbk.VBProject.References
        For i = 1 To .Count
            If .Item(i).Name = sRefName Then
               Exit For
            End If
        Next i
        If i > .Count Then
           .AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
        End If
    End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
    Resume EX
    Resume ' debug code
End Sub

Public Sub DebugPrintExistingRefs()
    Dim i As Integer
    With Application.ThisWorkbook.VBProject.References
        For i = 1 To .Count
            Debug.Print "    AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
        Next i
    End With
End Sub

The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.

How to add default signature in Outlook

Dim OutApp As Object, OutMail As Object, LogFile As String
Dim cell As Range, S As String, WMBody As String, lFile As Long

S = Environ("appdata") & "\Microsoft\Signatures\"
If Dir(S, vbDirectory) <> vbNullString Then S = S & Dir$(S & "*.htm") Else S = ""
S = CreateObject("Scripting.FileSystemObject").GetFile(S).OpenAsTextStream(1,  -2).ReadAll

WMBody = "<br>Hi All,<br><br>" & _
         "Last line,<br><br>" & S 'Add the Signature to end of HTML Body

Just thought I'd share how I achieve this. Not too sure if it's correct in the defining variables sense but it's small and easy to read which is what I like.

I attach WMBody to .HTMLBody within the object Outlook.Application OLE.

Hope it helps someone.

Thanks, Wes.

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

php.ini:

xdebug.max_nesting_level = -1

I'm not entirely sure if the value will ever overflow and reach -1, but it'll either never reach -1, or it'll set the max_nesting_level pretty high.

Freeze the top row for an html table only (Fixed Table Header Scrolling)

The Chromatable jquery plugin allows a fixed header (or top row) with widths that allow percentages--granted, only a percentage of 100%.

http://www.chromaloop.com/posts/chromatable-jquery-plugin

I can't think of how you could do this without javascript.

update: new link -> http://www.jquery-plugins.info/chromatable-00012248.htm

Increasing Google Chrome's max-connections-per-server limit to more than 6

I don't know that you can do it in Chrome outside of Windows -- some Googling shows that Chrome (and therefore possibly Chromium) might respond well to a certain registry hack.

However, if you're just looking for a simple solution without modifying your code base, have you considered Firefox? In the about:config you can search for "network.http.max" and there are a few values in there that are definitely worth looking at.

Also, for a device that will not be moving (i.e. it is mounted in a fixed location) you should consider not using Wi-Fi (even a Home-Plug would be a step up as far as latency / stability / dropped connections go).

Elegant way to report missing values in a data.frame

Another graphical alternative - plot_missing function from excellent DataExplorer package:

enter image description here

Docs also points out to the fact that you can save this results for additional analysis with missing_data <- plot_missing(data).

Omitting one Setter/Getter in Lombok

According to @Data description you can use:

All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.

No more data to read from socket error

This is a very low-level exception, which is ORA-17410.

It may happen for several reasons:

  1. A temporary problem with networking.

  2. Wrong JDBC driver version.

  3. Some issues with a special data structure (on database side).

  4. Database bug.

In my case, it was a bug we hit on the database, which needs to be patched.

"[notice] child pid XXXX exit signal Segmentation fault (11)" in apache error.log

A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.

Try disabling all non-essential modules (in php.ini), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.

If that doesn't help, you should report a php bug.

How to print exact sql query in zend framework ?

The query returned from the profiler or query object will have placeholders if you're using those.

To see the exact query run by mysql you can use the general query log.

This will list all the queries which have run since it was enabled. Don't forget to disable this once you've collected your sample. On an active server; this log can fill up very fast.

From a mysql terminal or query tool like MySQL Workbench run:

SET GLOBAL log_output = 'table';
SET GLOBAL general_log = 1;

then run your query. The results are stored in the "mysql.general_log" table.

SELECT * FROM mysql.general_log

To disable the query log:

SET GLOBAL general_log = 0;

To verify it's turned off:

SHOW VARIABLES LIKE 'general%';

This helped me locate a query where the placeholder wasn't being replaced by zend db. Couldn't see that with the profiler.

load scripts asynchronously

I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.

export default class ScriptLoader {
  constructor (options) {
    const { src, global, protocol = document.location.protocol } = options
    this.src = src
    this.global = global
    this.protocol = protocol
    this.isLoaded = false
  }

  loadScript () {
    return new Promise((resolve, reject) => {
      // Create script element and set attributes
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      script.src = `${this.protocol}//${this.src}`

      // Append the script to the DOM
      const el = document.getElementsByTagName('script')[0]
      el.parentNode.insertBefore(script, el)

      // Resolve the promise once the script is loaded
      script.addEventListener('load', () => {
        this.isLoaded = true
        resolve(script)
      })

      // Catch any errors while loading the script
      script.addEventListener('error', () => {
        reject(new Error(`${this.src} failed to load.`))
      })
    })
  }

  load () {
    return new Promise(async (resolve, reject) => {
      if (!this.isLoaded) {
        try {
          await this.loadScript()
          resolve(window[this.global])
        } catch (e) {
          reject(e)
        }
      } else {
        resolve(window[this.global])
      }
    })
  }
}

Usage is like this:

const loader = new Loader({
    src: 'cdn.segment.com/analytics.js',
    global: 'Segment',
})

// scriptToLoad will now be a reference to `window.Segment`
const scriptToLoad = await loader.load()

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

If you don't want use connection pool (you sure, that your app has only one connection), you can do this - if connection falls you must establish new one - call method .openSession() instead .getCurrentSession()

For example:

SessionFactory sf = null;
// get session factory
// ...
//
Session session = null;
try {
        session = sessionFactory.getCurrentSession();
} catch (HibernateException ex) {
        session = sessionFactory.openSession();
}

If you use Mysql, you can set autoReconnect property:

    <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/database?autoReconnect=true</property>

I hope this helps.

How to output in CLI during execution of PHP Unit tests?

It's not a bug, but very much intentional. Your best bet is to write to a log file of some kind and tail the log to watch for output.

If you are trying to TEST output, check this out.

Also:

Note: Please note that PHPUnit swallows all output that is emitted during the execution of a test. In strict mode, a test that emits output will fail.

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

How do I find which application is using up my port?

How about netstat?

http://support.microsoft.com/kb/907980

The command is netstat -anob.

(Make sure you run command as admin)

I get:

C:\Windows\system32>netstat -anob

Active Connections

     Proto  Local Address          Foreign Address        State           PID
  TCP           0.0.0.0:80                0.0.0.0:0                LISTENING         4
 Can not obtain ownership information

  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       692
  RpcSs
 [svchost.exe]

  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       7540
 [Skype.exe]

  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
 Can not obtain ownership information
  TCP    0.0.0.0:623            0.0.0.0:0              LISTENING       564
 [LMS.exe]

  TCP    0.0.0.0:912            0.0.0.0:0              LISTENING       4480
 [vmware-authd.exe]

And If you want to check for the particular port, command to use is: netstat -aon | findstr 8080 from the same path

Deserialize JSON array(or list) in C#

Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx

name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);

How do I save and restore multiple variables in python?

There is a built-in library called pickle. Using pickle you can dump objects to a file and load them later.

import pickle

f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()

f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Tried following code

 $db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

Then

 try {
 $db->query('SET NAMES gbk');
 $stmt = $db->prepare('SELECT * FROM 2_1_paidused WHERE NumberRenamed = ? LIMIT 1');
 $stmt->execute(array("\xbf\x27 OR 1=1 /*"));
 }
 catch (PDOException $e){
 echo "DataBase Errorz: " .$e->getMessage() .'<br>';
 }
 catch (Exception $e) {
 echo "General Errorz: ".$e->getMessage() .'<br>';
 }

And got

DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/*' LIMIT 1' at line 1

If added $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); after $db = ...

Then got blank page

If instead SELECT tried DELETE, then in both cases got error like

 DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM 2_1_paidused WHERE NumberRenamed = '¿\' OR 1=1 /*' LIMIT 1' at line 1

So my conclusion that no injection possible...

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

Yes. You just have to use the RAISE_APPLICATION_ERROR function. If you also want to name your exception, you'll need to use the EXCEPTION_INIT pragma in order to associate the error number to the named exception. Something like

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    ex_custom EXCEPTION;
  3    PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
  4  begin
  5    raise_application_error( -20001, 'This is a custom error' );
  6  exception
  7    when ex_custom
  8    then
  9      dbms_output.put_line( sqlerrm );
 10* end;
SQL> /
ORA-20001: This is a custom error

PL/SQL procedure successfully completed.

git rebase: "error: cannot stat 'file': Permission denied"

Trying to close IDE such as Sublime, VS Code, Webstorm,... and close your programs that have the folder open such as CMD, Powershell, CMDer, Terminal,... will fix the issue.

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values.

Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.

I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution: @Enumerated(EnumType.STRING)

Is there any good dynamic SQL builder library in Java?

You can use the following library:

https://github.com/pnowy/NativeCriteria

The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).

You can find the examples on github page, the library is available at Maven central of course.

NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));

program cant start because php5.dll is missing

For Wamp x86+Phalcon users (with same error):

Take care of download the right version of Phalcon:

Phalcon 1.3.2 - Windows x86 for PHP 5.5.0 (VC11)

How to print to stderr in Python?

The same applies to stdout:

print 'spam'
sys.stdout.write('spam\n')

As stated in the other answers, print offers a pretty interface that is often more convenient (e.g. for printing debug information), while write is faster and can also be more convenient when you have to format the output exactly in certain way. I would consider maintainability as well:

  1. You may later decide to switch between stdout/stderr and a regular file.

  2. print() syntax has changed in Python 3, so if you need to support both versions, write() might be better.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Another way to do this, is using directly a parameter on the libreoffice command:

libreoffice --convert-to pdf /path/to/file.{doc,docx}

---- ---- ---- ---- ---- ---- Explanation ---- ---- ---- ---- ---- ----

First you need to download and install LibreOffice. Can be downloaded from Here
Now open your terminal / command prompt then go to libreOffice root, for windows it may be OS/Program Files/LibreOffice/program here you'll find an executable soffice.exe

Here you can convert it directly by the above mentioned commands or you may also use :
soffice in place of libreoffice

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

I had to add extension=php_openssl.dll to my php.ini file located in xampp/php/php.ini. Somehow it was not there, after adding it and restarting Apache everything was working fine.

Stateless vs Stateful

Just to add on others' contributions....Another way is look at it from a web server and concurrency's point of view...

HTTP is stateless in nature for a reason...In the case of a web server, being stateful means that it would have to remember a user's 'state' for their last connection, and /or keep an open connection to a requester. That would be very expensive and 'stressful' in an application with thousands of concurrent connections...

Being stateless in this case has obvious efficient usage of resources...i.e support a connection in in a single instance of request and response...No overhead of keeping connections open and/or remember anything from the last request...

Best lightweight web server (only static content) for Windows

Have a look at mongoose:

  • single executable
  • very small memory footprint
  • allows multiple worker threads
  • easy to install as service
  • configurable with a configuration file if required

php, mysql - Too many connections to database error

If you need to increase MySQL Connections without MySQL restart do like below, also if you don't know configuration file, below use the mysqlworkbench or phpmyadmin or command prompt to run below queries.

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 151   |
+-----------------+-------+
1 row in set (0.00 sec)

mysql> SET GLOBAL max_connections = 250;
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 250   |
+-----------------+-------+
1 row in set (0.00 sec)

These settings will change at MySQL Restart.


For permanent changes add below line in my.cnf and restart MySQL.

max_connections = 151

How to display UTF-8 characters in phpMyAdmin?

Its realy simple to add multilanguage in myphpadmin if you got garbdata showing in myphpadmin, just go to myphpadmin click your database go to operations tab in operation tab page see collation section set it to utf8_general_ci, after that all your garbdata will show correctly. a simple and easy trick

entity framework Unable to load the specified metadata resource

Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.

The following res: (resource) references need to point to your model.

<add name="Entities" connectionString="metadata=
    res://*/Models.WraithNath.co.uk.csdl|
    res://*/Models.WraithNath.co.uk.ssdl|
    res://*/Models.WraithNath.co.uk.msl;

Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).

It also may help to specify the assembly rather than using "//*/".

Worst case, you can check everything (a bit slower but should always find the resource) by using

<add name="Entities" connectionString="metadata=
        res://*/;provider= <!-- ... -->

What is the first character in the sort order used by Windows Explorer?

I know it's an old question, but it's easy to check this out. Just create a folder with a bunch of dummy files whose names are each character on the keyboard. Of course, you can't really use \ | / : * ? " < > and leading and trailing blanks are a terrible idea.

If you do this, and it looks like no one did, you find that the Windows sort order for the FIRST character is 1. Special characters 2. Numbers 3. Letters

But for subsequent characters, it seems to be 1. Numbers 2. Special characters 3. Letters

Numbers are kind of weird, thanks to the "Improvements" made after the Y2K non-event. Special characters you would think would sort in ASCII order, but there are exceptions, notably the first two, apostrophe and dash, and the last two, plus and equals. Also, I have heard but not actually seen something about dashes being ignored. That is, in fact, NOT my experience.

So, ShxFee, I assume you meant the sort should be ascending, not descending, and the top-most (first) character in the sort order for the first character of the name is the apostrophe.

As NigelTouch said, special characters do not sort to ASCII, but my notes above specify exactly what does and does not sort in normal ASCII order. But he is certainly wrong about special characters always sorting first. As I noted above, that only appears to be true for the first character of the name.

Simple and fast method to compare images for similarity

If you can be sure to have precise alignment of your template (the icon) to the testing region, then any old sum of pixel differences will work.

If the alignment is only going to be a tiny bit off, then you can low-pass both images with cv::GaussianBlur before finding the sum of pixel differences.

If the quality of the alignment is potentially poor then I would recommend either a Histogram of Oriented Gradients or one of OpenCV's convenient keypoint detection/descriptor algorithms (such as SIFT or SURF).

Toggle Checkboxes on/off

Check-all checkbox should be updated itself under certain conditions. Try to click on '#select-all-teammembers' then untick few items and click select-all again. You can see inconsistency. To prevent it use the following trick:

  var checkBoxes = $('input[name=recipients\\[\\]]');
  $('#select-all-teammembers').click(function() {
    checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    $(this).prop("checked", checkBoxes.is(':checked'));
  }); 

BTW all checkboxes DOM-object should be cached as described above.

How to multiply values using SQL

Why use GROUP BY at all?

SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC

Import file size limit in PHPMyAdmin

In my case, I also had to add the line "FcgidMaxRequestLen 1073741824" (without the quotes) in /etc/apache2/mods-available/fcgid.conf. It's documented here http://forum.ispsystem.com/en/showthread.php?p=6611 . Since mod_fcgid 2.3.6, they changed the default for FcgidMaxRequestLen from 1GB to 128K (see https://svn.apache.org/repos/asf/httpd/mod_fcgid/trunk/CHANGES-FCGID )

How to specify font attributes for all elements on an html web page?

* {
 font-size: 100%;
 font-family: Arial;
}

The asterisk implies all elements.

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.

Show percent % instead of counts in charts of categorical variables

Since this was answered there have been some meaningful changes to the ggplot syntax. Summing up the discussion in the comments above:

 require(ggplot2)
 require(scales)

 p <- ggplot(mydataf, aes(x = foo)) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        ## version 3.0.0
        scale_y_continuous(labels=percent)

Here's a reproducible example using mtcars:

 ggplot(mtcars, aes(x = factor(hp))) +  
        geom_bar(aes(y = (..count..)/sum(..count..))) + 
        scale_y_continuous(labels = percent) ## version 3.0.0

enter image description here

This question is currently the #1 hit on google for 'ggplot count vs percentage histogram' so hopefully this helps distill all the information currently housed in comments on the accepted answer.

Remark: If hp is not set as a factor, ggplot returns:

enter image description here

Python base64 data decode

Note Slipstream's response, that base64.b64encode and base64.b64decode need bytes-like object, not string.

>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python3.6/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

PHP Pass by reference in foreach

I think this code show the procedure more clear.

<?php

$a = array ('zero','one','two', 'three');

foreach ($a as &$v) {
}

var_dump($a);

foreach ($a as $v) {
  var_dump($a);
}

Result: (Take attention on the last two array)

array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(5) "three"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(4) "zero"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(3) "one"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(3) "two"
}
array(4) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  &string(3) "two"
}

Apache SSL Configuration Error (SSL Connection Error)

Step to enable SSL correctly.

sudo a2enmod ssl  
sudo apt-get install openssl

Configure the path of SSL certificates in your SSL config file (default-ssl.conf) that might be located in /etc/apache2/sites-available. I have stored certificates under /etc/apache2/ssl/

SSLEngine On
SSLCertificateFile /etc/apache2/ssl/certificate.crt
SSLCertificateChainFile /etc/apache2/ssl/ca_bundle.crt
SSLCertificateKeyFile /etc/apache2/ssl/private.key

Enable SSL config file

sudo a2ensite default-ssl.conf

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:

Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True

Now it works fine.

Getting one value from a tuple

General

Single elements of a tuple a can be accessed -in an indexed array-like fashion-

via a[0], a[1], ... depending on the number of elements in the tuple.

Example

If your tuple is a=(3,"a")

  • a[0] yields 3,
  • a[1] yields "a"

Concrete answer to question

def tup():
  return (3, "hello")

tup() returns a 2-tuple.

In order to "solve"

i = 5 + tup()  # I want to add just the three

you select the 3 by

tup()[0|    #first element

so in total

i = 5 + tup()[0]

Alternatives

Go with namedtuple that allows you to access tuple elements by name (and by index). Details at https://docs.python.org/3/library/collections.html#collections.namedtuple

>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'

PHP Warning: PHP Startup: ????????: Unable to initialize module

If you installed php with homebrew, then check if your apache2.conf file is using homebrew version of php5.so file.

How to install and run phpize

Step - 1: If you are unsure about the php version installed, then first run the following command in terminal

php -v

Output: the above command will output the php version installed on your machine, mine is 7.2

PHP 7.2.3-1ubuntu1 (cli) (built: Mar 14 2018 22:03:58) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.3-1ubuntu1, Copyright (c) 1999-2018, by Zend Technologies

Step 2: Then to install phpize run the following command, Since my php version is 7.2.3. i will replace it with 7.2, so the command will be,

sudo apt-get install php7.2-dev

Step 3: Done!

Alternate method(Optional): To automatically install the phpize version based on the php version installed on your machine run the following command.

sudo apt-get install php-dev

This command will automatically detect the appropriate version of php installed and will install the matching phpize for the same.

What is mod_php?

mod_php means PHP, as an Apache module.

Basically, when loading mod_php as an Apache module, it allows Apache to interpret PHP files (those are interpreted by mod_php).


EDIT : There are (at least) two ways of running PHP, when working with Apache :

  • Using CGI : a PHP process is launched by Apache, and it is that PHP process that interprets PHP code -- not Apache itself
  • Using PHP as an Apache module (called mod_php) : the PHP interpreter is then kind of "embedded" inside the Apache process : there is no external PHP process -- which means that Apache and PHP can communicate better.


And re-edit, after the comment : using CGI or mod_php is up to you : it's only a matter of configuration of your webserver.

To know which way is currently used on your server, you can check the output of phpinfo() : there should be something indicating whether PHP is running via mod_php (or mod_php5), or via CGI.

You might also want to take a look at the php_sapi_name() function : it returns the type of interface between web server and PHP.


If you check in your Apache's configuration files, when using mod_php, there should be a LoadModule line looking like this :

LoadModule php5_module        modules/libphp5.so

(The file name, on the right, can be different -- on Windows, for example, it should be a .dll)

A good Sorted List for Java

SortedList decorator from Java Happy Libraries can be used to decorate TreeList from Apache Collections. That would produce a new list which performance is compareable to TreeSet. https://sourceforge.net/p/happy-guys/wiki/Sorted%20List/

How do I set up a private Git repository on GitHub? Is it even possible?

GitHub is a great tool in-all for making repositories. However, it does not do good with private repositories.

You're forced to pay for private repositories unless you get some sort of plan. I have a couple of projects so far, and if GitHub doesn't do what I want I just go to Bitbucket. It's a bit harder to work with than GitHub, however it's unlimited free repositories.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

Do not assume your unix_socket which would be different from one to another, try to find it.

First of all, get your unix_socket location.

$ mysql -u root -p

Enter your mysql password and login your mysql server from command line.

mysql> show variables like '%sock%';
+---------------+---------------------------------------+
| Variable_name | Value                                 |
+---------------+---------------------------------------+
| socket        | /opt/local/var/run/mysql5/mysqld.sock |
+---------------+---------------------------------------+

Your unix_soket could be diffrent.

Then change your php.ini, find your php.ini file from

<? phpinfo();

You maybe install many php with different version, so please don't assume your php.ini file location, get it from your 'phpinfo';

Change your php.ini:

mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

mysqli.default_socket = /opt/local/var/run/mysql5/mysqld.sock

pdo_mysql.default_socket = /opt/local/var/run/mysql5/mysqld.sock

Then restart your apache or php-fpm.

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Increasing number of max-connections will not solve the problem.

We were experiencing the same situation on our servers. This is what happens

User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.

You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour

SET interactive_timeout=3600

How to get main div container to align to centre?

You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.

What does "zend_mm_heap corrupted" mean

Because I never found a solution to this I decided to upgrade my LAMP environment. I went to Ubuntu 10.4 LTS with PHP 5.3.x. This seems to have stopped the problem for me.

Test whether string is a valid integer

For portability to pre-Bash 3.1 (when the =~ test was introduced), use expr.

if expr "$string" : '-\?[0-9]\+$' >/dev/null
then
  echo "String is a valid integer."
else
  echo "String is not a valid integer."
fi

expr STRING : REGEX searches for REGEX anchored at the start of STRING, echoing the first group (or length of match, if none) and returning success/failure. This is old regex syntax, hence the excess \. -\? means "maybe -", [0-9]\+ means "one or more digits", and $ means "end of string".

Bash also supports extended globs, though I don't recall from which version onwards.

shopt -s extglob
case "$string" of
    @(-|)[0-9]*([0-9]))
        echo "String is a valid integer." ;;
    *)
        echo "String is not a valid integer." ;;
esac

# equivalently, [[ $string = @(-|)[0-9]*([0-9])) ]]

@(-|) means "- or nothing", [0-9] means "digit", and *([0-9]) means "zero or more digits".

Convert a timedelta to days, hours and minutes

I found the easiest way is using str(timedelta). It will return a sting formatted like 3 days, 21:06:40.001000, and you can parse hours and minutes using simple string operations or regular expression.

How to getElementByClass instead of GetElementById with JavaScript?

Use it to access class in Javascript.

<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>

What is the best or most commonly used JMX Console / Client

JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!

Which one is the best PDF-API for PHP?

Try TCPDF. I find it the best so far.

For detailed tutorial on using the two most popular pdf generation classes: TCPDF and FPDF.. please follow this link: PHP: Easily create PDF on the fly with TCPDF and FPDF

Hope it helps.

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

Have you tried using:

(status,output) = commands.getstatusoutput("ps aux")

I thought this had fixed the exact same problem for me. But then my process ended up getting killed instead of failing to spawn, which is even worse..

After some testing I found that this only occurred on older versions of python: it happens with 2.6.5 but not with 2.7.2

My search had led me here python-close_fds-issue, but unsetting closed_fds had not solved the issue. It is still well worth a read.

I found that python was leaking file descriptors by just keeping an eye on it:

watch "ls /proc/$PYTHONPID/fd | wc -l"

Like you, I do want to capture the command's output, and I do want to avoid OOM errors... but it looks like the only way is for people to use a less buggy version of Python. Not ideal...

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Very simple :

In your Super POM parent or setting.xml, use

        <repository>
        <id>central</id>
        <releases>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <updatePolicy>never</updatePolicy>
        </snapshots>
        <url>http://repo1.maven.org/maven2</url>
        <layout>legacy</layout>
    </repository>

It's my tips

Find a class somewhere inside dozens of JAR files?

To search all jar files in a given directory for a particular class, you can do this:

ls *.jar | xargs grep -F MyClass

or, even simpler,

grep -F MyClass *.jar

Output looks like this:

Binary file foo.jar matches

It's very fast because the -F option means search for Fixed string, so it doesn't load the the regex engine for each grep invocation. If you need to, you can always omit the -F option and use regexes.

XSS filtering function in PHP

function clean($data){
    $data = rawurldecode($data);
    return filter_var($data, FILTER_SANITIZE_SPEC_CHARS);
}

file_get_contents behind a proxy?

To use file_get_contents() over/through a proxy that doesn't require authentication, something like this should do :

(I'm not able to test this one : my proxy requires an authentication)

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Of course, replacing the IP and port of my proxy by those which are OK for yours ;-)

If you're getting that kind of error :

Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required

It means your proxy requires an authentication.

If the proxy requires an authentication, you'll have to add a couple of lines, like this :

$auth = base64_encode('LOGIN:PASSWORD');

$aContext = array(
    'http' => array(
        'proxy'           => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
        'header'          => "Proxy-Authorization: Basic $auth",
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Same thing about IP and port, and, this time, also LOGIN and PASSWORD ;-) Check out all valid http options.

Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.

And... The page should be displayed ;-)

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

If you're developing something more complicated and want multiple columns to be fixed/stuck to the left, you'll probably need something like this.

_x000D_
_x000D_
.wrapper {_x000D_
    overflow-x: scroll;_x000D_
}_x000D_
_x000D_
td {_x000D_
    min-width: 50px;_x000D_
}_x000D_
_x000D_
.fixed {_x000D_
    position: absolute;_x000D_
    background: #aaa;_x000D_
}
_x000D_
<div class="content" style="width: 400px">_x000D_
_x000D_
  <div class="wrapper" style="margin-left: 100px">_x000D_
_x000D_
      <table>_x000D_
        <thead>_x000D_
          <tr>_x000D_
            <th class="fixed" style="left: 0px">aaa</th>_x000D_
            <th class="fixed" style="left: 50px">aaa2</th>_x000D_
            <th>a</th>_x000D_
            <th>b</th>_x000D_
            <th>c</th>_x000D_
            <th>d</th>_x000D_
            <th>e</th>_x000D_
            <th>f</th>_x000D_
            <th>a</th>_x000D_
            <th>b</th>_x000D_
            <th>c</th>_x000D_
            <th>d</th>_x000D_
            <th>e</th>_x000D_
            <th>f</th>_x000D_
            <th>a</th>_x000D_
            <th>b</th>_x000D_
            <th>c</th>_x000D_
            <th>d</th>_x000D_
            <th>e</th>_x000D_
            <th>f</th>_x000D_
            <th>a</th>_x000D_
            <th>b</th>_x000D_
            <th>c</th>_x000D_
            <th>d</th>_x000D_
            <th>e</th>_x000D_
            <th>f</th>        _x000D_
          </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
          <tr>_x000D_
            <td class="fixed" style="left: 0px">aaa</td>_x000D_
            <td class="fixed" style="left: 50px">aaa2</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td class="fixed" style="left: 0">bbb</td>_x000D_
            <td class="fixed" style="left: 50px">bbb2</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
            <td>a</td>_x000D_
            <td>b</td>_x000D_
            <td>c</td>_x000D_
            <td>d</td>_x000D_
            <td>e</td>_x000D_
            <td>f</td>_x000D_
          </tr>_x000D_
        </tbody>_x000D_
      </table>_x000D_
_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Disable pasting text into HTML form

Hope below code will work :

<!--Disable Copy And Paste-->
<script language='JavaScript1.2'>
function disableselect(e){
return false
}
function reEnable(){
return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>

Unable to call the built in mb_internal_encoding method?

If someone is having trouble with installing php-mbstring package in ubuntu do following sudo apt-get install libapache2-mod-php5

Rails :include vs. :joins

tl;dr

I contrast them in two ways:

joins - For conditional selection of records.

includes - When using an association on each member of a result set.

Longer version

Joins is meant to filter the result set coming from the database. You use it to do set operations on your table. Think of this as a where clause that performs set theory.

Post.joins(:comments)

is the same as

Post.where('id in (select post_id from comments)')

Except that if there are more than one comment you will get duplicate posts back with the joins. But every post will be a post that has comments. You can correct this with distinct:

Post.joins(:comments).count
=> 10
Post.joins(:comments).distinct.count
=> 2

In contract, the includes method will simply make sure that there are no additional database queries when referencing the relation (so that we don't make n + 1 queries)

Post.includes(:comments).count
=> 4 # includes posts without comments so the count might be higher.

The moral is, use joins when you want to do conditional set operations and use includes when you are going to be using a relation on each member of a collection.

Java: Get last element after split

String str = "www.anywebsite.com/folder/subfolder/directory";
int index = str.lastIndexOf('/');
String lastString = str.substring(index +1);

Now lastString has the value "directory"

Use success() or complete() in AJAX call

complete executes after either the success or error callback were executed.

Maybe you should check the second parameter complete offers too. It's a String holding the type of success the ajaxCall had.

The different callbacks are described a little more in detail here jQuery.ajax( options )


I guess you missed the fact that the complete and the success function (I know inconsistent API) get different data passed in. success gets only the data, complete gets the whole XMLHttpRequest object. Of course there is no responseText property on the data string.

So if you replace complete with success you also have to replace data.responseText with data only.

success

The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.

complete

The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.

If you need to have access to the whole XMLHttpRequest object in the success callback I suggest trying this.

var myXHR = $.ajax({
    ...
    success: function(data, status) {
        ...do whatever with myXHR; e.g. myXHR.responseText...
    },
    ...
});

How to analyze information from a Java core dump?

Okay if you've created the core dump with gcore or gdb then you'll need to convert it to something called a HPROF file. These can be used by VisualVM, Netbeans or Eclipse's Memory Analyzer Tool (formerly SAP Memory Analyzer). I'd recommend Eclipse MAT.

To convert the file use the commandline tool jmap.

# jmap -dump:format=b,file=dump.hprof /usr/bin/java core.1234

where:

dump.hprof is the name of the hprof file you wish to create

/usr/bin/java is the path to the version of the java binary that generated the core dump

core.1234 is your regular core file.

Dynamic WHERE clause in LINQ

You can also use the PredicateBuilder from LinqKit to chain multiple typesafe lambda expressions using Or or And.

http://www.albahari.com/nutshell/predicatebuilder.aspx

How does "FOR" work in cmd batch file?

Couldn't resist throwing this out there, old as this thread is... Usually when the need arises to iterate through each of the files in PATH, all you really want to do is find a particular file... If that's the case, this one-liner will spit out the first directory it finds your file in:

(ex: looking for java.exe)

for %%x in (java.exe) do echo %%~dp$PATH:x

Could not establish trust relationship for SSL/TLS secure channel -- SOAP

The very simple "catch all" solution is this:

System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

The solution from sebastian-castaldi is a bit more detailed.

Best way to determine user's locale within browser

You said your website has Flash, then, as another option, you can get operation system's language with flash.system.Capabilities.language— see How to determine OS language within browser to guess an operation system locale.

Visual Studio: ContextSwitchDeadlock

The ContextSwitchDeadlock doesn't necessarily mean your code has an issue, just that there is a potential. If you go to Debug > Exceptions in the menu and expand the Managed Debugging Assistants, you will find ContextSwitchDeadlock is enabled. If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue.

Reading an Excel file in PHP

It depends on how you want to use the data in the excel file. If you want to import it into mysql, you could simply save it as a CSV formatted file and then use fgetcsv to parse it.

Clearing NSUserDefaults

You can remove the application's persistent domain like this:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

In Swift 3 and later:

if let bundleID = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundleID)
}

This is similar to the answer by @samvermette but is a little bit cleaner IMO.

How can I get a vertical scrollbar in my ListBox?

In my case the number of items in the ListBox is dynamic so I didn't want to use the Height property. I used MaxHeight instead and it works nicely. The scrollbar appears when it fills the space I've allocated for it.

How can I combine multiple rows into a comma-delimited list in Oracle?

you can try this query.

select listagg(country_name,',') within group (order by country_name) cnt 
from countries; 

Select values of checkbox group with jQuery

With map in instead of each it is possible to avoid the array creation step:

var checkedCheckboxesValues = 
    $('input:checkbox[name="groupName"]:checked')
        .map(function() {
            return $(this).val();
        }).get();

From the map() page of the docs:

Pass each element in the current matched set through a function, producing a new jQuery object containing the return values

get() turns those values into an array.

Is there a way for non-root processes to bind to "privileged" ports on Linux?

At startup:

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

Then you can bind to the port you forward to.

Can I invoke an instance method on a Ruby module without including it?

I think the shortest way to do just throw-away single call (without altering existing modules or creating new ones) would be as follows:

Class.new.extend(UsefulThings).get_file

Changing website favicon dynamically

I use this feature all the time when developing sites ... so I can see at-a-glance which tab has local, dev or prod running in it.

Now that Chrome supports SVG favicons it makes it a whole lot easier.

Tampermonkey Script

Have a gander at https://gist.github.com/elliz/bb7661d8ed1535c93d03afcd0609360f for a tampermonkey script that points to a demo site I chucked up at https://elliz.github.io/svg-favicon/

Basic code

Adapted this from another answer ... could be improved but good enough for my needs.

(function() {
    'use strict';

    // play with https://codepen.io/elliz/full/ygvgay for getting it right
    // viewBox is required but does not need to be 16x16
    const svg = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
      <circle cx="8" cy="8" r="7.2" fill="gold" stroke="#000" stroke-width="1" />
      <circle cx="8" cy="8" r="3.1" fill="#fff" stroke="#000" stroke-width="1" />
    </svg>
    `;

    var favicon_link_html = document.createElement('link');
    favicon_link_html.rel = 'icon';
    favicon_link_html.href = svgToDataUri(svg);
    favicon_link_html.type = 'image/svg+xml';

    try {
        let favicons = document.querySelectorAll('link[rel~="icon"]');
        favicons.forEach(function(favicon) {
            favicon.parentNode.removeChild(favicon);
        });

        const head = document.getElementsByTagName('head')[0];
        head.insertBefore( favicon_link_html, head.firstChild );
    }
    catch(e) { }

    // functions -------------------------------
    function escapeRegExp(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }

    function replaceAll(str, find, replace) {
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
    }

    function svgToDataUri(svg) {
        // these may not all be needed - used to be for uri-encoded svg in old browsers
        var encoded = svg.replace(/\s+/g, " ")
        encoded = replaceAll(encoded, "%", "%25");
        encoded = replaceAll(encoded, "> <", "><"); // normalise spaces elements
        encoded = replaceAll(encoded, "; }", ";}"); // normalise spaces css
        encoded = replaceAll(encoded, "<", "%3c");
        encoded = replaceAll(encoded, ">", "%3e");
        encoded = replaceAll(encoded, "\"", "'"); // normalise quotes ... possible issues with quotes in <text>
        encoded = replaceAll(encoded, "#", "%23"); // needed for ie and firefox
        encoded = replaceAll(encoded, "{", "%7b");
        encoded = replaceAll(encoded, "}", "%7d");
        encoded = replaceAll(encoded, "|", "%7c");
        encoded = replaceAll(encoded, "^", "%5e");
        encoded = replaceAll(encoded, "`", "%60");
        encoded = replaceAll(encoded, "@", "%40");
        var dataUri = 'data:image/svg+xml;charset=UTF-8,' + encoded.trim();
        return dataUri;
    }

})();

Just pop your own SVG (maybe cleaned with Jake Archibald's SVGOMG if you're using a tool) into the const at the top. Make sure it is square (using the viewBox attribute) and you're good to go.

Simple Random Samples from a Sql database

Just use

WHERE RAND() < 0.1 

to get 10% of the records or

WHERE RAND() < 0.01 

to get 1% of the records, etc.

How to improve Netbeans performance?

Don't invest time in optimizing your NB installation as long as you can scale vertically: get a SSD (and faster hardware in general).

Also:

  • Add an exception for all relevant folders (e.g. project dir, temp dir) to your anti virus software (or better, get rid of it).
  • Don't use network drives for your projects
    • check if your home drive is local
    • check if your IDE uses non-local folders (e.g. %AppData%)

PHP validation/regex for URL

The best URL Regex that worked for me:

function valid_URL($url){
    return preg_match('%^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu', $url);
}

Examples:

valid_URL('https://twitter.com'); // true
valid_URL('http://twitter.com');  // true
valid_URL('http://twitter.co');   // true
valid_URL('http://t.co');         // true
valid_URL('http://twitter.c');    // false
valid_URL('htt://twitter.com');   // false

valid_URL('http://example.com/?a=1&b=2&c=3'); // true
valid_URL('http://127.0.0.1');    // true
valid_URL('');                    // false
valid_URL(1);                     // false

Source: http://urlregex.com/

How can I measure the actual memory usage of an application or process?

I would suggest that you use atop. You can find everything about it on this page. It is capable of providing all the necessary KPI for your processes and it can also capture to a file.

Why not use tables for layout in HTML?

In the past, screen readers and other accessibility software had a difficult time handling tables in an efficient fashion. To some extent, this became handled in screen readers by the reader switching between a "table" mode and a "layout" mode based on what it saw inside the table. This was often wrong, and so the users had to manually switch the mode when navigating through tables. In any case, the large, often highly nested tables were, and to a large extent, are still very difficult to navigate through using a screen reader.

The same is true when divs or other block-level elements are used to recreate tables and are highly nested. The purpose of divs is to be used as a fomating and layout element, and as such, are intended used to hold similar information, and lay it out on the screen for visual users. When a screen reader encounters a page, it often ignores any layout information, both CSS based, as well as html attribute based(This isn't true for all screen readers, but for the most popular ones, like JAWS, Windows Eyes, and Orca for Linux it is).

To this end, tabular data, that is to say data that makes logical sense to be ordered in two or more dimensions, with some sort of headers, is best placed in tables, and use divs to manage the layout of content on the page. (another way to think of what "tabular data" is is to try to draw it in graph form...if you can't, it likely is not best represented in a table)

Finally, with a table-based layout, in order to achieve a fine-grained control of the position of elements on the page, highly nested tables are often used. This has two effects: 1.) Increased code size for each page - Since navigation and common structure is often done with the tables, the same code is sent over the network for each request, whereas a div/css based layout pulls the css file over once, and then uses less wordy divs. 2.) Highly nested tables take much longer for the client's browser to render, leading to slightly slower load times.

In both cases, the increase in "last mile" bandwidth, as well as much faster personal computers mitigates these factors, but none-the-less, they still are existing issues for many sites.

With all of this in mind, as others have said, tables are easier, because they are more grid-oriented, allowing for less thought. If the site in question is not expected to be around long, or will not be maintained, it might make sense to do what is easiest, because it might be the most cost effective. However, if the anticipated userbase might include a substantial portion of handicapped individuals, or if the site will be maintained by others for a long time, spending the time up front to do things in a concise, accessible way may payoff more in the end.

List of macOS text editors and code editors

I like Aptana Studio and Redcar for rails programming.

Is there a way to make Firefox ignore invalid ssl-certificates?

I ran into this issue when trying to get to one of my companies intranet sites. Here is the solution I used:

  1. enter about:config into the firefox address bar and agree to continue.
  2. search for the preference named security.ssl.enable_ocsp_stapling.
  3. double-click this item to change its value to false.

This will lower your security as you will be able to view sites with invalid certs. Firefox will still prompt you that the cert is invalid and you have the choice to proceed forward, so it was worth the risk for me.

Convert Pandas column containing NaNs to dtype `int`

use pd.to_numeric()

df["DateColumn"] = pd.to_numeric(df["DateColumn"])

simple and clean

Why is 2 * (i * i) faster than 2 * i * i in Java?

Byte codes: https://cs.nyu.edu/courses/fall00/V22.0201-001/jvm2.html Byte codes Viewer: https://github.com/Konloch/bytecode-viewer

On my JDK (Windows 10 64 bit, 1.8.0_65-b17) I can reproduce and explain:

public static void main(String[] args) {
    int repeat = 10;
    long A = 0;
    long B = 0;
    for (int i = 0; i < repeat; i++) {
        A += test();
        B += testB();
    }

    System.out.println(A / repeat + " ms");
    System.out.println(B / repeat + " ms");
}


private static long test() {
    int n = 0;
    for (int i = 0; i < 1000; i++) {
        n += multi(i);
    }
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) {
        n += multi(i);
    }
    long ms = (System.currentTimeMillis() - startTime);
    System.out.println(ms + " ms A " + n);
    return ms;
}


private static long testB() {
    int n = 0;
    for (int i = 0; i < 1000; i++) {
        n += multiB(i);
    }
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) {
        n += multiB(i);
    }
    long ms = (System.currentTimeMillis() - startTime);
    System.out.println(ms + " ms B " + n);
    return ms;
}

private static int multiB(int i) {
    return 2 * (i * i);
}

private static int multi(int i) {
    return 2 * i * i;
}

Output:

...
405 ms A 785527736
327 ms B 785527736
404 ms A 785527736
329 ms B 785527736
404 ms A 785527736
328 ms B 785527736
404 ms A 785527736
328 ms B 785527736
410 ms
333 ms

So why? The byte code is this:

 private static multiB(int arg0) { // 2 * (i * i)
     <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>

     L1 {
         iconst_2
         iload0
         iload0
         imul
         imul
         ireturn
     }
     L2 {
     }
 }

 private static multi(int arg0) { // 2 * i * i
     <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>

     L1 {
         iconst_2
         iload0
         imul
         iload0
         imul
         ireturn
     }
     L2 {
     }
 }

The difference being: With brackets (2 * (i * i)):

  • push const stack
  • push local on stack
  • push local on stack
  • multiply top of stack
  • multiply top of stack

Without brackets (2 * i * i):

  • push const stack
  • push local on stack
  • multiply top of stack
  • push local on stack
  • multiply top of stack

Loading all on the stack and then working back down is faster than switching between putting on the stack and operating on it.

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

Is there a way to view past mysql queries with phpmyadmin?

Here is a trick that some may find useful:

For Select queries (only), you can create Views, especially where you find yourself running the same select queries over and over e.g. in production support scenarios.

The main advantages of creating Views are:

  • they are resident within the database and therefore permanent
  • they can be shared across sessions and users
  • they provide all the usual benefits of working with tables
  • they can be queried further, just like tables e.g. to filter down the results further
  • as they are stored as queries under the hood, they do not add any overheads.

You can create a view easily by simply clicking the "Create view" link at the bottom of the results table display.

How to instantiate a File object in JavaScript?

Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File

var file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});

Python Pandas - Find difference between two data frames

Finding difference by index. Assuming df1 is a subset of df2 and the indexes are carried forward when subsetting

df1.loc[set(df1.index).symmetric_difference(set(df2.index))].dropna()

# Example

df1 = pd.DataFrame({"gender":np.random.choice(['m','f'],size=5), "subject":np.random.choice(["bio","phy","chem"],size=5)}, index = [1,2,3,4,5])

df2 =  df1.loc[[1,3,5]]

df1

 gender subject
1      f     bio
2      m    chem
3      f     phy
4      m     bio
5      f     bio

df2

  gender subject
1      f     bio
3      f     phy
5      f     bio

df3 = df1.loc[set(df1.index).symmetric_difference(set(df2.index))].dropna()

df3

  gender subject
2      m    chem
4      m     bio

Split string into tokens and save them in an array

You can use strtok()

char string[]=  "abc/qwe/jkh";
char *array[10];
int i=0;

array[i] = strtok(string,"/");

while(array[i]!=NULL)
{
   array[++i] = strtok(NULL,"/");
}

pycharm running way slow

In my case, the problem was a folder in the project directory containing 300k+ files totaling 11Gb. This was just a temporary folder with images results of some computation. After moving this folder out of the project structure, the slowness disappeared. I hope this can help someone, please check your project structure to see if there is anything that is not necessary.

Download a file by jQuery.Ajax

How to DOWNLOAD a file after receiving it by AJAX

It’s convenient when the file is created for a long time and you need to show PRELOADER

Example when submitting a web form:

<script>
$(function () {
    $('form').submit(function () {
        $('#loader').show();
        $.ajax({
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'binary',
            xhrFields: {
                'responseType': 'blob'
            },
            success: function(data, status, xhr) {
                $('#loader').hide();
                // if(data.type.indexOf('text/html') != -1){//If instead of a file you get an error page
                //     var reader = new FileReader();
                //     reader.readAsText(data);
                //     reader.onload = function() {alert(reader.result);};
                //     return;
                // }
                var link = document.createElement('a'),
                    filename = 'file.xlsx';
                // if(xhr.getResponseHeader('Content-Disposition')){//filename 
                //     filename = xhr.getResponseHeader('Content-Disposition');
                //     filename=filename.match(/filename="(.*?)"/)[1];
                //     filename=decodeURIComponent(escape(filename));
                // }
                link.href = URL.createObjectURL(data);
                link.download = filename;
                link.click();
            }
        });
        return false;
    });
});
</script>

Optional functional is commented out to simplify the example.

No need to create temporary files on the server.

On jQuery v2.2.4 OK. There will be an error on the old version:

Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

Setting up foreign keys in phpMyAdmin?

From the official MySQL documentation at https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html:

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.

'import' and 'export' may only appear at the top level

This is not direct answer to the original question but I hope this suggestion helps someones with similar error:

When using a newer web-api with Webpack+Babel for transpiling and you get

Module parse failed: 'import' and 'export' may only appear at the top level

then you probably forgot to import a polyfill.

For example:
when using fetch() api and targeting for es2015, you should

  1. add whatwg-fetch polyfill to package.json
  2. add import {fetch} from 'whatwg-fetch'

Get current time in hours and minutes

you can use command

date | awk '{print $4}'| cut -d ':' -f3

as you mentioned using only the date|awk '{print $4}' pipeline gives you something like this

20:18:19

so as we can see if we want to extract some part of this string then we need a delimiter , for our case it is :, so we decide to chop on the basis of :. Now this delimiter will chop the string into three parts i.e. 20 ,18 and 19 , as we want the second one we use -f2 in our command. to sum up ,

cut : chops some string based on delimeter.

-d : delimeter (here :)

-f2 : the chopped off token that we want.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I'm a MacOS user.

I solved it by uninstalling Android Studio and reinstalling it again.

If you want to try this link helped me a lot.

Uninstall Android Studio MacOS (terminal)

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

You need to tell Eclipse which JDK/JRE's you have installed and where they are located.

This is somewhat burried in the Eclipse preferences: In the Window-Menu select "Preferences". In the Preferences Tree, open the Node "Java" and select "Installed JRE's". Then click on the "Add"-Button in the Panel and select "Standard VM", "Next" and for "JRE Home" click on the "Directory"-Button and select the top level folder of the JDK you want to add.

Its easier than the description may make it look.

Git - Won't add files?

I just had this issue and the problem was that I was inside a directory and not at the top level. Once I moved to the top level it worked.

usr/bin/ld: cannot find -l<nameOfTheLibrary>

To figure out what the linker is looking for, run it in verbose mode.

For example, I encountered this issue while trying to compile MySQL with ZLIB support. I was receiving an error like this during compilation:

/usr/bin/ld: cannot find -lzlib

I did some Googl'ing and kept coming across different issues of the same kind where people would say to make sure the .so file actually exists and if it doesn't, then create a symlink to the versioned file, for example, zlib.so.1.2.8. But, when I checked, zlib.so DID exist. So, I thought, surely that couldn't be the problem.

I came across another post on the Internets that suggested to run make with LD_DEBUG=all:

LD_DEBUG=all make

Although I got a TON of debugging output, it wasn't actually helpful. It added more confusion than anything else. So, I was about to give up.

Then, I had an epiphany. I thought to actually check the help text for the ld command:

ld --help

From that, I figured out how to run ld in verbose mode (imagine that):

ld -lzlib --verbose

This is the output I got:

==================================================
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.a failed
attempt to open /usr/local/lib64/libzlib.so failed
attempt to open /usr/local/lib64/libzlib.a failed
attempt to open /lib64/libzlib.so failed
attempt to open /lib64/libzlib.a failed
attempt to open /usr/lib64/libzlib.so failed
attempt to open /usr/lib64/libzlib.a failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.a failed
attempt to open /usr/local/lib/libzlib.so failed
attempt to open /usr/local/lib/libzlib.a failed
attempt to open /lib/libzlib.so failed
attempt to open /lib/libzlib.a failed
attempt to open /usr/lib/libzlib.so failed
attempt to open /usr/lib/libzlib.a failed
/usr/bin/ld.bfd.real: cannot find -lzlib

Ding, ding, ding...

So, to finally fix it so I could compile MySQL with my own version of ZLIB (rather than the bundled version):

sudo ln -s /usr/lib/libz.so.1.2.8 /usr/lib/libzlib.so

Voila!

How can I create tests in Android Studio?

As of Android Studio 1.1, we've got official (experimental) support for writing Unit Tests (Roboelectric works as well).

Source: https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support

How to get a list of column names

$<?
$db = sqlite_open('mysqlitedb');
$cols = sqlite_fetch_column_types('form name'$db, SQLITE_ASSOC);
foreach ($cols as $column => $type) {
  echo "Column: $column  Type: $type\n";
}

What is the default root pasword for MySQL 5.7

After you installed MySQL-community-server 5.7 from fresh on linux, you will need to find the temporary password from /var/log/mysqld.log to login as root.

  1. grep 'temporary password' /var/log/mysqld.log
  2. Run mysql_secure_installation to change new password

ref: http://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html

How can I get a list of locally installed Python modules?

I ran into a custom installed python 2.7 on OS X. It required X11 to list modules installed (both using help and pydoc).

To be able to list all modules without installing X11 I ran pydoc as http-server, i.e.:

pydoc -p 12345

Then it's possible to direct Safari to http://localhost:12345/ to see all modules.

How can I display a tooltip message on hover using jQuery?

You can use bootstrap tooltip. Do not forget to initialize it.

<span class="tooltip-r" data-toggle="tooltip" data-placement="left" title="Explanation">
inside span
</span>

Will be shown text Explanation on the left side.

and run it with js:

$('.tooltip-r').tooltip();

Spring cannot find bean xml configuration file when it does exist

I also had a similar problem but because of a bit different cause so sharing here in case it can help anybody.

My file location

beans.xml file

How I was using

ClassPathXmlApplicationContext("beans.xml");

There are two solutions

  1. Take the beans.xml out of package and put in default package.
  2. Specify package name while using it viz.

ClassPathXmlApplicationContext("com/mypackage/beans.xml");

Insert variable into Header Location PHP

We can also use this with the $_GET method

$employee_id = 'EMP-1234';

header('Location: employee.php?id='.$employee_id);

add item in array list of android

You're trying to assign the result of the add operation to resultArrGame, and add can either return true or false, depending on if the operation was successful or not. What you want is probably just:

resultArrGame.add(txt.Game.getText().toString());

How do I send a file in Android from a mobile device to server using http?

the most effective method is to use org.apache.http.entity.mime.MultipartEntity;

see this code from the link using org.apache.http.entity.mime.MultipartEntity;

public class SimplePostRequestTest3 {

  /**
   * @param args
   */
  public static void main(String[] args) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp");

    try {
      FileBody bin = new FileBody(new File("C:/ABC.txt"));
      StringBody comment = new StringBody("BETHECODER HttpClient Tutorials");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("fileup0", bin);
      reqEntity.addPart("fileup1", comment);

      reqEntity.addPart("ONE", new StringBody("11111111"));
      reqEntity.addPart("TWO", new StringBody("222222222"));
      httppost.setEntity(reqEntity);

      System.out.println("Requesting : " + httppost.getRequestLine());
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httppost, responseHandler);

      System.out.println("responseBody : " + responseBody);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }

}

Added:

Example Link

bootstrap datepicker today as default

Set after Init

 $('#dp-ex-3').datepicker({ autoclose: true, language: 'es' });
$('#dp-ex-3').datepicker('update', new Date());

This example is working.

Python 'list indices must be integers, not tuple"

To create list of lists, you need to separate them with commas, like this

coin_args = [
    ["pennies", '2.5', '50.0', '.01'],
    ["nickles", '5.0', '40.0', '.05'],
    ["dimes", '2.268', '50.0', '.1'],
    ["quarters", '5.67', '40.0', '.25']
]

How to restart adb from root to user mode?

adb kill-server and adb start-server only control the adb daemon on the PC side. You need to restart adbd daemon on the device itself after reverting the service.adb.root property change done by adb root:

~$ adb shell id
uid=2000(shell) gid=2000(shell)

~$ adb root
restarting adbd as root

~$ adb shell id
uid=0(root) gid=0(root)

~$ adb shell 'setprop service.adb.root 0; setprop ctl.restart adbd'

~$ adb shell id
uid=2000(shell) gid=2000(shell)

C# : Passing a Generic Object

You need to define something in the interface, such as:

public interface ITest
{
    string Name { get; }
}

Implement ITest in your classes:

public class MyClass1 : ITest
{
    public string Name { get { return "Test1"; } }
}

public class MyClass2 : ITest
{
    public string Name { get { return "Test2"; } }
}

Then restrict your generic Print function, to ITest:

public void Print<T>(T test) where T : ITest
{
}

How to change navbar/container width? Bootstrap 3

just simple:

.navbar{
    width:65% !important;
    margin:0px auto;
    left:0;
    right:0;
    padding:0;
}

or,

.navbar.navbar-fixed-top{
    width:65% !important;
    margin:0px auto;
    left:0;
    right:0;
    padding:0;
}

Hope it works (at least, for future searchers)

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

What Worked for me was:

Open localhost/reports
Go to properties tab (SSRS 2008)
Security->New Role Assignment
Add DOMAIN/USERNAME or DOMAIN/USERGROUP
Check Report builder

Request format is unrecognized for URL unexpectedly ending in

Found a solution on this website

All you need is to add the following to your web.config

<configuration>
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</configuration>

More info from Microsoft

Highcharts - how to have a chart with dynamic height?

Just don't set the height property in HighCharts and it will handle it dynamically for you so long as you set a height on the chart's containing element. It can be a fixed number or a even a percent if position is absolute.

Highcharts docs:

By default the height is calculated from the offset height of the containing element

Example: http://jsfiddle.net/wkkAd/149/

#container {
    height:100%;
    width:100%;
    position:absolute;
}

Disabling SSL Certificate Validation in Spring RestTemplate

If you are using rest template, you can use this piece of code

    fun getClientHttpRequestFactory(): ClientHttpRequestFactory {
        val timeout = envTimeout.toInt()
        val config = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build()

        val acceptingTrustStrategy = TrustStrategy { chain: Array<X509Certificate?>?, authType: String? -> true }

        val sslContext: SSLContext = SSLContexts.custom()
            .loadTrustMaterial(null, acceptingTrustStrategy)
            .build()

        val csf = SSLConnectionSocketFactory(sslContext)

        val client = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(config)
            .setSSLSocketFactory(csf)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build()
        return HttpComponentsClientHttpRequestFactory(client)
    }

    @Bean
    fun getRestTemplate(): RestTemplate {
        return RestTemplate(getClientHttpRequestFactory())
    }

Removing duplicate elements from an array in Swift

Many answers available here, but I missed this simple extension, suitable for Swift 2 and up:

extension Array where Element:Equatable {
    func removeDuplicates() -> [Element] {
        var result = [Element]()

        for value in self {
            if result.contains(value) == false {
                result.append(value)
            }
        }

        return result
    }
}

Makes it super simple. Can be called like this:

let arrayOfInts = [2, 2, 4, 4]
print(arrayOfInts.removeDuplicates()) // Prints: [2, 4]

Filtering based on properties

To filter an array based on properties, you can use this method:

extension Array {

    func filterDuplicates(@noescape includeElement: (lhs:Element, rhs:Element) -> Bool) -> [Element]{
        var results = [Element]()

        forEach { (element) in
            let existingElements = results.filter {
                return includeElement(lhs: element, rhs: $0)
            }
            if existingElements.count == 0 {
                results.append(element)
            }
        }

        return results
    }
}

Which you can call as followed:

let filteredElements = myElements.filterDuplicates { $0.PropertyOne == $1.PropertyOne && $0.PropertyTwo == $1.PropertyTwo }

How to remove the arrow from a select element in Firefox

Since Firefox 35, "-moz-appearance:none" that you already wrote in your code, finally remove arrow button as desired.

It was a bug solved since that version.

Visual C++ executable and missing MSVCR100d.dll

Usually the application that misses the .dll indicates what version you need – if one does not work, simply download the Microsoft visual C++ 2010 x86 or x64 from this link:

For 32 bit OS:Here

For 64 bit OS:Here

Java ArrayList of Arrays?

BTW. you should prefer coding against an Interface.

private ArrayList<String[]> action = new ArrayList<String[]>();

Should be

private List<String[]> action = new ArrayList<String[]>();

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

The following groovy script would be useful, if your job does not use "Source Code Management" directly (likewise "Git Parameter Plugin"), but still have access to a local (cloned) git repository:

import jenkins.model.Jenkins

def envVars = Jenkins.instance.getNodeProperties()[0].getEnvVars() 
def GIT_PROJECT_PATH = envVars.get('GIT_PROJECT_PATH') 
def gettags = "git ls-remote -t --heads origin".execute(null, new File(GIT_PROJECT_PATH))

return gettags.text.readLines()
         .collect { it.split()[1].replaceAll('\\^\\{\\}', '').replaceAll('refs/\\w+/', '')  }
         .unique()

See full explanation here: https://stackoverflow.com/a/37810768/658497

convert strtotime to date time format in php

$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);

Where

http://php.net/manual/en/function.date.php

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

window.location.href and window.open () methods in JavaScript

The window.open will open url in new browser Tab

The window.location.href will open url in current Tab (instead you can use location)

Here is example fiddle (in SO snippets window.open doesn't work)

_x000D_
_x000D_
var url = 'https://example.com';_x000D_
_x000D_
function go1() { window.open(url) }_x000D_
_x000D_
function go2() { window.location.href = url }_x000D_
_x000D_
function go3() { location = url }
_x000D_
<div>Go by:</div>_x000D_
<button onclick="go1()">window.open</button>_x000D_
<button onclick="go2()">window.location.href</button>_x000D_
<button onclick="go3()">location</button>
_x000D_
_x000D_
_x000D_

sql query to return differences between two tables

There is a performance issue related with the left join as well as full join with large data.

In my opinion this is the best solution:

select [First Name], count(1) e from (select * from [Temp Test Data] union all select * from [Temp Test Data 2]) a group by [First Name] having e = 1

Run an Ansible task only when the variable contains a specific string

This works for me in Ansible 2.9:

variable1 = www.example.com. 
variable2 = www.example.org. 

when: ".com" in variable1

and for not:

when: not ".com" in variable2

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

In my case, I fixed this error by change export default class yourComponent extends React.Component() {} to export default class yourComponent extends React.Component {}. Yes delete the parenthesis () fixed the error.

Correct modification of state arrays in React.js

I was having a similar issue when I wanted to modify the array state while retaining the position of the element in the array

This is a function to toggle between like and unlike:

    const liker = (index) =>
        setData((prevState) => {
            prevState[index].like = !prevState[index].like;
            return [...prevState];
        });

as we can say the function takes the index of the element in the array state, and we go ahead and modify the old state and rebuild the state tree

ruby 1.9: invalid byte sequence in UTF-8

If you don't "care" about the data you can just do something like:

search_params = params[:search].valid_encoding? ? params[:search].gsub(/\W+/, '') : "nothing"

I just used valid_encoding? to get passed it. Mine is a search field, and so i was finding the same weirdness over and over so I used something like: just to have the system not break. Since i don't control the user experience to autovalidate prior to sending this info (like auto feedback to say "dummy up!") I can just take it in, strip it out and return blank results.

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

Difference between Static methods and Instance methods

Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

An efficient compression algorithm for short text strings

I don't have code to hand, but I always liked the approach of building a 2D lookup table of size 256 * 256 chars (RFC 1978, PPP Predictor Compression Protocol). To compress a string you loop over each char and use the lookup table to get the 'predicted' next char using the current and previous char as indexes into the table. If there is a match you write a single 1 bit, otherwise write a 0, the char and update the lookup table with the current char. This approach basically maintains a dynamic (and crude) lookup table of the most probable next character in the data stream.

You can start with a zeroed lookup table, but obviosuly it works best on very short strings if it is initialised with the most likely character for each character pair, for example, for the English language. So long as the initial lookup table is the same for compression and decompression you don't need to emit it into the compressed data.

This algorithm doesn't give a brilliant compression ratio, but it is incredibly frugal with memory and CPU resources and can also work on a continuous stream of data - the decompressor maintains its own copy of the lookup table as it decompresses, thus the lookup table adjusts to the type of data being compressed.

How to enable CORS in flask

OK, I don't think the official snippet mentioned by galuszkak should be used everywhere, we should concern the case that some bug may be triggered during the handler such as hello_world function. Whether the response is correct or uncorrect, the Access-Control-Allow-Origin header is what we should concern. So, thing is very simple, just like bellow:

@blueprint.after_request # blueprint can also be app~~
def after_request(response):
    header = response.headers
    header['Access-Control-Allow-Origin'] = '*'
    return response

That is all~~

is there a post render callback for Angular JS directive?

I got this working with the following directive:

app.directive('datatableSetup', function () {
    return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});

And in the HTML:

<table class="table table-hover dataTable dataTable-columnfilter " datatable-setup="">

trouble shooting if the above doesnt work for you.

1) note that 'datatableSetup' is the equivalent of 'datatable-setup'. Angular changes the format into camel case.

2) make sure that app is defined before the directive. e.g. simple app definition and directive.

var app = angular.module('app', []);
app.directive('datatableSetup', function () {
    return { link: function (scope, elm, attrs) { elm.dataTable(); } }
});

hadoop No FileSystem for scheme: file

thanks david_p,scala

conf.set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName);
conf.set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName);

or

<property>
 <name>fs.hdfs.impl</name>
 <value>org.apache.hadoop.hdfs.DistributedFileSystem</value>
</property>

How to install an apk on the emulator in Android Studio?

Run simulator -> drag and drop yourApp.apk into simulator screen. Thats all. No commands.

Calculating number of full months between two dates in SQL

I know this is an old question, but as long as the dates are >= 01-Jan-1753 I use:

DATEDIFF(MONTH, DATEADD(DAY,-DAY(@Start)+1,@Start),DATEADD(DAY,-DAY(@Start)+1,@End))

Pass parameters in setInterval function

Add them as parameters to setInterval:

setInterval(funca, 500, 10, 3);

The syntax in your question uses eval, which is not recommended practice.

What is the correct value for the disabled attribute?

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :

The checked content attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />

Recommendation

If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

Count number of vector values in range with R

There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

sum( 2 %<% x %<% 5 )
sum( 2 %<=% x %<=% 5 )

which gives the same results as:

sum( 2 < x & x < 5 )
sum( 2 <= x & x <= 5 )

Which is better is probably more a matter of personal preference.

How to sort a list of strings numerically?

You could pass a function to the key parameter to the .sort method. With this, the system will sort by key(x) instead of x.

list1.sort(key=int)

BTW, to convert the list to integers permanently, use the map function

list1 = list(map(int, list1))   # you don't need to call list() in Python 2.x

or list comprehension

list1 = [int(x) for x in list1]

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

How can I pass data from Flask to JavaScript in a template?

<script>
    const geocodeArr = JSON.parse('{{ geocode | tojson }}');
    console.log(geocodeArr);
</script>

This uses jinja2 to turn the geocode tuple into a json string, and then the javascript JSON.parse turns that into a javascript array.

What does $(function() {} ); do?

I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:

function example() {
}

A function of that nature can be called at any time, anywhere.

jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:

$(document).ready(function() {
});

So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.

$(document).ready(function() {        
    // Assign all list items on the page to be the  color red.  
    //      This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
    $('li').css('color', 'red');   
});

The pseudo-code for that block is:

When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');

Adding a new line/break tag in XML

The solution to this question is:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="dummy.xsl"?>
  <item>
     <summary>
        <![CDATA[Tootsie roll tiramisu macaroon wafer carrot cake. <br />      
                 Danish topping sugar plum tart bonbon caramels cake.]]>
     </summary>
  </item>

by adding the <br /> inside the the <![CDATA]]> this allows the line to break, thus creating a new line!

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

You must declare the reportfile as variable for console.

Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....

Example: for batch/console

cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile

Exemple Javascript:

var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;

You can change the dir and filename how ever you want.

Frank from Berlin

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

In Perl, how can I read an entire file into a string?

Add:

 local $/;

before reading from the file handle. See How can I read in an entire file all at once?, or

$ perldoc -q "entire file"

See Variables related to filehandles in perldoc perlvar and perldoc -f local.

Incidentally, if you can put your script on the server, you can have all the modules you want. See How do I keep my own module/library directory?.

In addition, Path::Class::File allows you to slurp and spew.

Path::Tiny gives even more convenience methods such as slurp, slurp_raw, slurp_utf8 as well as their spew counterparts.

How do I convert dmesg timestamp to custom date format?

Understanding dmesg timestamp is pretty simple: it is time in seconds since the kernel started. So, having time of startup (uptime), you can add up the seconds and show them in whatever format you like.

Or better, you could use the -T command line option of dmesg and parse the human readable format.

From the man page:

-T, --ctime
    Print human readable timestamps. The timestamp could be inaccurate!

    The time source used for the logs is not updated after system SUSPEND/RESUME.

Is it possible to program Android to act as physical USB keyboard?

Your Android already identifies with a VID/PID when plugged into a host. It already has an interface for Mass Storage. You would need to hack the driver at a low level to support a 2nd interface for 03:01 HID. Then it would just be a question of pushing scancodes to the modified driver. This wouldn't be simple, but it would be a neat hack. One use would be for typing long random passwords for logins.

How can I get onclick event on webview in android?

This works for me

webView.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                // Do what you want
                                return false;
                            }
                        });

Why does ASP.NET webforms need the Runat="Server" attribute?

I've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being runat="server" or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.

This conversation was had on Mike Schinkel's Blog between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):

[...] but the importance of <runat="server"> is more for consistency and extensibility.

If the developer has to mark some tags (viz. <asp: />) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <runat="server"> attribute, this is negated.

It continues:

If <runat=client> was required for all client-side tags, the parser would need to parse all tags and strip out the <runat=client> part.

He continues:

Currently, If my guess is correct, the parser simply ignores all text (tags or no tags) unless it is a tag with the runat=server attribute or a “<%” prefix or ssi “<!– #include(...) Also, since ASP.NET is designed to allow separation of the web designers (foo.aspx) from the web developers (foo.aspx.vb), the web designers can use their own web designer tools to place HTML and client-side JavaScript without having to know about ASP.NET specific tags or attributes.

MongoDB: Server has startup warnings ''Access control is not enabled for the database''

Mongodb v3.4

You need to do the following to create a secure database:

Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).

1) Start MongoDB without access control.

mongod --port 27017 --dbpath /data/db

2) Connect to the instance.

mongo --port 27017

3) Create the user administrator (in the admin authentication database).

use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

4) Re-start the MongoDB instance with access control.

mongod --auth --port 27017 --dbpath /data/db

5) Connect and authenticate as the user administrator.

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

6) Create additional users as needed for your deployment (e.g. in the test authentication database).

use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

7) Connect and authenticate as myTester.

mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/

What is setContentView(R.layout.main)?

In Android the visual design is stored in XML files and each Activity is associated to a design.

setContentView(R.layout.main)

R means Resource

layout means design

main is the xml you have created under res->layout->main.xml

Whenever you want to change the current look of an Activity or when you move from one Activity to another, the new Activity must have a design to show. We call setContentView in onCreate with the desired design as argument.

Coarse-grained vs fine-grained

Corse-grained services provides broader functionalities as compared to fine-grained service. Depending on the business domain, a single service can be created to serve a single business unit or specialised multiple fine-grained services can be created if subunits are largely independent of each other. Coarse grained service may get more difficult may be less adaptable to change due to its size while fine-grained service may introduce additional complexity of managing multiple services.

Removing duplicate objects with Underscore for Javascript

Try iterator function

For example you can return first element

x = [['a',1],['b',2],['a',1]]

_.uniq(x,false,function(i){  

   return i[0]   //'a','b'

})

=> [['a',1],['b',2]]

adding css class to multiple elements

You need to qualify the a part of the selector too:

.button input, .button a {
    //css stuff here
}

Basically, when you use the comma to create a group of selectors, each individual selector is completely independent. There is no relationship between them.

Your original selector therefore matched "all elements of type 'input' that are descendants of an element with the class name 'button', and all elements of type 'a'".

Undefined symbols for architecture i386

At the risk of sounding obvious, always check the spelling of your forward class files. Sometimes XCode (at least XCode 4.3.2) will turn a declaration green that's actually camel cased incorrectly. Like in this example:

"_OBJC_CLASS_$_RadioKit", referenced from:
  objc-class-ref in RadioPlayerViewController.o

If RadioKit was a class file and you make it a property of another file, in the interface declaration, you might see that

Radiokit *rk;

has "Radiokit" in green when the actual decalaration should be:

RadioKit *rk;

This error will also throw this type of error. Another example (in my case), is when you have _iPhone and _iphone extensions on your class names for universal apps. Once I changed the appropriate file from _iphone to the correct _iPhone, the errors went away.

How to add an extra language input to Android?

I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.

Fail to create Android virtual Device, "No system image installed for this Target"

As a workaround, go to sdk installation directory and perform the following steps:

  • Navigate to system-images/android-19/default
  • Move everything in there to system-images/android-19/

The directory structure should look like this: enter image description here

And it should work!

Could not find method compile() for arguments Gradle

compile is a configuration that is usually introduced by a plugin (most likely the java plugin) Have a look at the gradle userguide for details about configurations. For now adding the java plugin on top of your build script should do the trick:

apply plugin:'java'

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

If you need to organize data in columns of 1 / 2 / 4 depending of the viewport size then push and pull may be no option at all. No matter how you order your items in the first place, one of the sizes may give you a wrong order.

A solution in this case is to use nested rows and cols without any push or pull classes.

Example

In XS you want...

A
B
C
D
E
F
G
H

In SM you want...

A   E
B   F
C   G
D   H

In MD and above you want...

A   C   E   G
B   D   F   H


Solution

Use nested two-column child elements in a surrounding two-column parent element:

Here is a working snippet:

_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript" ></script>_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> _x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-sm-6">_x000D_
    <div class="row">_x000D_
      <div class="col-md-6"><p>A</p><p>B</p></div>_x000D_
      <div class="col-md-6"><p>C</p><p>D</p></div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col-sm-6">_x000D_
    <div class="row">_x000D_
      <div class="col-md-6"><p>E</p><p>F</p></div>_x000D_
      <div class="col-md-6"><p>G</p><p>H</p></div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Another beauty of this solution is, that the items appear in the code in their natural order (A, B, C, ... H) and don't have to be shuffled, which is nice for CMS generation.

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

Setting background-image using jQuery CSS property

Don't forget that the jQuery css function allows objects to be passed which allows you to set multiple items at the same time. The answered code would then look like this:

$(this).css({'background-image':'url(' + imageUrl + ')'})

Show hidden div on ng-click within ng-repeat

Remove the display:none, and use ng-show instead:

<ul class="procedures">
    <li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
        <h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="showDetails">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

Here's the fiddle: http://jsfiddle.net/asmKj/


You can also use ng-class to toggle a class:

<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">

I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/

Laravel: Using try...catch with DB::transaction()

If you use PHP7, use Throwable in catch for catching user exceptions and fatal errors.

For example:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

If your code must be compartable with PHP5, use Exception and Throwable:

DB::beginTransaction();

try {
    DB::insert(...);    
    DB::commit();
} catch (\Exception $e) {
    DB::rollback();
    throw $e;
} catch (\Throwable $e) {
    DB::rollback();
    throw $e;
}

Deep-Learning Nan loss reasons

Regularization can help. For a classifier, there is a good case for activity regularization, whether it is binary or a multi-class classifier. For a regressor, kernel regularization might be more appropriate.

Change :hover CSS properties with JavaScript

Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):

HTML:

<button id=Button>Button Title</button>

CSS:

.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}

JavaScript:

var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');

How to open a workbook specifying its path

Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

Or, in a more structured way...

Sub openwb()
    Dim sPath As String, sFile As String
    Dim wb As Workbook

    sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
    sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"

    Set wb = Workbooks.Open(sFile)
End Sub

Mockito - NullpointerException when stubbing Method

For me the reason I was getting NPE is that I was using Mockito.any() when mocking primitives. I found that by switching to using the correct variant from mockito gets rid of the errors.

For example, to mock a function that takes a primitive long as parameter, instead of using any(), you should be more specific and replace that with any(Long.class) or Mockito.anyLong().

Hope that helps someone.

Image inside div has extra space below the image

Another option suggested in this blog post is setting the style of the image as style="display: block;"

Convert MFC CString to integer

Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

int atoi(
   const char *str 
);
int _wtoi(
   const wchar_t *str 
);
int _atoi_l(
   const char *str,
   _locale_t locale
);
int _wtoi_l(
   const wchar_t *str,
   _locale_t locale
);

CString is wchar_t string. So, if you want convert Cstring to int, you can use:

 CString s;  
int test = _wtoi(s)

Allowing Untrusted SSL Certificates with HttpClient

A quick and dirty solution is to use the ServicePointManager.ServerCertificateValidationCallback delegate. This allows you to provide your own certificate validation. The validation is applied globally across the whole App Domain.

ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) => true;

I use this mainly for unit testing in situations where I want to run against an endpoint that I am hosting in process and am trying to hit it with a WCF client or the HttpClient.

For production code you may want more fine grained control and would be better off using the WebRequestHandler and its ServerCertificateValidationCallback delegate property (See dtb's answer below). Or ctacke answer using the HttpClientHandler. I am preferring either of these two now even with my integration tests over how I used to do it unless I cannot find any other hook.

What is the role of the bias in neural networks?

When you use ANNs, you rarely know about the internals of the systems you want to learn. Some things cannot be learned without a bias. E.g., have a look at the following data: (0, 1), (1, 1), (2, 1), basically a function that maps any x to 1.

If you have a one layered network (or a linear mapping), you cannot find a solution. However, if you have a bias it's trivial!

In an ideal setting, a bias could also map all points to the mean of the target points and let the hidden neurons model the differences from that point.

Is there a query language for JSON?

OK, this post is a little old, but... if you want to do SQL-like query in native JSON (or JS objects) on JS objects, take a look at https://github.com/deitch/searchjs

It is both a jsql language written entirely in JSON, and a reference implementation. You can say, "I want to find all object in an array that have name==="John" && age===25 as:

{name:"John",age:25,_join:"AND"}

The reference implementation searchjs works in the browser as well as as a node npm package

npm install searchjs

It can also do things like complex joins and negation (NOT). It natively ignores case.

It doesn't yet do summation or count, but it is probably easier to do those outside.

Static Initialization Blocks

The non-static block:

{
    // Do Something...
}

Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.

Example:

public class Test {

    static{
        System.out.println("Static");
    }

    {
        System.out.println("Non-static block");
    }

    public static void main(String[] args) {
        Test t = new Test();
        Test t2 = new Test();
    }
}

This prints:

Static
Non-static block
Non-static block

Check if number is decimal

If all you need to know is whether a decimal point exists in a variable then this will get the job done...

function containsDecimal( $value ) {
    if ( strpos( $value, "." ) !== false ) {
        return true;
    }
    return false;
}

This isn't a very elegant solution but it works with strings and floats.

Make sure to use !== and not != in the strpos test or you will get incorrect results.

docker unauthorized: authentication required - upon push with successful login

Here the solution for my case ( private repos, free account plan)

https://success.docker.com/Datacenter/Solve/Getting_%22unauthorized%3A_authentication_required%22_when_trying_to_push_image_to_DTR

The image build name to push has to have the same name of the repos.

Example: repos on docker hub is: accountName/resposName image build name "accountName/resposName" -> docker build -t accountName/resposName

then type docker push accountName/resposName:latest

That's all.

How to recursively delete an entire directory with PowerShell 2.0?

There seems to be issues where Remove-Item -Force -Recurse can intermittently fail on Windows because the underlying filesystem is asynchronous. This answer seems to address it. The user has also been actively involved with the Powershell team on GitHub.

Create pandas Dataframe by appending one row at a time

You can also build up a list of lists and convert it to a dataframe -

import pandas as pd

columns = ['i','double','square']
rows = []

for i in range(6):
    row = [i, i*2, i*i]
    rows.append(row)

df = pd.DataFrame(rows, columns=columns)

giving

    i   double  square
0   0   0   0
1   1   2   1
2   2   4   4
3   3   6   9
4   4   8   16
5   5   10  25

How do I detect unsigned integer multiply overflow?

You can't access the overflow flag from C/C++.

Some compilers allow you to insert trap instructions into the code. On GCC the option is -ftrapv.

The only portable and compiler independent thing you can do is to check for overflows on your own. Just like you did in your example.

However, -ftrapv seems to do nothing on x86 using the latest GCC. I guess it's a leftover from an old version or specific to some other architecture. I had expected the compiler to insert an INTO opcode after each addition. Unfortunately it does not do this.

How do I make CMake output into a 'bin' dir?

English is not my native language; please excuse typing errors.

use this line config :
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build/)
place your any CMakeLists.txt project.
this ${PROJECT_SOURCE_DIR} is your current source directory where project place .
and if wander why is ${EXECUTABLE_OUTPUT_PATH}
check this file CMakeCache.txt then search the key word output path,
all the variables define here , it would give a full explanation of the project all setting·

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Is it necessary to write HEAD, BODY and HTML tags?

Contrary to @Liza Daly's note about HTML5, that spec is actually quite specific about which tags can be omitted, and when (and the rules are a bit different from HTML 4.01, mostly to clarify where ambiguous elements like comments and whitespace belong)

The relevant reference is http://www.w3.org/TR/2011/WD-html5-20110525/syntax.html#optional-tags, and it says:

  • An html element's start tag may be omitted if the first thing inside the html element is not a comment.

  • An html element's end tag may be omitted if the html element is not immediately followed by a comment.

  • A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

  • A head element's end tag may be omitted if the head element is not immediately followed by a space character or a comment.

  • A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a script or style element.

  • A body element's end tag may be omitted if the body element is not immediately followed by a comment.

So your example is valid HTML5, and would be parsed like this, with the html, head and body tags in their implied positions:

<!DOCTYPE html><HTML><HEAD>     
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Page Title</title>
    <link rel="stylesheet" type="text/css" href="css/reset.css">
    <script src="js/head_script.js"></script></HEAD><BODY><!-- this script will be in head //-->


<div>Some html</div> <!-- here body starts //-->

    <script src="js/body_script.js"></script></BODY></HTML>

Note that the comment "this script will be in head" is actually parsed as part of the body, although the script itself is part of the head. According to the spec, if you want that to be different at all, then the </HEAD> and <BODY> tags may not be omitted. (Although the corresponding <HEAD> and </BODY> tags still can be)

Current timestamp as filename in Java

try this one

String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

How to open a web page automatically in full screen mode

view full size page large (function () { var viewFullScreen = document.getElementById("view-fullscreen"); if (viewFullScreen) { viewFullScreen.addEventListener("click", function () { var docElm = document.documentElement; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } }, false); } })();

_x000D_
_x000D_
<div class="container">      _x000D_
            <section class="main-content">_x000D_
                                    <center><a href="#"><button id="view-fullscreen">view full size page large</button></a><center>_x000D_
                                           <script>(function () {_x000D_
    var viewFullScreen = document.getElementById("view-fullscreen");_x000D_
    if (viewFullScreen) {_x000D_
        viewFullScreen.addEventListener("click", function () {_x000D_
            var docElm = document.documentElement;_x000D_
            if (docElm.requestFullscreen) {_x000D_
                docElm.requestFullscreen();_x000D_
            }_x000D_
            else if (docElm.mozRequestFullScreen) {_x000D_
                docElm.mozRequestFullScreen();_x000D_
            }_x000D_
            else if (docElm.webkitRequestFullScreen) {_x000D_
                docElm.webkitRequestFullScreen();_x000D_
            }_x000D_
        }, false);_x000D_
    }_x000D_
    })();</script>_x000D_
                                           </section>_x000D_
</div>
_x000D_
_x000D_
_x000D_

for view demo clcik here demo of click to open page in fullscreen

How to unstage large number of files without deleting the content

2019 update

As pointed out by others in related questions (see here, here, here, here, here, here, and here), you can now unstage a file with git restore --staged <file>.

To unstage all the files in your project, run the following from the root of the repository (the command is recursive):

git restore --staged .

If you only want to unstage the files in a directory, navigate to it before running the above or run:

git restore --staged <directory-path>

Notes

  • git restore was introduced in July 2019 and released in version 2.23.
    With the --staged flag, it restores the content of the working tree from HEAD (so it does the opposite of git add and does not delete any change).

  • This is a new command, but the behaviour of the old commands remains unchanged. So the older answers with git reset or git reset HEAD are still perfectly valid.

  • When running git status with staged uncommitted file(s), this is now what Git suggests to use to unstage file(s) (instead of git reset HEAD <file> as it used to prior to v2.23).

RESTful Authentication

The 'very insightful' article mentioned by @skrebel ( http://www.berenddeboer.net/rest/authentication.html ) discusses a convoluted but really broken method of authentication.

You may try to visit the page (which is supposed to be viewable only to authenticated user) http://www.berenddeboer.net/rest/site/authenticated.html without any login credentials.

(Sorry I can't comment on the answer.)

I would say REST and authentication simply do not mix. REST means stateless but 'authenticated' is a state. You cannot have them both at the same layer. If you are a RESTful advocate and frown upon states, then you have to go with HTTPS (i.e. leave the security issue to another layer).

How To Use DateTimePicker In WPF?

For the controls embedded in WPF Extended WPF Toolkit Release 1.4.0, please refer http://elegantcode.com/2011/04/08/extended-wpf-toolkit-release-1-4-0/

For Calendar & DatePicker Walkthrough please refer, http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx

And you can cutomize the look and feel by Microsoft Expression Studio [Use Edit Template option] Sample shows here:

Add following namespaces to xaml page

xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit.Extended"
xmlns:Microsoft_Windows_Controls_Core_Converters="clr-namespace:Microsoft.Windows.Controls.Core.Converters;assembly=WPFToolkit.Extended" 
xmlns:Microsoft_Windows_Controls_Chromes="clr-namespace:Microsoft.Windows.Controls.Chromes;assembly=WPFToolkit.Extended"

Add followings to Page/Window resources

<!--DateTimePicker Customized Style-->
        <Style x:Key="DateTimePickerStyle1" TargetType="{x:Type toolkit:DateTimePicker}">
            <Setter Property="TimeWatermarkTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="WatermarkTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type toolkit:DateTimePicker}">
                        <Border>
                            <Grid>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="Auto"/>
                                    </Grid.ColumnDefinitions>

                                    <toolkit:DateTimeUpDown AllowSpin="{TemplateBinding AllowSpin}" 
                                                                  BorderThickness="1,1,0,1" 
                                                                  FormatString="{TemplateBinding FormatString}" 
                                                                  Format="{TemplateBinding Format}" 
                                                                  ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}" 
                                                                  Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}" 
                                                                  WatermarkTemplate="{TemplateBinding WatermarkTemplate}" 
                                                                  Watermark="{TemplateBinding Watermark}" 
                                                                  Foreground="#FFEFE3E3" 
                                                                  BorderBrush="#FFEBB31A">
                                        <toolkit:DateTimeUpDown.Background>
                                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                                <GradientStop Color="Black" Offset="0"/>
                                                <GradientStop Color="#FF2F2828" Offset="1"/>
                                            </LinearGradientBrush>
                                        </toolkit:DateTimeUpDown.Background>
                                    </toolkit:DateTimeUpDown>

                                    <ToggleButton x:Name="_calendarToggleButton" 
                                                  Background="{x:Null}" Grid.Column="1" IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}">
                                        <ToggleButton.IsHitTestVisible>
                                            <Binding Path="IsOpen" RelativeSource="{RelativeSource TemplatedParent}">
                                                <Binding.Converter>
                                                    <Microsoft_Windows_Controls_Core_Converters:InverseBoolConverter/>
                                                </Binding.Converter>
                                            </Binding>
                                        </ToggleButton.IsHitTestVisible>
                                        <ToggleButton.Style>
                                            <Style TargetType="{x:Type ToggleButton}">
                                                <Setter Property="Template">
                                                    <Setter.Value>
                                                        <ControlTemplate TargetType="{x:Type ToggleButton}">
                                                            <Grid SnapsToDevicePixels="True">
                                                                <Microsoft_Windows_Controls_Chromes:ButtonChrome x:Name="ToggleButtonChrome" CornerRadius="0,2.75,2.75,0" InnerCornerRadius="0,1.75,1.75,0" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" BorderBrush="{x:Null}">
                                                                    <Microsoft_Windows_Controls_Chromes:ButtonChrome.Background>
                                                                        <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
                                                                            <GradientStop Color="#FFF3F3F3" Offset="1"/>
                                                                            <GradientStop Color="#7FC0A112"/>
                                                                        </LinearGradientBrush>
                                                                    </Microsoft_Windows_Controls_Chromes:ButtonChrome.Background>
                                                                </Microsoft_Windows_Controls_Chromes:ButtonChrome>
                                                                <Grid>
                                                                    <Grid.ColumnDefinitions>
                                                                        <ColumnDefinition Width="*"/>
                                                                        <ColumnDefinition Width="Auto"/>
                                                                    </Grid.ColumnDefinitions>
                                                                    <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Stretch" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Stretch"/>
                                                                    <Grid x:Name="arrowGlyph" Grid.Column="1" IsHitTestVisible="False" Margin="5">
                                                                        <Path Data="M0,1C0,1 0,0 0,0 0,0 3,0 3,0 3,0 3,1 3,1 3,1 4,1 4,1 4,1 4,0 4,0 4,0 7,0 7,0 7,0 7,1 7,1 7,1 6,1 6,1 6,1 6,2 6,2 6,2 5,2 5,2 5,2 5,3 5,3 5,3 4,3 4,3 4,3 4,4 4,4 4,4 3,4 3,4 3,4 3,3 3,3 3,3 2,3 2,3 2,3 2,2 2,2 2,2 1,2 1,2 1,2 1,1 1,1 1,1 0,1 0,1z" Fill="#FF82E511" Height="4" Width="7"/>
                                                                    </Grid>
                                                                </Grid>
                                                            </Grid>
                                                        </ControlTemplate>
                                                    </Setter.Value>
                                                </Setter>
                                            </Style>
                                        </ToggleButton.Style>
                                    </ToggleButton>
                                </Grid>

                                <Popup IsOpen="{Binding IsChecked, ElementName=_calendarToggleButton}" StaysOpen="False">
                                    <Border BorderThickness="1" Padding="3">
                                        <Border.BorderBrush>
                                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                                <GradientStop Color="#FFA3AEB9" Offset="0"/>
                                                <GradientStop Color="#FF8399A9" Offset="0.375"/>
                                                <GradientStop Color="#FF718597" Offset="0.375"/>
                                                <GradientStop Color="#FFD2C217" Offset="1"/>
                                            </LinearGradientBrush>
                                        </Border.BorderBrush>
                                        <Border.Background>
                                            <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                                <GradientStop Color="White" Offset="0"/>
                                                <GradientStop Color="#FFE9B116" Offset="1"/>
                                            </LinearGradientBrush>
                                        </Border.Background>
                                        <StackPanel Background="{x:Null}">
                                            <Calendar x:Name="Part_Calendar" BorderThickness="0" DisplayDate="2011-06-28" Background="#7FE0B41A"/>
                                            <toolkit:TimePicker x:Name="Part_TimeUpDown" Format="ShortTime" Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}" WatermarkTemplate="{TemplateBinding TimeWatermarkTemplate}" Watermark="{TemplateBinding TimeWatermark}" Background="{x:Null}" Style="{DynamicResource TimePickerStyle1}"/>
                                        </StackPanel>
                                    </Border>
                                </Popup>
                            </Grid>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="TimePickerStyle1" 
               TargetType="{x:Type toolkit:TimePicker}">
            <Setter Property="WatermarkTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type toolkit:TimePicker}">
                        <Border>
                            <Grid>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="Auto"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid>
                                        <toolkit:DateTimeUpDown x:Name="PART_TimeUpDown" AllowSpin="{TemplateBinding AllowSpin}" BorderThickness="1,1,0,1" FormatString="{TemplateBinding FormatString}" ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}" Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}" WatermarkTemplate="{TemplateBinding WatermarkTemplate}" Watermark="{TemplateBinding Watermark}" Background="#7FE0B41A" BorderBrush="#FFF9F2F2">
                                            <toolkit:DateTimeUpDown.Format>
                                                <TemplateBinding Property="Format">
                                                    <TemplateBinding.Converter>
                                                        <Microsoft_Windows_Controls_Core_Converters:TimeFormatToDateTimeFormatConverter/>
                                                    </TemplateBinding.Converter>
                                                </TemplateBinding>
                                            </toolkit:DateTimeUpDown.Format>
                                        </toolkit:DateTimeUpDown>
                                    </Grid>
                                    <ToggleButton x:Name="_timePickerToggleButton" Grid.Column="1" IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}" >
                                        <ToggleButton.IsHitTestVisible>
                                            <Binding Path="IsOpen" RelativeSource="{RelativeSource TemplatedParent}">
                                                <Binding.Converter>
                                                    <Microsoft_Windows_Controls_Core_Converters:InverseBoolConverter/>
                                                </Binding.Converter>
                                            </Binding>
                                        </ToggleButton.IsHitTestVisible>
                                        <ToggleButton.Style>
                                            <Style TargetType="{x:Type ToggleButton}">
                                                <Setter Property="Template">
                                                    <Setter.Value>
                                                        <ControlTemplate TargetType="{x:Type ToggleButton}">
                                                            <Grid SnapsToDevicePixels="True">
                                                                <Microsoft_Windows_Controls_Chromes:ButtonChrome x:Name="ToggleButtonChrome" CornerRadius="0,2.75,2.75,0" InnerCornerRadius="0,1.75,1.75,0" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/>
                                                                <Grid>
                                                                    <Grid.ColumnDefinitions>
                                                                        <ColumnDefinition Width="*"/>
                                                                        <ColumnDefinition Width="Auto"/>
                                                                    </Grid.ColumnDefinitions>
                                                                    <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Stretch" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Stretch"/>
                                                                    <Grid x:Name="arrowGlyph" Grid.Column="1" IsHitTestVisible="False" Margin="5">
                                                                        <Path Data="M0,1C0,1 0,0 0,0 0,0 3,0 3,0 3,0 3,1 3,1 3,1 4,1 4,1 4,1 4,0 4,0 4,0 7,0 7,0 7,0 7,1 7,1 7,1 6,1 6,1 6,1 6,2 6,2 6,2 5,2 5,2 5,2 5,3 5,3 5,3 4,3 4,3 4,3 4,4 4,4 4,4 3,4 3,4 3,4 3,3 3,3 3,3 2,3 2,3 2,3 2,2 2,2 2,2 1,2 1,2 1,2 1,1 1,1 1,1 0,1 0,1z" Fill="Black" Height="4" Width="7"/>
                                                                    </Grid>
                                                                </Grid>
                                                            </Grid>
                                                        </ControlTemplate>
                                                    </Setter.Value>
                                                </Setter>
                                            </Style>
                                        </ToggleButton.Style>
                                    </ToggleButton>
                                </Grid>

                                <Popup IsOpen="{Binding IsChecked, ElementName=_timePickerToggleButton}" StaysOpen="False">
                                    <Border BorderThickness="1">
                                        <Border.Background>
                                            <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                                                <GradientStop Color="White" Offset="0"/>
                                                <GradientStop Color="#FFE7C857" Offset="1"/>
                                            </LinearGradientBrush>
                                        </Border.Background>
                                        <Border.BorderBrush>
                                            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                                <GradientStop Color="#FFA3AEB9" Offset="0"/>
                                                <GradientStop Color="#FF8399A9" Offset="0.375"/>
                                                <GradientStop Color="#FF718597" Offset="0.375"/>
                                                <GradientStop Color="#FF617584" Offset="1"/>
                                            </LinearGradientBrush>
                                        </Border.BorderBrush>

                                        <Grid>
                                            <ListBox x:Name="PART_TimeListItems" BorderThickness="0" DisplayMemberPath="Display" Height="130" Width="150" Background="#7FE0B41A">
                                                <ListBox.ItemContainerStyle>
                                                    <Style TargetType="{x:Type ListBoxItem}">
                                                        <Setter Property="Template">
                                                            <Setter.Value>
                                                                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                                                                    <Border x:Name="Border" SnapsToDevicePixels="True">
                                                                        <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Margin="4"/>
                                                                    </Border>
                                                                    <ControlTemplate.Triggers>
                                                                        <Trigger Property="IsMouseOver" Value="True">
                                                                            <Setter Property="Background" TargetName="Border" Value="#FFE7F5FD"/>
                                                                        </Trigger>
                                                                        <Trigger Property="IsSelected" Value="True">
                                                                            <Setter Property="Background" TargetName="Border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                                                                            <Setter Property="Foreground" Value="White"/>
                                                                        </Trigger>
                                                                    </ControlTemplate.Triggers>
                                                                </ControlTemplate>
                                                            </Setter.Value>
                                                        </Setter>
                                                    </Style>
                                                </ListBox.ItemContainerStyle>
                                            </ListBox>
                                        </Grid>
                                    </Border>
                                </Popup>
                            </Grid>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

And in Window you can use the style as

Thanks,

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

Change Timezone in Lumen or Laravel 5

There are two ways to update your code. 1. Please open the file app.php file present in config directory at lool of your project. Go down the page and check Application Timezone where you will find

'timezone' => 'UTC',

Here you can add your timezone like

'timezone' => 'Europe/Paris',

If you want to manage your timezone from .env file, then you can add below code in your config.php file.

'timezone' => env('APP_TIMEZONE', 'UTC'),

and add the below line in your .env file.

APP_TIMEZONE='Europe/Paris'

Please check the link below for more information: https://laravel.com/docs/5.6/configuration#accessing-configuration-values

How do I return the SQL data types from my query?

Checking data types. The first way to check data types for SQL Server database is a query with the SYS schema table. The below query uses COLUMNS and TYPES tables:

    SELECT C.NAME AS COLUMN_NAME,
       TYPE_NAME(C.USER_TYPE_ID) AS DATA_TYPE,
       C.IS_NULLABLE,
       C.MAX_LENGTH,
       C.PRECISION,
       C.SCALE
FROM SYS.COLUMNS C
JOIN SYS.TYPES T
     ON C.USER_TYPE_ID=T.USER_TYPE_ID
WHERE C.OBJECT_ID=OBJECT_ID('your_table_name');

In this way, you can find data types of columns.

Relative path to absolute path in C#?

You can use Path.Combine with the "base" path, then GetFullPath on the results.

string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, @"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath);  // Will turn the above into a proper abs path

java.lang.IllegalArgumentException: No converter found for return value of type

In my case i'm using spring boot , and i have encountered a similar error :

No converter for [class java.util.ArrayList] with preset Content-Type 'null'

turns out that i have a controller with

@GetMapping(produces = { "application/xml", "application/json" })

and shamefully i wasn't adding the Accept header to my requests

Check if a string has white space

Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/" characters are sufficient.

/^\s+$/ is checking whether the string is ALL whitespace:

  • ^ matches the start of the string.
  • \s+ means at least 1, possibly more, spaces.
  • $ matches the end of the string.

Try replacing the regex with /\s/ (and no quotes)

Right align text in android TextView

try to add android:gravity="center" into TextView

Getting the parameters of a running JVM

On linux, you can run this command and see the result :

ps aux | grep "java"

android.content.res.Resources$NotFoundException: String resource ID #0x0

Change

dateTime.setText(app.getTotalDl());

To

dateTime.setText(String.valueOf(app.getTotalDl()));

There are different versions of setText - one takes a String and one takes an int resource id. If you pass it an integer it will try to look for the corresponding string resource id - which it can't find, which is your error.

I guess app.getTotalDl() returns an int. You need to specifically tell setText to set it to the String value of this int.

setText (int resid) vs setText (CharSequence text)

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

Why are my PowerShell scripts not running?

Use:

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

Always use the above command to enable to executing PowerShell in the current session.

$(form).ajaxSubmit is not a function

Drupal 8

Drupal 8 does not include JS-libraries to pages automaticly. So most probably if you meet this error you need to attach 'core/jquery.form' library to your page (or form). Add something like this to your render array:

$form['#attached']['library'][] = 'core/jquery.form';

How to set delay in android?

You can use CountDownTimer which is much more efficient than any other solution posted. You can also produce regular notifications on intervals along the way using its onTick(long) method

Have a look at this example showing a 30seconds countdown

   new CountDownTimer(30000, 1000) {
         public void onFinish() {
             // When timer is finished 
             // Execute your code here
     }

     public void onTick(long millisUntilFinished) {
              // millisUntilFinished    The amount of time until finished.
     }
   }.start();

Can't start hostednetwork

Some fixes I've used for this problem:

  1. Check if the connection you want to share is shareable.

    a. Press Win-key + r and run ncpa.cpl

    b. Right click on the connection you want to share and go to properties

    c. Go to sharing tab and check if sharing is enabled

  2. Run devmgmt.msc from the run console.

    a. Expand the network adapters list

    b. Right click -> properties on the adapter of the connection you want to share

    c. Go to power management tab and enable allow this computer to turn off this device to save power. Restart your laptop if you've made changes.

  3. Check if airplane mode is disabled. You can enable airplane mode and then turn on the wi-fi, you can never know. Do disable airplane mode if it is on.

  4. Use admin command prompt to run this command.

SQL Developer with JDK (64 bit) cannot find JVM

I was trying to use the sqldeveloper that comes with the Oracle installation under:

C:\oracle\product\11.2.0\dbhome_1\sqldeveloper

I tried most of the suggestions in this post to no avail, so I downloaded the one from oracle's download page (you must register) which asks for the location of the jdk folder (rather than the location of java.exe). This worked for me without any problems.

C# - using List<T>.Find() with custom objects

Find() will find the element that matches the predicate that you pass as a parameter, so it is not related to Equals() or the == operator.

var element = myList.Find(e => [some condition on e]);

In this case, I have used a lambda expression as a predicate. You might want to read on this. In the case of Find(), your expression should take an element and return a bool.

In your case, that would be:

var reponse = list.Find(r => r.Statement == "statement1")

And to answer the question in the comments, this is the equivalent in .NET 2.0, before lambda expressions were introduced:

var response = list.Find(delegate (Response r) {
    return r.Statement == "statement1";
});

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

PowerShell array initialization

Or try this an idea. Works with powershell 5.0+.

[bool[]]$tf=((,$False)*5)

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

    Windows PowerShell
    Copyright (C) 2014 Microsoft Corporation. All rights reserved.

    PS C:\Windows\system32> **$dte = Get-Date**
    PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
    PS C:\Windows\system32> **$PastDueDate**

    Sunday, March 1, 2020 12:00:00 AM

   PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
   PS C:\Windows\system32> **$NewDateFormat 03012020**

There're few additional methods available as well e.g.: $dte.AddDays(-45).Day

How to get a Static property with Reflection

A little clarity...

// Get a PropertyInfo of specific property type(T).GetProperty(....)
PropertyInfo propertyInfo;
propertyInfo = typeof(TypeWithTheStaticProperty)
    .GetProperty("NameOfStaticProperty", BindingFlags.Public | BindingFlags.Static); 

// Use the PropertyInfo to retrieve the value from the type by not passing in an instance
object value = propertyInfo.GetValue(null, null);

// Cast the value to the desired type
ExpectedType typedValue = (ExpectedType) value;

Populate a Drop down box from a mySQL table in PHP

At the top first set up database connection as follow:

<?php
$mysqli = new mysqli("localhost", "username", "password", "database") or die($this->mysqli->error);
$query= $mysqli->query("SELECT PcID from PC");
?> 

Then include the following code in HTML inside form

<select name="selected_pcid" id='selected_pcid'>

            <?php 

             while ($rows = $query->fetch_array(MYSQLI_ASSOC)) {
                        $value= $rows['id'];
                ?>
                 <option value="<?= $value?>"><?= $value?></option>
                <?php } ?>
             </select>

However, if you are using materialize css or any other out of the box css, make sure that select field is not hidden or disabled.

Anchor links in Angularjs?

If you are using SharePoint and angular then do it like below:

<a ng-href="{{item.LinkTo.Url}}" target="_blank" ng-bind="item.Title;" ></a> 

where LinkTo and Title is SharePoint Column.

Mutex example / tutorial?

For those looking for the shortex mutex example:

#include <mutex>

int main() {
    std::mutex m;

    m.lock();
    // do thread-safe stuff
    m.unlock();
}

Add item to array in VBScript

Based on Charles Clayton's answer, but slightly simplified...

' add item to array
Sub ArrayAdd(arr, val)
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = val
End Sub

Used like so

a = Array()
AddItem(a, 5)
AddItem(a, "foo")

Java command not found on Linux

I found the best way for me was to download unzip then symlink your new usr/java/jre-version/bin/java to your main bin as java.

jquery, domain, get URL

jQuery is not needed, use simple javascript:

document.domain

horizontal line and right way to code it in html, css

it is depends on requirement , but many developers suggestions is to make your code as simple as possible . so, go with simple "hr" tag and CSS code for that.

How to write log to file

The default logger in Go writes to stderr (2). redirect to file

import ( 
    "syscall"
    "os" 
 )
func main(){
  fErr, err = os.OpenFile("Errfile", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
  syscall.Dup2(int(fErr.Fd()), 1) /* -- stdout */
  syscall.Dup2(int(fErr.Fd()), 2) /* -- stderr */

}

Multiprocessing vs Threading Python

As I learnd in university most of the answers above are right. In PRACTISE on different platforms (always using python) spawning multiple threads ends up like spawning one process. The difference is the multiple cores share the load instead of only 1 core processing everything at 100%. So if you spawn for example 10 threads on a 4 core pc, you will end up getting only the 25% of the cpus power!! And if u spawn 10 processes u will end up with the cpu processing at 100% (if u dont have other limitations). Im not a expert in all the new technologies. Im answering with own real experience background

jQuery replace one class with another

You can use .removeClass and .addClass. More in http://api.jquery.com.

Psql list all tables

To see the public tables you can do

list tables

\dt

list table, view, and access privileges

\dp or \z

or just the table names

select table_name from information_schema.tables where table_schema = 'public';

Excel VBA code to copy a specific string to clipboard

To write text to (or read text from) the Windows clipboard use this VBA function:

Function Clipboard$(Optional s$)
    Dim v: v = s  'Cast to variant for 64-bit VBA support
    With CreateObject("htmlfile")
    With .parentWindow.clipboardData
        Select Case True
            Case Len(s): .setData "text", v
            Case Else:   Clipboard = .getData("text")
        End Select
    End With
    End With
End Function

'Three examples of copying text to the clipboard:
Clipboard "Excel Hero was here."
Clipboard var1 & vbLF & var2
Clipboard 123

'To read text from the clipboard:
MsgBox Clipboard

This is a solution that does NOT use MS Forms nor the Win32 API. Instead it uses the Microsoft HTML Object Library which is fast and ubiquitous and NOT deprecated by Microsoft like MS Forms. And this solution respects line feeds. This solution also works from 64-bit Office. Finally, this solution allows both writing to and reading from the Windows clipboard. No other solution on this page has these benefits.

How do you reinstall an app's dependencies using npm?

You can do this with one simple command:

npm ci

Documentation:

npm ci
Install a project with a clean slate

JavaScript alert box with timer

May be it's too late but the following code works fine

document.getElementById('alrt').innerHTML='<b>Please wait, Your download will start soon!!!</b>'; 
setTimeout(function() {document.getElementById('alrt').innerHTML='';},5000);

<div id='alrt' style="fontWeight = 'bold'"></div>

What's the difference between SortedList and SortedDictionary?

Here is a tabular view if it helps...

From a performance perspective:

+------------------+---------+----------+--------+----------+----------+---------+
| Collection       | Indexed | Keyed    | Value  | Addition |  Removal | Memory  |
|                  | lookup  | lookup   | lookup |          |          |         |
+------------------+---------+----------+--------+----------+----------+---------+
| SortedList       | O(1)    | O(log n) | O(n)   | O(n)*    | O(n)     | Lesser  |
| SortedDictionary | O(n)**  | O(log n) | O(n)   | O(log n) | O(log n) | Greater |
+------------------+---------+----------+--------+----------+----------+---------+

  * Insertion is O(log n) for data that are already in sort order, so that each 
    element is added to the end of the list. If a resize is required, that element
    takes O(n) time, but inserting n elements is still amortized O(n log n).
    list.
** Available through enumeration, e.g. Enumerable.ElementAt.

From an implementation perspective:

+------------+---------------+----------+------------+------------+------------------+
| Underlying | Lookup        | Ordering | Contiguous | Data       | Exposes Key &    |
| structure  | strategy      |          | storage    | access     | Value collection |
+------------+---------------+----------+------------+------------+------------------+
| 2 arrays   | Binary search | Sorted   | Yes        | Key, Index | Yes              |
| BST        | Binary search | Sorted   | No         | Key        | Yes              |
+------------+---------------+----------+------------+------------+------------------+

To roughly paraphrase, if you require raw performance SortedDictionary could be a better choice. If you require lesser memory overhead and indexed retrieval SortedList fits better. See this question for more on when to use which.

You can read more here, here, here, here and here.

How to change button background image on mouseOver?

In the case of winforms:

If you include the images to your resources you can do it like this, very simple and straight forward:

public Form1()
          {
               InitializeComponent();
               button1.MouseEnter += new EventHandler(button1_MouseEnter);
               button1.MouseLeave += new EventHandler(button1_MouseLeave);
          }

          void button1_MouseLeave(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
          }


          void button1_MouseEnter(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

I would not recommend hardcoding image paths.

As you have altered your question ...

There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :

in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover); 
button1.MouseMove += new MouseEventHandler(button1_MouseMove);

void button1_MouseMove(object sender, MouseEventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

          void button1_MouseHover(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

To add images to your resources: Projectproperties/resources/add/existing file

SSL Connection / Connection Reset with IISExpress

In my case, the localhost url was redirected to https://localhost when I was debugging. This happened from one moment to other, without changing anything. I solved this by making a hard reload to the browser. Here the link

mat-form-field must contain a MatFormFieldControl

Unfortunately I can't just comment on some already good answers as I don't have the SO points yet, however, there are 3 key modules that you'll need to make sure you are importing into your component's parent module, aside from what you have to import into your component directly. I wanted to briefly share them and highlight what they do.

  1. MatInputModule
  2. MatFormFieldModule
  3. ReactiveFormsModule

The first two are for Angular Material. A lot of people new to Angular Material will instinctively come across one of these and not realize that building a form requires both.

So what's the difference between them?

MatFormFieldModule encompasses all the different types of form fields that Angular Material has available. This is more of a high level module for form fields in general, whereas the MatInputModule is specifically for 'input' field types, as opposed to select boxes, radio buttons, etc.

The third item on the above list is Angular's Reactive Forms Module. The Reactive Forms Module is responsible for a ton of under-the-hood Angular love. If you are going to work with Angular, I highly recommend that you spend some time reading Angular Docs. They have all of your answers. Building applications rarely DOESN'T involve forms, and more often than not, your application will involve reactive forms. For that reason, please take the time to read these two pages.

Angular Docs: Reactive Forms

Angular Docs: Reactive Forms Module

The first doc 'Reactive Forms' will be your most powerful weapon as you get started, and the second doc will be your most power weapon as you get on to more advanced applications of Angular Reactive Forms.

Remember, these need to be imported directly into your component's module, not the component you are using them in. If I remember correctly, in Angular 2, we imported the entire set of Angular Material modules in our main app module, and then imported what we needed in each of our components directly. The current method is much more efficient IMO because we are guaranteed to import the entire set of Angular Material modules if we only use a few of them.

I hope this provides a bit more insight into building forms with Angular Material.

Determine the type of an object?

be careful using isinstance

isinstance(True, bool)
True
>>> isinstance(True, int)
True

but type

type(True) == bool
True
>>> type(True) == int
False

How to convert an array to object in PHP?

I would definitly go with a clean way like this :

<?php

class Person {

  private $name;
  private $age;
  private $sexe;

  function __construct ($payload)
  {
     if (is_array($payload))
          $this->from_array($payload);
  }


  public function from_array($array)
  {
     foreach(get_object_vars($this) as $attrName => $attrValue)
        $this->{$attrName} = $array[$attrName];
  }

  public function say_hi ()
  {
     print "hi my name is {$this->name}";
  }
}

print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();

?>

if you submit:

formulaire

you will get this:

mike

I found this more logical comparing the above answers from Objects should be used for the purpose they've been made for (encapsulated cute little objects).

Also using get_object_vars ensure that no extra attributes are created in the manipulated Object (you don't want a car having a family name, nor a person behaving 4 wheels).

How to add items to a spinner in Android?

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

SVN 405 Method Not Allowed

My guess is that the folder you are trying to add already exists in SVN. You can confirm by checking out the files to a different folder and see if trunk already has the required folder.

How can I wrap or break long text/word in a fixed width span?

In my case, display: block was breaking the design as intended.

The max-width property just saved me.

and for styling, you can use text-overflow: ellipsis as well.

my code was

max-width: 255px
overflow:hidden

Select current element in jQuery

I think by combining .children() with $(this) will return the children of the selected item only

consider the following:

$("div li").click(function() {
$(this).children().css('background','red');
});

this will change the background of the clicked li only

cannot resolve symbol javafx.application in IntelliJ Idea IDE

Sample Java application:

I'm crossposting my answer from another question here since it is related and also seems to solve the problem in the question.

Here is my example project with OpenJDK 12, JavaFX 12 and Gradle 5.4

  • Opens a JavaFX window with the title "Hello World!"
  • Able to build a working runnable distribution zip file (Windows to be tested)
  • Able to open and run in IntelliJ without additional configuration
  • Able to run from the command line

I hope somebody finds the Github project useful.

Instructions for the Scala case:

Additionally below are instructions that work with the Gradle Scala plugin, but don't seem work with Java. I'm leaving this here in case somebody else is also using Scala, Gradle and JavaFX.

1) As mentioned in the question, the JavaFX Gradle plugin needs to be set up. Open JavaFX has detailed documentation on this

2) Additionally you need the the JavaFX SDK for your platform unzipped somewhere. NOTE: Be sure to scroll down to Latest releases section where JavaFX 12 is (LTS 11 is first for some reason.)

3) Then, in IntelliJ you go to the File -> Project Structure -> Libraries, hit the ?-button and add the lib folder from the unzipped JavaFX SDK.

For longer instructions with screenshots, check out the excellent Open JavaFX docs for IntelliJ I can't get a deep link working, so select JavaFX and IntelliJ and then Modular from IDE from the docs nav. Then scroll down to step 3. Create a library. Consider checking the other steps too if you are having trouble.

It is difficult to say if this is exactly the same situation as in the original question, but it looked similar enough that I landed here, so I'm adding my experience here to help others.

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

Calling Python in Java?

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

see here how to use Python interpreter in Java.

Running Java Program from Command Line Linux

What is the package name of your class? If there is no package name, then most likely the solution is:

java -cp FileManagement Main

How can I profile C++ code running on Linux?

You can use a logging framework like loguru since it includes timestamps and total uptime which can be used nicely for profiling:

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

To reiterate a prior solution and to stress the pure CSS implementation here is my answer.

A Pure CSS solution is needed in cases where you are sourcing content from another site, and thus you have no control over the HTML that is delivered. In my case I am trying to remove branding of licensed source content so that the licencee does not have to advertise for the company they are buying the content from. Therefore, I'm removing their logo while keeping everything else. I should note that this is within my client's contract to do so.

{ /* image size is 204x30 */
     width:0;
     height:0;
     padding-left:102px;
     padding-right:102px;
     padding-top:15px;
     padding-bottom:15px;
     background-image:url(http://sthstest/Style%20Library/StThomas/images/rhn_nav_logo2.gif);
}

How do I print colored output with Python 3?

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def colour_print(text,colour):
    if colour == 'OKBLUE':
        string = bcolors.OKBLUE + text + bcolors.ENDC
        print(string)
    elif colour == 'HEADER':
        string = bcolors.HEADER + text + bcolors.ENDC
        print(string)
    elif colour == 'OKCYAN':
        string = bcolors.OKCYAN + text + bcolors.ENDC
        print(string)
    elif colour == 'OKGREEN':
        string = bcolors.OKGREEN + text + bcolors.ENDC
        print(string)
    elif colour == 'WARNING':
        string = bcolors.WARNING + text + bcolors.ENDC
        print(string)
    elif colour == 'FAIL':
        string = bcolors.HEADER + text + bcolors.ENDC
        print(string)
    elif colour == 'BOLD':
        string = bcolors.BOLD + text + bcolors.ENDC
        print(string)
    elif colour == 'UNDERLINE':
        string = bcolors.UNDERLINE + text + bcolors.ENDC
        print(string)

just copy the above code. just call them easily

colour_print('Hello world','OKBLUE')
colour_print('easy one','OKCYAN')
colour_print('copy and paste','OKGREEN')
colour_print('done','OKBLUE')

Hope it would help

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

It's because the virtual environment viarable has not been installed.

Try this:

sudo pip install virtualenv
virtualenv --python python3 env
source env/bin/activate
pip install <Package>

or

sudo pip3 install virtualenv
virtualenv --python python3 env
source env/bin/activate
pip3 install <Package>

How can I add comments in MySQL?

Several ways:

# Comment
-- Comment
/* Comment */

Remember to put the space after --.

See the documentation.

What is the iPad user agent?

It's worth noting that when running in web-app mode (using the apple-mobile-web-app-capable meta tag) the user agent changes from:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B405 Safari/531.21.10

to:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405

dynamically set iframe src

You should also consider that in some Opera versions onload is fired several times and add some hooks:

// fixing Opera 9.26, 10.00
if (doc.readyState && doc.readyState != 'complete') {
    // Opera fires load event multiple times
    // Even when the DOM is not ready yet
    // this fix should not affect other browsers
    return;
}

// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
    // In Opera 9.64 event was fired second time
    // when body.innerHTML changed from false
    // to server response approx. after 1 sec
    return;
}

Code borrowed from Ajax Upload

Difference Between One-to-Many, Many-to-One and Many-to-Many?

Take a look at this article: Mapping Object Relationships

There are two categories of object relationships that you need to be concerned with when mapping. The first category is based on multiplicity and it includes three types:

*One-to-one relationships.  This is a relationship where the maximums of each of its multiplicities is one, an example of which is holds relationship between Employee and Position in Figure 11.  An employee holds one and only one position and a position may be held by one employee (some positions go unfilled).
*One-to-many relationships. Also known as a many-to-one relationship, this occurs when the maximum of one multiplicity is one and the other is greater than one.  An example is the works in relationship between Employee and Division.  An employee works in one division and any given division has one or more employees working in it.
*Many-to-many relationships. This is a relationship where the maximum of both multiplicities is greater than one, an example of which is the assigned relationship between Employee and Task.  An employee is assigned one or more tasks and each task is assigned to zero or more employees. 

The second category is based on directionality and it contains two types, uni-directional relationships and bi-directional relationships.

*Uni-directional relationships.  A uni-directional relationship when an object knows about the object(s) it is related to but the other object(s) do not know of the original object.  An example of which is the holds relationship between Employee and Position in Figure 11, indicated by the line with an open arrowhead on it.  Employee objects know about the position that they hold, but Position objects do not know which employee holds it (there was no requirement to do so).  As you will soon see, uni-directional relationships are easier to implement than bi-directional relationships.
*Bi-directional relationships.  A bi-directional relationship exists when the objects on both end of the relationship know of each other, an example of which is the works in relationship between Employee and Division.  Employee objects know what division they work in and Division objects know what employees work in them. 

Configuration System Failed to Initialize

I started to get this problem after uninstalling Oracle Client Drivers and it removed my C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\machine.config!

Copying it from another computer resolved the problem.

Using import fs from 'fs'

For default exports you should use:

import * as fs from 'fs';

Or in case the module has named exports:

import {fs} from 'fs';

Example:

//module1.js

export function function1() {
  console.log('f1')
}

export function function2() {
  console.log('f2')
}

export default function1;

And then:

import defaultExport, { function1, function2 } from './module1'

defaultExport();  // This calls function1
function1();
function2();

Additionally, you should use Webpack or something similar to be able to use ES6 import

Not an enclosing class error Android Studio

replace code in onClick() method with this:

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

Simplest way to set image as JPanel background

Simplest way to set image as JPanel background

Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.

See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:

  1. scaled
  2. tiled
  3. actual

Can we pass parameters to a view in SQL?

Normally views are not parameterized. But you could always inject some parameters. For example using session context:

CREATE VIEW my_view
AS
SELECT *
FROM tab
WHERE num = SESSION_CONTEXT(N'my_num');

Invocation:

EXEC sp_set_session_context 'my_num', 1; 
SELECT * FROM my_view;

And another:

EXEC sp_set_session_context 'my_num', 2; 
SELECT * FROM my_view;

DBFiddle Demo

The same is applicable for Oracle (of course syntax for context function is different).

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

Resize an Array while keeping current elements in Java?

It is not possible to change the Array Size. But you can copy the element of one array into another array by creating an Array of bigger size.

It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full

public class ResizingArrayStack1 {
    private String[] s;
    private int size = 0;
    private int index = 0;

    public void ResizingArrayStack1(int size) {
        this.size = size;
        s = new String[size];
    }


    public void push(String element) {
        if (index == s.length) {
            resize(2 * s.length);
        }
        s[index] = element;
        index++;
    }

    private void resize(int capacity) {
        String[] copy = new String[capacity];
        for (int i = 0; i < s.length; i++) {
            copy[i] = s[i];
            s = copy;
        }
    }

    public static void main(String[] args) {
        ResizingArrayStack1 rs = new ResizingArrayStack1();
        rs.push("a");
        rs.push("b");
        rs.push("c");
        rs.push("d");
    }
}

How to increase MySQL connections(max_connections)?

From Increase MySQL connection limit:-

MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:

For MySQL 3.x:

# vi /etc/my.cnf
set-variable = max_connections = 250

For MySQL 4.x and 5.x:

# vi /etc/my.cnf
max_connections = 250

Restart MySQL once you’ve made the changes and verify with:

echo "show variables like 'max_connections';" | mysql

EDIT:-(From comments)

The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs

How do I combine 2 javascript variables into a string

warning! this does not work with links.

var variable = 'variable', another = 'another';

['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');

Get filename in batch for loop

The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %, like this:

@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF

jquery save json data object in cookie

It is not good practice to save the value that is returned from JSON.stringify(userData) to a cookie; it can lead to a bug in some browsers.

Before using it, you should convert it to base64 (using btoa), and when reading it, convert from base64 (using atob).

val = JSON.stringify(userData)
val = btoa(val)

write_cookie(val)

HTML input file selection event not firing upon selecting the same file

Clearing the value of 0th index of input worked for me. Please try the below code, hope this will work (AngularJs).

          scope.onClick = function() {
            input[0].value = "";
                input.click();
            };

Android RatingBar change star colors

<!--For rating bar -->
    <style name="RatingBarfeed" parent="Theme.AppCompat">
        <item name="colorControlNormal">@color/colorPrimary</item>
        <item name="colorControlActivated">@color/colorPrimary</item>
    </style>

use your own color

Invalidating JSON Web Tokens

Why not just use the jti claim (nonce) and store that in a list as a user record field (db dependant, but at very least a comma-separated list is fine)? No need for separate lookup, as others have pointed out presumably you want to get the user record anyway, and this way you can have multiple valid tokens for different client instances ("logout everywhere" can reset the list to empty)

Replace comma with newline in sed on MacOS?

Apparently \r is the key!

$ sed 's/, /\r/g' file3.txt > file4.txt

Transformed this:

ABFS, AIRM, AMED, BOSC, CALI, ECPG, FRGI, GERN, GTIV, HSON, IQNT, JRCC, LTRE,
MACK, MIDD, NKTR, NPSP, PME, PTIX, REFR, RSOL, UBNT, UPI, YONG, ZEUS

To this:

ABFS
AIRM
AMED
BOSC
CALI
ECPG
FRGI
GERN
GTIV
HSON
IQNT
JRCC
LTRE
MACK
MIDD
NKTR
NPSP
PME
PTIX
REFR
RSOL
UBNT
UPI
YONG
ZEUS

SOAP Action WSDL

I have solved this problem, in Java Code, adding:

 MimeHeaders headers = message.getMimeHeaders();
 headers.addHeader("SOAPAction", endpointURL);

Giving my function access to outside variable

Two Answers

1. Answer to the asked question.

2. A simple change equals a better way!

Answer 1 - Pass the Vars Array to the __construct() in a class, you could also leave the construct empty and pass the Arrays through your functions instead.

<?php

// Create an Array with all needed Sub Arrays Example: 
// Example Sub Array 1
$content_arrays["modals"]= array();
// Example Sub Array 2
$content_arrays["js_custom"] = array();

// Create a Class
class Array_Pushing_Example_1 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Primary Contents Array as Parameter in __construct
    public function __construct($content_arrays){

        // Declare it
        $this->content_arrays = $content_arrays;

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class with the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_1($content_arrays);

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Answer 2 - A simple change however would put it inline with modern standards. Just declare your Arrays in the Class.

<?php

// Create a Class
class Array_Pushing_Example_2 {

    // Public to access outside of class
    public $content_arrays;

    // Needed in the class only
    private $push_value_1;
    private $push_value_2;
    private $push_value_3;
    private $push_value_4;  
    private $values;
    private $external_values;

    // Declare Contents Array and Sub Arrays in __construct
    public function __construct(){

        // Declare them
        $this->content_arrays["modals"] = array();
        $this->content_arrays["js_custom"] = array();

    }

    // Push Values from in the Array using Public Function
    public function array_push_1(){

        // Values
        $this->push_values_1 = array(1,"2B or not 2B",3,"42",5);
        $this->push_values_2 = array("a","b","c");

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_1 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_2 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

    // GET Push Values External to the Class with Public Function
    public function array_push_2($external_values){

        $this->push_values_3 = $external_values["values_1"];
        $this->push_values_4 = $external_values["values_2"];

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_3 as $this->values){

            $this->content_arrays["js_custom"][] = $this->values;

        }

        // Loop Values and Push Values to Sub Array
        foreach($this->push_values_4 as $this->values){

            $this->content_arrays["modals"][] = $this->values;

        }

    // Return Primary Array with New Values
    return $this->content_arrays;

    }

}

// Start the Class without the Contents Array as a Parameter
$content_arrays = new Array_Pushing_Example_2();

// Push Internal Values to the Arrays
$content_arrays->content_arrays = $content_arrays->array_push_1();

// Push External Values to the Arrays
$external_values = array();
$external_values["values_1"] = array("car","house","bike","glass");
$external_values["values_2"] = array("FOO","foo");
$content_arrays->content_arrays = $content_arrays->array_push_2($external_values);

// The Output
echo "Array Custom Content Results 1";
echo "<br>";
echo "<br>";

echo "Modals - Count: ".count($content_arrays->content_arrays["modals"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get Modals Array Results
foreach($content_arrays->content_arrays["modals"] as $modals){

    echo $modals;
    echo "<br>";

}

echo "<br>";
echo "JS Custom - Count: ".count($content_arrays->content_arrays["js_custom"]);
echo "<br>";
echo "-------------------";
echo "<br>";

// Get JS Custom Array Results
foreach($content_arrays->content_arrays["js_custom"] as $js_custom){

    echo $js_custom;
    echo "<br>";


}

echo "<br>";

?>

Both options output the same information and allow a function to push and retrieve information from an Array and sub Arrays to any place in the code(Given that the data has been pushed first). The second option gives more control over how the data is used and protected. They can be used as is just modify to your needs but if they were used to extend a Controller they could share their values among any of the Classes the Controller is using. Neither method requires the use of a Global(s).

Output:

Array Custom Content Results

Modals - Count: 5

a

b

c

FOO

foo

JS Custom - Count: 9

1

2B or not 2B

3

42

5

car

house

bike

glass

reactjs - how to set inline style of backgroundcolor?

https://facebook.github.io/react/tips/inline-styles.html

You don't need the quotes.

<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

serialize/deserialize java 8 java.time with Jackson JSON mapper

You may set this in your application.yml file to resolve Instant time, which is Date API in java8:

spring.jackson.serialization.write-dates-as-timestamps=false

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

A possibility is that the git server you are pushing to is down/crashed, and the solution lies in restarting the git server.

How to list active / open connections in Oracle?

When I'd like to view incoming connections from our application servers to the database I use the following command:

SELECT username FROM v$session 
WHERE username IS NOT NULL 
ORDER BY username ASC;

Simple, but effective.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

Note that if the problem is being caused by appearing scrollbars, putting

body {
  overflow: hidden;
}

in your CSS might be an easy fix (if you don't need the page to scroll).

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

Inline onclick JavaScript variable

There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider

JS

var myvar=15;
function init(){
    document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;

HTML

<input id="EditBanner" type="button"  value="Edit Image" />

Generating matplotlib graphs without a running X server

@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal.

E.g.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')

You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.

Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

I've changed the recursion to iteration.

def MovingTheBall(listOfBalls,position,numCell):
while 1:
    stop=1
    positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
    for i in range(0,len(listOfBalls)):
        if positionTmp==listOfBalls[i].pos:
            stop=0
    if stop==1:
        if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
            stop=0
        else:
            return positionTmp

Works good :D

How to get the GL library/headers?

What operating system?

Here on Ubuntu, I have

$ dpkg -S /usr/include/GL/gl.h 
mesa-common-dev: /usr/include/GL/gl.h
$ 

but not the difference in a) capitalization and b) forward/backward slashes. Your example is likely to be wrong in its use of backslashes.

git pull error :error: remote ref is at but expected

A hard reset will also resolve the problem

git reset --hard origin/master

How to enable CORS in apache tomcat

Just to add a bit of extra info over the right solution. Be aware that you'll need this class org.apache.catalina.filters.CorsFilter. So in order to have it, if your tomcat is not 7.0.41 or higher, download 'tomcat-catalina.7.0.41.jar' or higher ( you can do it from http://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina ) and put it in the 'lib' folder inside Tomcat installation folders. I actually used 7.0.42 Hope it helps!