Programs & Examples On #Expression evaluation

Anything related to expression evaluation, i.e. the process of determining the value of an expression in running code.

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

How to add an action to a UIAlertView button using Swift iOS

See my code:

 @IBAction func foundclicked(sender: AnyObject) {

            if (amountTF.text.isEmpty)
            {
                let alert = UIAlertView(title: "Oops! Empty Field", message: "Please enter the amount", delegate: nil, cancelButtonTitle: "OK")

                alert.show()
            }

            else {

            var alertController = UIAlertController(title: "Confirm Bid Amount", message: "Final Bid Amount : "+amountTF.text , preferredStyle: .Alert)
            var okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default) {
                UIAlertAction in

                JHProgressHUD.sharedHUD.loaderColor = UIColor.redColor()
                        JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Amount registering" , andFooter: "Loading")
                }
            var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
                UIAlertAction in

                alertController .removeFromParentViewController()
            }
                            alertController.addAction(okAction)
                            alertController.addAction(cancelAction)

                self.presentViewController(alertController, animated: true, completion: nil)

            }

        }

Print range of numbers on same line

n = int(input())
for i in range(1,n+1):
    print(i,end='')

What is a MIME type?

MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.

For example, using the Content-type header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.

Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".

A MIME type is a string identifier composed of two parts: a type and a subtype.

  • The "type" refers to a logical grouping of many MIME types that are closely related to each other; it's no more than a high level category.
  • "subtypes" are specific to one file type within the "type".

The x- prefix of a MIME subtype simply means that it's non-standard.
The vnd prefix means that the MIME value is vendor specific.

Source

iPhone X / 8 / 8 Plus CSS media queries

Here are some of the following media queries for iPhones. Here is the ref link https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

        /* iphone 3 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 1) { }
        
        /* iphone 4 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 480px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 5 */
        @media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (-webkit-device-pixel-ratio: 2) { }
        
        /* iphone 6, 6s, 7, 8 */
        @media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (-webkit-device-pixel-ratio: 2) { }
            
        /* iphone 6+, 6s+, 7+, 8+ */
        @media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (-webkit-device-pixel-ratio: 3) { }
        
        /* iphone X , XS, 11 Pro, 12 Mini */
        @media only screen and (min-device-width: 375px) and (max-device-height: 812px) and (-webkit-device-pixel-ratio: 3) { }

        /* iphone 12, 12 Pro */
        @media only screen and (min-device-width: 390px) and (max-device-height: 844px) and (-webkit-device-pixel-ratio: 3) { }
       
        /* iphone XR, 11 */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 2) { }
            
        /* iphone XS Max, 11 Pro Max */
        @media only screen and (min-device-width : 414px) and (max-device-height : 896px) and (-webkit-device-pixel-ratio : 3) { }

        /* iphone 12 Pro Max */
        @media only screen and (min-device-width : 428px) and (max-device-height : 926px) and (-webkit-device-pixel-ratio : 3) { }

List passed by ref - help me explain this behaviour

This link will help you in understanding pass by reference in C#. Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.

For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.

If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.

(Edit: this is the updated version of the documentation linked above.)

How to create a Restful web service with input parameters?

You can. Try something like this:

@Path("/todo/{varX}/{varY}")
@Produces({"application/xml", "application/json"})
public Todo whatEverNameYouLike(@PathParam("varX") String varX,
    @PathParam("varY") String varY) {
        Todo todo = new Todo();
        todo.setSummary(varX);
        todo.setDescription(varY);
        return todo;
}

Then call your service with this URL;
http://localhost:8088/JerseyJAXB/rest/todo/summary/description

How to properly add include directories with CMake

CMake is more like a script language if comparing it with other ways to create Makefile (e.g. make or qmake). It is not very cool like Python, but still.

There are no such thing like a "proper way" if looking in various opensource projects how people include directories. But there are two ways to do it.

  1. Crude include_directories will append a directory to the current project and all other descendant projects which you will append via a series of add_subdirectory commands. Sometimes people say that such approach is legacy.

  2. A more elegant way is with target_include_directories. It allows to append a directory for a specific project/target without (maybe) unnecessary inheritance or clashing of various include directories. Also allow to perform even a subtle configuration and append one of the following markers for this command.

PRIVATE - use only for this specified build target

PUBLIC - use it for specified target and for targets which links with this project

INTERFACE -- use it only for targets which links with the current project

PS:

  1. Both commands allow to mark a directory as SYSTEM to give a hint that it is not your business that specified directories will contain warnings.

  2. A similar answer is with other pairs of commands target_compile_definitions/add_definitions, target_compile_options/CMAKE_C_FLAGS

How to Consolidate Data from Multiple Excel Columns All into One Column

Here is how you do it with some simple Excel formulae, and no fancy VBA needed. The trick is to use the OFFSET formula. Please see this example spreadsheet:

https://docs.google.com/spreadsheet/ccc?key=0AuSyDFZlcRtHdGJOSnFwREotRzFfM28tWElpZ1FaR2c&usp=sharing#gid=0

python: how to identify if a variable is an array or a scalar

Is there an equivalent to isscalar() in numpy? Yes.

>>> np.isscalar(3.1)
True
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True
>>> np.isscalar('abcd')
True

Twitter Bootstrap - add top space between rows

Editing or overriding the row in Twitter bootstrap is a bad idea, because this is a core part of the page scaffolding and you will need rows without a top margin.

To solve this, instead create a new class "top-buffer" that adds the standard margin that you need.

.top-buffer { margin-top:20px; }

And then use it on the row divs where you need a top margin.

<div class="row top-buffer"> ...

How do you change the formatting options in Visual Studio Code?

I just found this extension called beautify in the Market Place and yes, it's another config\settings file. :)

Beautify javascript, JSON, CSS, Sass, and HTML in Visual Studio Code.

VS Code uses js-beautify internally, but it lacks the ability to modify the style you wish to use. This extension enables running js-beautify in VS Code, AND honouring any .jsbeautifyrc file in the open file's path tree to load your code styling. Run with F1 Beautify (to beautify a selection) or F1 Beautify file.

For help on the settings in the .jsbeautifyrc see Settings.md

Here is the GitHub repository: https://github.com/HookyQR/VSCodeBeautify

Immutable array in Java

As of Java 9 you can use List.of(...), JavaDoc.

This method returns an immutable List and is very efficient.

redistributable offline .NET Framework 3.5 installer for Windows 8

You don't have to copy everything to C:\dotnet35. Usually all the files are already copied to the folder C:\Windows\WinSxS. Then the command becomes (assuming Windows was installed to C:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:C:\Windows\WinSxS /LimitAccess" If not you can also point the command to the DVD directly. Then the command becomes (assuming DVD is mounted to D:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess".

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Q & A is built into Intellij ...

CTRL/CMD + SHIFT + A x 2 TYPE caret

Removing display of row names from data frame

Recently I had the same problem when using htmlTable() (‘htmlTable’ package) and I found a simpler solution: convert the data frame to a matrix with as.matrix():

htmlTable(as.matrix(df))

And be sure that the rownames are just indices. as.matrix() conservs the same columnames. That's it.

UPDATE

Following the comment of @DMR, I did't notice that htmlTable() has the parameter rnames = FALSE for cases like this. So a better answer would be:

htmlTable(df, rnames = FALSE)

Access Control Request Headers, is added to header in AJAX request with jQuery

Try to use the rack-cors gem. And add the header field in your Ajax call.

Insert using LEFT JOIN and INNER JOIN

INSERT INTO Test([col1],[col2]) (
    SELECT 
        a.Name AS [col1],
        b.sub AS [col2] 
    FROM IdTable b 
    INNER JOIN Nametable a ON b.no = a.no
)

Running multiple AsyncTasks at the same time -- not possible?

The android developers example of loading bitmaps efficiently uses a custom asynctask (copied from jellybean) so you can use the executeOnExecutor in apis lower than < 11

http://developer.android.com/training/displaying-bitmaps/index.html

Download the code and go to util package.

Kill all processes for a given user

Just (temporarily) killed my Macbook with

killall -u pu -m .

where pu is my userid. Watch the dot at the end of the command.

Also try

pkill -u pu

or

ps -o pid -u pu | xargs kill -1

Python Requests and persistent sessions

the other answers help to understand how to maintain such a session. Additionally, I want to provide a class which keeps the session maintained over different runs of a script (with a cache file). This means a proper "login" is only performed when required (timout or no session exists in cache). Also it supports proxy settings over subsequent calls to 'get' or 'post'.

It is tested with Python3.

Use it as a basis for your own code. The following snippets are release with GPL v3

import pickle
import datetime
import os
from urllib.parse import urlparse
import requests    

class MyLoginSession:
    """
    a class which handles and saves login sessions. It also keeps track of proxy settings.
    It does also maintine a cache-file for restoring session data from earlier
    script executions.
    """
    def __init__(self,
                 loginUrl,
                 loginData,
                 loginTestUrl,
                 loginTestString,
                 sessionFileAppendix = '_session.dat',
                 maxSessionTimeSeconds = 30 * 60,
                 proxies = None,
                 userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
                 debug = True,
                 forceLogin = False,
                 **kwargs):
        """
        save some information needed to login the session

        you'll have to provide 'loginTestString' which will be looked for in the
        responses html to make sure, you've properly been logged in

        'proxies' is of format { 'https' : 'https://user:pass@server:port', 'http' : ...
        'loginData' will be sent as post data (dictionary of id : value).
        'maxSessionTimeSeconds' will be used to determine when to re-login.
        """
        urlData = urlparse(loginUrl)

        self.proxies = proxies
        self.loginData = loginData
        self.loginUrl = loginUrl
        self.loginTestUrl = loginTestUrl
        self.maxSessionTime = maxSessionTimeSeconds
        self.sessionFile = urlData.netloc + sessionFileAppendix
        self.userAgent = userAgent
        self.loginTestString = loginTestString
        self.debug = debug

        self.login(forceLogin, **kwargs)

    def modification_date(self, filename):
        """
        return last file modification date as datetime object
        """
        t = os.path.getmtime(filename)
        return datetime.datetime.fromtimestamp(t)

    def login(self, forceLogin = False, **kwargs):
        """
        login to a session. Try to read last saved session from cache file. If this fails
        do proper login. If the last cache access was too old, also perform a proper login.
        Always updates session cache file.
        """
        wasReadFromCache = False
        if self.debug:
            print('loading or generating session...')
        if os.path.exists(self.sessionFile) and not forceLogin:
            time = self.modification_date(self.sessionFile)         

            # only load if file less than 30 minutes old
            lastModification = (datetime.datetime.now() - time).seconds
            if lastModification < self.maxSessionTime:
                with open(self.sessionFile, "rb") as f:
                    self.session = pickle.load(f)
                    wasReadFromCache = True
                    if self.debug:
                        print("loaded session from cache (last access %ds ago) "
                              % lastModification)
        if not wasReadFromCache:
            self.session = requests.Session()
            self.session.headers.update({'user-agent' : self.userAgent})
            res = self.session.post(self.loginUrl, data = self.loginData, 
                                    proxies = self.proxies, **kwargs)

            if self.debug:
                print('created new session with login' )
            self.saveSessionToCache()

        # test login
        res = self.session.get(self.loginTestUrl)
        if res.text.lower().find(self.loginTestString.lower()) < 0:
            raise Exception("could not log into provided site '%s'"
                            " (did not find successful login string)"
                            % self.loginUrl)

    def saveSessionToCache(self):
        """
        save session to a cache file
        """
        # always save (to update timeout)
        with open(self.sessionFile, "wb") as f:
            pickle.dump(self.session, f)
            if self.debug:
                print('updated session cache-file %s' % self.sessionFile)

    def retrieveContent(self, url, method = "get", postData = None, **kwargs):
        """
        return the content of the url with respect to the session.

        If 'method' is not 'get', the url will be called with 'postData'
        as a post request.
        """
        if method == 'get':
            res = self.session.get(url , proxies = self.proxies, **kwargs)
        else:
            res = self.session.post(url , data = postData, proxies = self.proxies, **kwargs)

        # the session has been updated on the server, so also update in cache
        self.saveSessionToCache()            

        return res

A code snippet for using the above class may look like this:

if __name__ == "__main__":
    # proxies = {'https' : 'https://user:pass@server:port',
    #           'http' : 'http://user:pass@server:port'}

    loginData = {'user' : 'usr',
                 'password' :  'pwd'}

    loginUrl = 'https://...'
    loginTestUrl = 'https://...'
    successStr = 'Hello Tom'
    s = MyLoginSession(loginUrl, loginData, loginTestUrl, successStr, 
                       #proxies = proxies
                       )

    res = s.retrieveContent('https://....')
    print(res.text)

    # if, for instance, login via JSON values required try this:
    s = MyLoginSession(loginUrl, None, loginTestUrl, successStr, 
                       #proxies = proxies,
                       json = loginData)

How can I get a uitableViewCell by indexPath?

Finally, I get the cell using the following code:

UITableViewCell *cell = (UITableViewCell *)[(UITableView *)self.view cellForRowAtIndexPath:nowIndex];

Because the class is extended UITableViewController:

@interface SearchHotelViewController : UITableViewController

So, the self is "SearchHotelViewController".

Check if table exists in SQL Server

IF EXISTS 
(
    SELECT  * 

    FROM    INFORMATION_SCHEMA.TABLES 

    WHERE   TABLE_SCHEMA = 'PutSchemaHere'     
            AND  
            TABLE_NAME   = 'PutTableNameHere'
)

Mask output of `The following objects are masked from....:` after calling attach() function

You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

Here is the best way to find out Foreign Key Relationship in all Database.

exec sp_helpconstraint 'Table Name'

and one more way

select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME='Table Name'
--and left(CONSTRAINT_NAME,2)='FK'(If you want single key)

Center a popup window on screen?

My version with ES6 JavaScript.
Works well on Chrome and Chromium with dual screen setup.

function openCenteredWindow({url, width, height}) {
    const pos = {
        x: (screen.width / 2) - (width / 2),
        y: (screen.height/2) - (height / 2)
    };

    const features = `width=${width} height=${height} left=${pos.x} top=${pos.y}`;

    return window.open(url, '_blank', features);
}

Example

openCenteredWindow({
    url: 'https://stackoverflow.com/', 
    width: 500, 
    height: 600
}).focus();

How to find a Java Memory Leak

Most of the time, in enterprise applications the Java heap given is larger than the ideal size of max 12 to 16 GB. I have found it hard to make the NetBeans profiler work directly on these big java apps.

But usually this is not needed. You can use the jmap utility that comes with the jdk to take a "live" heap dump , that is jmap will dump the heap after running GC. Do some operation on the application, wait till the operation is completed, then take another "live" heap dump. Use tools like Eclipse MAT to load the heapdumps, sort on the histogram, see which objects have increased, or which are the highest, This would give a clue.

su  proceeuser
/bin/jmap -dump:live,format=b,file=/tmp/2930javaheap.hrpof 2930(pid of process)

There is only one problem with this approach; Huge heap dumps, even with the live option, may be too big to transfer out to development lap, and may need a machine with enough memory/RAM to open.

That is where the class histogram comes into picture. You can dump a live class histogram with the jmap tool. This will give only the class histogram of memory usage.Basically it won't have the information to chain the reference. For example it may put char array at the top. And String class somewhere below. You have to draw the connection yourself.

jdk/jdk1.6.0_38/bin/jmap -histo:live 60030 > /tmp/60030istolive1330.txt

Instead of taking two heap dumps, take two class histograms, like as described above; Then compare the class histograms and see the classes that are increasing. See if you can relate the Java classes to your application classes. This will give a pretty good hint. Here is a pythons script that can help you compare two jmap histogram dumps. histogramparser.py

Finally tools like JConolse and VisualVm are essential to see the memory growth over time, and see if there is a memory leak. Finally sometimes your problem may not be a memory leak , but high memory usage.For this enable GC logging;use a more advanced and new compacting GC like G1GC; and you can use jdk tools like jstat to see the GC behaviour live

jstat -gccause pid <optional time interval>

Other referecences to google for -jhat, jmap, Full GC, Humongous allocation, G1GC

Getting each individual digit from a whole integer

RGB values fall nicely on bit boundaries; decimal digits don't. I don't think there's an easy way to do this using bitwise operators at all. You'd need to use decimal operators like modulo 10 (% 10).

Please add a @Pipe/@Directive/@Component annotation. Error

The Above error occurs if any wrong import done. For example sometimes Service files may be added in TestBed.configureTestingModule. And also while importing Material component for example import from

import {MatDialogModule} from '@angular/material/dialog'

not from

import {MatDialogModule} from '@angular/material'

Page scroll when soft keyboard popped up

Ok, I have searched several hours now to find the problem, and I found it.

None of the changes like fillViewport="true" or android:windowSoftInputMode="adjustResize" helped me.

I use Android 4.4 and this is the big mistake:

android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

Somehow, the Fullscreen themes prevent the ScrollViews from scrolling when the SoftKeyboard is visible.

At the moment, I ended up using this instead:

android:theme="@android:style/Theme.Black.NoTitleBar

I don't know how to get rid of the top system bar with time and battery display, but at least I got the problem.

Hope this helps others who have the same problem.

EDIT: I got a little workaround for my case, so I posted it here:

I am not sure if this will work for you, but it will definitely help you in understanding, and clear some things up.

EDIT2: Here is another good topic that will help you to go in the right direction or even solve your problem.

Cross domain POST request is not sending cookie Ajax Jquery

There have been a slew of recent changes in this arena, so I thought a fresh answer would be helpful.

To have a cookie sent by the browser to another site during a request the following criteria must be met:

A lot of people find their way to this post trying to do local development against a remote endpoint, which is possible if the above criteria are met.

jquery append div inside div with id and manipulate

var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

Pure css close button

Edit: Updated css to match with what you have..

DEMO

HTML

<div>
    <span class="close-btn"><a href="#">X</a></span>
</div>

CSS

.close-btn {
    border: 2px solid #c2c2c2;
    position: relative;
    padding: 1px 5px;
    top: -20px;
    background-color: #605F61;
    left: 198px;
    border-radius: 20px;
}

.close-btn a {
    font-size: 15px;
    font-weight: bold;
    color: white;
    text-decoration: none;
}

Strip off URL parameter with PHP

$var = preg_replace( "/return=[^&]+/", "", $var ); 
$var = preg_replace( "/&{2,}/", "&", $var );

Second line will just replace && to &

How should I do integer division in Perl?

You can cast ints in Perl:

int(5/1.5) = 3;

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I have added for this:

Server compression

server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain

taken from http://bisaga.com/blog/programming/web-compression-on-spring-boot-application/

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

Use multiple css stylesheets in the same html page

The one you include last will be the one that is used. Note however that if any rules has !important in the first stylesheet they will take priority.

Paste MS Excel data to SQL Server

The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement. Then copy these insert into a text file and then execute on the SQL. The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.

Intellij Cannot resolve symbol on import

File -> Invalidate Caches/Restart or rebuilding the project did not work wor me.

What worked for my Gradle project was to "Refresh all Gradle projects" from the Gradle tab on top-right corner of IntelliJ v2017, using the yellow marked button shown below:

enter image description here

How to top, left justify text in a <td> cell that spans multiple rows

 <td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>

That should do it.

ES6 modules implementation, how to load a json file

With json-loader installed, now you can simply use:

import suburbs from '../suburbs.json';

or, even more simply:

import suburbs from '../suburbs';

Anchor links in Angularjs?

I don't know if that answers your question, but yes, you can use angularjs links, such as:

<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>

There is a good example on the AngularJS website:

http://docs.angularjs.org/api/ng.directive:ngHref

UPDATE: The AngularJS documentation was a bit obscure and it didn't provide a good solution for it. Sorry!

You can find a better solution here: How to handle anchor hash linking in AngularJS

Netbeans how to set command line arguments in Java

If it's a Maven project then Netbeans is running your application using the exec-maven-plugin so you'll need to append your options onto the existing exec.args property found in the Run Maven dialog. This dialog can be accessed from the the Output window by pressing the yellow double arrow icon.

enter image description here

Difference between maven scope compile and provided for JAR packaging

When you set maven scope as provided, it means that when the plugin runs, the actual dependencies version used will depend on the version of Apache Maven you have installed.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

you can use the download attribute on an a tag ...

<a href="data:image/jpeg;base64,/9j/4AAQSkZ..." download="filename.jpg"></a>

see more: https://developer.mozilla.org/en/HTML/element/a#attr-download

Vertically align an image inside a div with responsive height

Make another div and add both 'dummy' and 'img-container' inside the div

Do HTML and CSS like follows

_x000D_
_x000D_
html , body {height:100%;}_x000D_
.responsive-container { height:100%; display:table; text-align:center; width:100%;}_x000D_
.inner-container {display:table-cell; vertical-align:middle;}
_x000D_
<div class="responsive-container">_x000D_
    <div class="inner-container">_x000D_
  <div class="dummy">Sample</div>_x000D_
  <div class="img-container">_x000D_
   Image tag_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Instead of 100% for the 'responsive-container' you can give the height that you want.,

Can't Autowire @Repository annotated interface in Spring Boot

I had a similar issue with Spring Data MongoDB: I had to add the package path to @EnableMongoRepositories

how to configuring a xampp web server for different root directory

You can also put in a new virtual Host entry in the

c:\xampp\apache\conf\httpd-vhosts.conf

like:

<VirtualHost *:80>
  ServerAdmin [email protected]
  DocumentRoot "C:/xampp/htdocs/myproject/web"
  ServerName localhost
  ErrorLog "logs/dummy-host2.example.com-error.log"
  CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

When is the init() function run?

When is the init() function run?

With Go 1.16 (Q1 2021), you will see precisely when it runs, and for how long.

See commit 7c58ef7 from CL (Change List) 254659, fixing issue 41378 .

Runtime: implement GODEBUG=inittrace=1 support

Setting inittrace=1 causes the runtime to emit a single line to standard error for each package with init work, summarizing the execution time and memory allocation.

The emitted debug information for init functions can be used to find bottlenecks or regressions in Go startup performance.

Packages with no init function work (user defined or compiler generated) are omitted.

Tracing plugin inits is not supported as they can execute concurrently. This would make the implementation of tracing more complex while adding support for a very rare use case. Plugin inits can be traced separately by testing a main package importing the plugins package imports explicitly.

$ GODEBUG=inittrace=1 go test
init internal/bytealg @0.008 ms, 0 ms clock, 0 bytes, 0 allocs
init runtime @0.059 ms, 0.026 ms clock, 0 bytes, 0 allocs
init math @0.19 ms, 0.001 ms clock, 0 bytes, 0 allocs
init errors @0.22 ms, 0.004 ms clock, 0 bytes, 0 allocs
init strconv @0.24 ms, 0.002 ms clock, 32 bytes, 2 allocs
init sync @0.28 ms, 0.003 ms clock, 16 bytes, 1 allocs
init unicode @0.44 ms, 0.11 ms clock, 23328 bytes, 24 allocs
...

Inspired by [email protected] who instrumented doInit in a prototype to measure init times with GDB.

Preloading CSS Images

I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.

Here's a test : http://paragraphe.org/slidetoggletest/test.html

<script>
    var pic = new Image();
    var pic2 = new Image();
    var pic3 = new Image();
    pic.src="images/inputs/input1.png";
    pic2.src="images/inputs/input2.png";
    pic3.src="images/inputs/input3.png";
</script>

Creating your own header file in C

myfile.h

#ifndef _myfile_h
#define _myfile_h

void function();

#endif

myfile.c

#include "myfile.h"

void function() {

}

Facebook Architecture

Facebook is using LAMP structure. Facebook’s back-end services are written in a variety of different programming languages including C++, Java, Python, and Erlang and they are used according to requirement. With LAMP Facebook uses some technologies ,to support large number of requests, like

  1. Memcache - It is a memory caching system that is used to speed up dynamic database-driven websites (like Facebook) by caching data and objects in RAM to reduce reading time. Memcache is Facebook’s primary form of caching and helps alleviate the database load. Having a caching system allows Facebook to be as fast as it is at recalling your data.

  2. Thrift (protocol) - It is a lightweight remote procedure call framework for scalable cross-language services development. Thrift supports C++, PHP, Python, Perl, Java, Ruby, Erlang, and others.

  3. Cassandra (database) - It is a database management system designed to handle large amounts of data spread out across many servers.

  4. HipHop for PHP - It is a source code transformer for PHP script code and was created to save server resources. HipHop transforms PHP source code into optimized C++. After doing this, it uses g++ to compile it to machine code.

If we go into more detail, then answer to this question go longer. We can understand more from following posts:

  1. How Does Facebook Work?
  2. Data Management, Facebook-style
  3. Facebook database design?
  4. Facebook wall's database structure
  5. Facebook "like" data structure

How do I import material design library to Android Studio?

First, add the Material Design dependency.

implementation 'com.google.android.material:material:<version>'

To get the latest material design library version. check the official website github repository.

Current version is 1.2.0.

So, you have to add,

implementation 'com.google.android.material:material:1.2.0'

Then, you need to change the app theme to material theme by adding,

<style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

in your style.xml. Dont forget to set the same theme in your application theme in your manifest file.

The property 'value' does not exist on value of type 'HTMLElement'

Based on Tomasz Nurkiewiczs answer, the "problem" is that typescript is typesafe. :) So the document.getElementById() returns the type HTMLElement which does not contain a value property. The subtype HTMLInputElement does however contain the value property.

So a solution is to cast the result of getElementById() to HTMLInputElement like this:

var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;

<> is the casting operator in typescript. See the question TypeScript: casting HTMLElement.

The resulting javascript from the line above looks like this:

inputValue = (document.getElementById(elementId)).value;

i.e. containing no type information.

.ssh directory not being created

I am assuming that you have enough permissions to create this directory.

To fix your problem, you can either ssh to some other location:

ssh [email protected]

and accept new key - it will create directory ~/.ssh and known_hosts underneath, or simply create it manually using

mkdir ~/.ssh
chmod 700 ~/.ssh

Note that chmod 700 is an important step!

After that, ssh-keygen should work without complaints.

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Yes, on Arrays.asList, returning a fixed-size list.

Other than using a linked list, simply use addAll method list.

Example:

String idList = "123,222,333,444";

List<String> parentRecepeIdList = new ArrayList<String>();

parentRecepeIdList.addAll(Arrays.asList(idList.split(","))); 

parentRecepeIdList.add("555");

Java 8 Distinct by property

Another library that supports this is jOO?, and its Seq.distinct(Function<T,U>) method:

Seq.seq(persons).distinct(Person::getName).toList();

Under the hood, it does practically the same thing as the accepted answer, though.

Convert any object to a byte[]

checkout this article :http://www.morgantechspace.com/2013/08/convert-object-to-byte-array-and-vice.html

Use the below code

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();
}

// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);

    return obj;
}

Java 8: Difference between two LocalDateTime in multiple units

Here is a very simple answer to your question. It works.

import java.time.*;
import java.util.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class MyClass {
public static void main(String args[]) {
    DateTimeFormatter T = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
    Scanner h = new Scanner(System.in);

    System.out.print("Enter date of birth[dd/mm/yyyy hh:mm]: ");
    String b = h.nextLine();

    LocalDateTime bd = LocalDateTime.parse(b,T);
    LocalDateTime cd = LocalDateTime.now();

    long minutes = ChronoUnit.MINUTES.between(bd, cd);
    long hours = ChronoUnit.HOURS.between(bd, cd);

    System.out.print("Age is: "+hours+ " hours, or " +minutes+ " minutes old");
}
}

Contain an image within a div?

object-fit, behaves like background-size, solving the issue of scaling images up and down to fit.

The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

snapshot of an image rendered with all the object-fit options

.cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    overflow: hidden;
}

Browser Support

There's no IE support, and support in Edge begins at v16, only for img element: https://caniuse.com/#search=object-fit

The bfred-it/object-fit-images polyfill works very well for me in IE11, tested on Browserstack: demo.


Alternative without polyfill using an image in SVG

For Edge pre v16, and ie9, ie10, ie11:

You can crop and scale any image using CSS object-fit and object-position. However, these properties are only supported in the latest version of MS Edge as well as all other modern browsers.

If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an <svg>, and using the viewBox and preserveAspectRatio attributes to do what object-fit and object-position do.

http://www.sarasoueidan.com/blog/svg-object-fit/#summary-recap

(The author explains the technique thoroughly, and duplicating the detail here would be impractical.)

Auto-redirect to another HTML page

If you want to redirect your webpage to another HTML FILE, just use as followed:

<meta http-equiv="refresh" content"2;otherpage.html">

2 being the seconds you want the client to wait before redirecting. Use "url=" only when it's an URL, to redirect to an HTML file just write the name after the ';'

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

In my case a misplaced session.clear() was causing this problem.

copy-item With Alternate Credentials

that evidently powershell's cmdlets such as copy-item, test-path, etc do not support alternate credentials...

It looks like they do here, copy-item certainly includes a -Credential parameter.

PS C:\> gcm -syn copy-item
Copy-Item [-Path] <String[]> [[-Destination] <String>] [-Container] [-Force] [-Filter <String>] [-I
nclude <String[]>] [-Exclude <String[]>] [-Recurse] [-PassThru] [-Credential <PSCredential>] [...]

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

How to use the CancellationToken property?

@BrainSlugs83

You shouldn't blindly trust everything posted on stackoverflow. The comment in Jens code is incorrect, the parameter doesn't control whether exceptions are thrown or not.

MSDN is very clear what that parameter controls, have you read it? http://msdn.microsoft.com/en-us/library/dd321703(v=vs.110).aspx

If throwOnFirstException is true, an exception will immediately propagate out of the call to Cancel, preventing the remaining callbacks and cancelable operations from being processed. If throwOnFirstException is false, this overload will aggregate any exceptions thrown into an AggregateException, such that one callback throwing an exception will not prevent other registered callbacks from being executed.

The variable name is also wrong because Cancel is called on CancellationTokenSource not the token itself and the source changes state of each token it manages.

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

Try this

ALTER DATABASE XXXX  SET RECOVERY SIMPLE

use XXXX

declare @log_File_Name varchar(200) 

select @log_File_Name  = name from sysfiles where filename like '%LDF'

declare @i int = FILE_IDEX ( @log_File_Name)

dbcc shrinkfile ( @i , 50) 

Mongoose: Find, modify, save

Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:

User.update({username: oldUsername}, {
    username: newUser.username, 
    password: newUser.password, 
    rights: newUser.rights
}, function(err, numberAffected, rawResponse) {
   //handle it
})

MySQL's now() +1 day

You can use:

NOW() + INTERVAL 1 DAY

If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:

CURDATE() + INTERVAL 1 DAY

window.location.href not working

Please check you are using // not \\ by-mistake , like below

Wrong:"http:\\stackoverflow.com"

Right:"http://stackoverflow.com"

jQuery Set Cursor Position in Text Area

I found a solution that works for me:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    var input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}

Now you can move the focus to the end of any element by calling:

$(element).focusEnd();

Or you specify the position.

$(element).setCursorPosition(3); // This will focus on the third character.

How to solve "Connection reset by peer: socket write error"?

The socket has been closed by the client (browser).

A bug in your code:

byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
   output.write(outputByte,0,4096);
}

The last packet read, then write may have a length < 4096, so I suggest:

byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
   output.write( outputByte, 0, len );
}

It's not your question, but it's my answer... ;-)

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

In Python script, how do I set PYTHONPATH?

If you put sys.path.append('dir/to/path') without check it is already added, you could generate a long list in sys.path. For that, I recommend this:

import sys
import os # if you want this directory

try:
    sys.path.index('/dir/path') # Or os.getcwd() for this directory
except ValueError:
    sys.path.append('/dir/path') # Or os.getcwd() for this directory

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC LIMIT 50

save resources make one query, there is no need to make nested queries

How do I mock an open used in a with statement (using the Mock framework in Python)?

To patch the built-in open() function with unittest:

This worked for a patch to read a json config.

class ObjectUnderTest:
    def __init__(self, filename: str):
        with open(filename, 'r') as f:
            dict_content = json.load(f)

The mocked object is the io.TextIOWrapper object returned by the open() function

@patch("<src.where.object.is.used>.open",
        return_value=io.TextIOWrapper(io.BufferedReader(io.BytesIO(b'{"test_key": "test_value"}'))))
    def test_object_function_under_test(self, mocker):

How to Insert Double or Single Quotes

Or Select range and Format cells > Custom \"@\"

How to set Python's default version to 3.x on OS X?

I'm not sure if this is available on OS X, but on linux I would make use of the module command. See here.

Set up the modulefile correctly, then add something like this to your rc file (e.g. ~/.bashrc):

module load python3.3

This will make it so that your paths get switched around as required when you log in without impacting any system defaults.

How do I change the string representation of a Python class?

This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

'""'

and not

'"a"'

as would be expected.

EDIT: answering mchicago's comment:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

b = A('b') print b

produces

'a'

while

json.dumps({'b': b})

produces

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

First letter capitalization for EditText

Apply following line in your EditText in XML.

android:inputType="textCapSentences|textMultiLine"

It will also allow multi-line support.

How to check if $_GET is empty?

Here are 3 different methods to check this

<?php
//Method 1
if(!empty($_GET))
echo "exist";
else
echo "do not exist";
//Method 2
echo "<br>";
if($_GET)
echo "exist";
else
echo "do not exist";
//Method 3
if(count($_GET))
echo "exist";
else
echo "do not exist";
?>

Regex to check if valid URL that ends in .jpg, .png, or .gif

(http(s?):)|([/|.|\w|\s])*\.(?:jpg|gif|png)

This will mach all images from this string:

background: rgb(255, 0, 0) url(../res/img/temp/634043/original/cc3d8715eed0c.jpg) repeat fixed left top; cursor: auto;
<div id="divbg" style="background-color:#ff0000"><img id="bg" src="../res/img/temp/634043/original/cc3d8715eed0c.jpg" width="100%" height="100%" /></div>
background-image: url(../res/img/temp/634043/original/cc3d8715eed0c.png);
background: rgb(255, 0, 0) url(http://google.com/res/../img/temp/634043/original/cc3    _d8715eed0c.jpg) repeat fixed left top; cursor: auto;
background: rgb(255, 0, 0) url(https://google.com/res/../img/temp/634043/original/cc3_d8715eed0c.jpg) repeat fixed left top; cursor: auto;

Test your regex here: https://regex101.com/r/l2Zt7S/1

How to install XNA game studio on Visual Studio 2012?

Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.

  1. First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.

  2. Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :

    xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"

  3. Run notepad as administrator then open extension.vsixmanifest in the destination directory just created.

  4. Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio element and change the Version attribute, as @brainslugs83 said in comments):

    <SupportedProducts>
      <VisualStudio Version="11.0">
        <Edition>VSTS</Edition>
        <Edition>VSTD</Edition>
        <Edition>Pro</Edition>
        <Edition>VCSExpress</Edition>
        <Edition>VPDExpress</Edition>
      </VisualStudio>
    </SupportedProducts>
    
  5. Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.

  6. You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.

    "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
    

This has been tested for Windows Games, but not WP7 or Xbox games.

[Edit] According Jowsty, this works also for XBox 360 Games.

[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.

R Apply() function on specific dataframe columns

Using an example data.frame and example function (just +1 to all values)

A <- function(x) x + 1
wifi <- data.frame(replicate(9,1:4))
wifi

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  1  1  1  1  1  1
#2  2  2  2  2  2  2  2  2  2
#3  3  3  3  3  3  3  3  3  3
#4  4  4  4  4  4  4  4  4  4

data.frame(wifi[1:3], apply(wifi[4:9],2, A) )
#or
cbind(wifi[1:3], apply(wifi[4:9],2, A) )

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  2  2  2  2  2  2
#2  2  2  2  3  3  3  3  3  3
#3  3  3  3  4  4  4  4  4  4
#4  4  4  4  5  5  5  5  5  5

Or even:

data.frame(wifi[1:3], lapply(wifi[4:9], A) )
#or
cbind(wifi[1:3], lapply(wifi[4:9], A) )

#  X1 X2 X3 X4 X5 X6 X7 X8 X9
#1  1  1  1  2  2  2  2  2  2
#2  2  2  2  3  3  3  3  3  3
#3  3  3  3  4  4  4  4  4  4
#4  4  4  4  5  5  5  5  5  5

Display a view from another controller in ASP.NET MVC

Yes its possible. Return a RedirectToAction() method like this:

return RedirectToAction("ActionOrViewName", "ControllerName");

How to get current foreground activity context in android?

The answer by waqas716 is good. I created a workaround for a specific case demanding less code and maintenance.

I found a specific work around by having a static method fetch a view from the activity I suspect to be in the foreground. You can iterate through all activities and check if you wish or get the activity name from martin's answer

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity; 

I then check if the view is not null and get the context via getContext().

View v = SuspectedActivity.get_view();

if(v != null)
{
    // an example for using this context for something not 
    // permissible in global application context. 
    v.getContext().startActivity(new Intent("rubberduck.com.activities.SomeOtherActivity"));
}

How to close activity and go back to previous activity in android

try this code instead of finish:

onBackPressed();

Installation of SQL Server Business Intelligence Development Studio

If you have installed SQL 2005 express edition and want to install BIDS (Business Intelligence Development Studio) then go to here Microsoft SQL Server 2005 Express Edition Toolkit

This has an option to install BIDS on my machine, and is the only way l could get hold of BIDS for SQL Server 2005 express edition.

Also this package l think has also allowed me to install both BIDS 2005 & 2008 express edition on the same machine.

I am not able launch JNLP applications using "Java Web Start"?

In my case, the problem was caused by starting my app from a shortcut on the public desktop (windows 7). As a result, as far as I can tell, the temporary files location was set to c:\users\public\etc. This resulted in the unable to write to cache detail. When I reset to defaults in the temporary files control applet, all worked fine.

What is the difference between JSF, Servlet and JSP?

The basic difference between Servlets and JSP is that in Servlets we write java code and in that we embed HTML code and there is just reverse case with JSP . In JSP we write HTML code and in that we embed java code using tags provided by JSP.

python plot normal distribution

Use seaborn instead i am using distplot of seaborn with mean=5 std=3 of 1000 values

value = np.random.normal(loc=5,scale=3,size=1000)
sns.distplot(value)

You will get a normal distribution curve

show validation error messages on submit in angularjs

// This worked for me.
<form  name="myForm" class="css-form" novalidate ng-submit="Save(myForm.$invalid)">
<input type="text" name="uName" ng-model="User.Name" required/>
<span ng-show="User.submitted && myForm.uName.$error.required">Name is required.</span>
<input ng-click="User.submitted=true" ng-disabled="User.submitted && tForm.$invalid" type="submit" value="Save" />
</form>
// in controller
$scope.Save(invalid)
{
if(invalid) return;
// save form
}

Executable directory where application is running from?

Dim strPath As String = System.IO.Path.GetDirectoryName( _
    System.Reflection.Assembly.GetExecutingAssembly().CodeBase)

Taken from HOW TO: Determine the Executing Application's Path (MSDN)

Convert Pandas column containing NaNs to dtype `int`

If you can modify your stored data, use a sentinel value for missing id. A common use case, inferred by the column name, being that id is an integer, strictly greater than zero, you could use 0 as a sentinel value so that you can write

if row['id']:
   regular_process(row)
else:
   special_process(row)

Disable vertical scroll bar on div overflow: auto

How about a shorthand notation?

{overflow: auto hidden;}

How to format a QString?

Use QString::arg() for the same effect.

How to print number with commas as thousands separators?

babel module in python has feature to apply commas depending on the locale provided.

To install babel run the below command.

pip install babel

usage

format_currency(1234567.89, 'USD', locale='en_US')
# Output: $1,234,567.89
format_currency(1234567.89, 'USD', locale='es_CO')
# Output: US$ 1.234.567,89 (raw output US$\xa01.234.567,89)
format_currency(1234567.89, 'INR', locale='en_IN')
# Output: ?12,34,567.89

How do I define a method in Razor?

You can simply declare them as local functions in a razor block (i.e. @{}).

@{
    int Add(int x, int y)
    {
        return x + y;
    }
}

<div class="container">
    <p>
        @Add(2, 5)
    </p>
</div>

Match groups in Python

this is not a regex solution.

alist={"I love ":""He loves"","Je t'aime ":"Il aime","Ich liebe ":"Er liebt"}
for k in alist.keys():
    if k in statement:
       print alist[k],statement.split(k)[1:]

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

Thanks to the talk with Sarfraz we could figure out the solution.

The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities table and filter correct entries).

So, instead of:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex]
};

it should be:

var data = {
        'mode': 'filter_city',
        'id_A': e[e.selectedIndex].value
};

Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.

Transfer data from one database to another database

if both databases are on same server and you want to transfer entire table (make copy of it) then use simple select into statement ...

select * into anotherDatabase..copyOfTable from oneDatabase..tableName

You can then write cursor top of sysobjects and copy entire set of tables that way.

If you want more complex data extraction & transformation, then use SSIS and build appropriate ETL in it.

Add a link to an image in a css style sheet

You can not do that...

via css the URL you put on the background-image is just for the image.

Via HTML you have to add the href for your hyperlink in this way:

<a href="http://home.com" id="logo">Your logo</a>

With text-indent and some other css you can adjust your a element to show just the image and clicking on it you will go to your link.


EDIT:

I'm here again to show you and explain why my solution is much better:

<a href="http://home.com" id="logo">Your logo name</a>

This block of HTML is SEO friendly because you have some text inside your link!

How to style it with css:

#logo {
  background-image: url(images/logo.png);
  display: block;
  margin: 0 auto;
  text-indent: -9999px;
  width: 981px;
  height: 180px;
}

Then if you don't care about SEO good to choose the other answer.

Passing a variable from node.js to html

I have achieved this by a http API node request which returns required object from node object for HTML page at client ,

for eg: API: localhost:3000/username

returns logged in user from cache by node App object .

node route file,

app.get('/username', function(req, res) {
    res.json({ udata: req.session.user });
    });

multiple figure in latex with captions

Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.

\begin{figure}[htp]
  \centering
  \label{figur}\caption{equation...}

  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \\
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \\
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}

\end{figure}

How to create a blank/empty column with SELECT query in oracle?

In DB2, using single quotes instead of your double quotes will work. So that could translate the same in Oracle..

SELECT CustomerName AS Customer, '' AS Contact 
FROM Customers;

The name 'ViewBag' does not exist in the current context

If you had tried all available answers and still cannot find the answer this might solve issue. If you have different solutions configurations like Debug, Release etc then set project output path to 'bin' and compile project. Revert change after compiling.

Project Output Path

VS looks for dlls in bin folder

How to generate List<String> from SQL query?

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.

Groovy built-in REST/HTTP client?

The simplest one got to be:

def html = "http://google.com".toURL().text

Convert string to Python class object?

In terms of arbitrary code execution, or undesired user passed names, you could have a list of acceptable function/class names, and if the input matches one in the list, it is eval'd.

PS: I know....kinda late....but it's for anyone else who stumbles across this in the future.

PHP strtotime +1 month adding an extra month

You can use this code to get the next month:

$ts = mktime(0, 0, 0, date("n") + 1, 1);
echo date("Y-m-d H:i:s", $ts);
echo date("n", $ts);

Assuming today is 2013-01-31 01:23:45 the above will return:

2013-02-01 00:00:00
2

Get properties and values from unknown object

One line solution using Linq...

var obj = new {Property1: 1, Property2: 2};
var property1 = obj.GetType().GetProperties().First(o => o.Name == "Property1").GetValue(obj , null);

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

Here's a modification of the accepted answer to provide more functionality.

RangeCollection.cs:

public class RangeCollection<T> : ObservableCollection<T>
{
    #region Members

    /// <summary>
    /// Occurs when a single item is added.
    /// </summary>
    public event EventHandler<ItemAddedEventArgs<T>> ItemAdded;

    /// <summary>
    /// Occurs when a single item is inserted.
    /// </summary>
    public event EventHandler<ItemInsertedEventArgs<T>> ItemInserted;

    /// <summary>
    /// Occurs when a single item is removed.
    /// </summary>
    public event EventHandler<ItemRemovedEventArgs<T>> ItemRemoved;

    /// <summary>
    /// Occurs when a single item is replaced.
    /// </summary>
    public event EventHandler<ItemReplacedEventArgs<T>> ItemReplaced;

    /// <summary>
    /// Occurs when items are added to this.
    /// </summary>
    public event EventHandler<ItemsAddedEventArgs<T>> ItemsAdded;

    /// <summary>
    /// Occurs when items are removed from this.
    /// </summary>
    public event EventHandler<ItemsRemovedEventArgs<T>> ItemsRemoved;

    /// <summary>
    /// Occurs when items are replaced within this.
    /// </summary>
    public event EventHandler<ItemsReplacedEventArgs<T>> ItemsReplaced;

    /// <summary>
    /// Occurs when entire collection is cleared.
    /// </summary>
    public event EventHandler<ItemsClearedEventArgs<T>> ItemsCleared;

    /// <summary>
    /// Occurs when entire collection is replaced.
    /// </summary>
    public event EventHandler<CollectionReplacedEventArgs<T>> CollectionReplaced;

    #endregion

    #region Helper Methods

    /// <summary>
    /// Throws exception if any of the specified objects are null.
    /// </summary>
    private void Check(params T[] Items)
    {
        foreach (T Item in Items)
        {
            if (Item == null)
            {
                throw new ArgumentNullException("Item cannot be null.");
            }
        }
    }

    private void Check(IEnumerable<T> Items)
    {
        if (Items == null) throw new ArgumentNullException("Items cannot be null.");
    }

    private void Check(IEnumerable<IEnumerable<T>> Items)
    {
        if (Items == null) throw new ArgumentNullException("Items cannot be null.");
    }

    private void RaiseChanged(NotifyCollectionChangedAction Action)
    {
        this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

    #endregion

    #region Bulk Methods

    /// <summary> 
    /// Adds the elements of the specified collection to the end of this.
    /// </summary> 
    public void AddRange(IEnumerable<T> NewItems)
    {
        this.Check(NewItems);
        foreach (var i in NewItems) this.Items.Add(i);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnItemsAdded(new ItemsAddedEventArgs<T>(NewItems));
    }

    /// <summary>
    /// Adds variable IEnumerable<T> to this.
    /// </summary>
    /// <param name="List"></param>
    public void AddRange(params IEnumerable<T>[] NewItems)
    {
        this.Check(NewItems);
        foreach (IEnumerable<T> Items in NewItems) foreach (T Item in Items) this.Items.Add(Item);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        //TO-DO: Raise OnItemsAdded with combined IEnumerable<T>.
    }

    /// <summary> 
    /// Removes the first occurence of each item in the specified collection. 
    /// </summary> 
    public void Remove(IEnumerable<T> OldItems)
    {
        this.Check(OldItems);
        foreach (var i in OldItems) Items.Remove(i);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
    }

    /// <summary>
    /// Removes all occurences of each item in the specified collection.
    /// </summary>
    /// <param name="itemsToRemove"></param>
    public void RemoveAll(IEnumerable<T> OldItems)
    {
        this.Check(OldItems);
        var set = new HashSet<T>(OldItems);
        var list = this as List<T>;
        int i = 0;
        while (i < this.Count) if (set.Contains(this[i])) this.RemoveAt(i); else i++;
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
    }

    /// <summary> 
    /// Replaces all occurences of a single item with specified item.
    /// </summary> 
    public void ReplaceAll(T Old, T New)
    {
        this.Check(Old, New);
        this.Replace(Old, New, false);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
    }

    /// <summary> 
    /// Clears this and adds specified collection. 
    /// </summary> 
    public void ReplaceCollection(IEnumerable<T> NewItems, bool SupressEvent = false)
    {
        this.Check(NewItems);
        IEnumerable<T> OldItems = new List<T>(this.Items);
        this.Items.Clear();
        foreach (T Item in NewItems) this.Items.Add(Item);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnReplaced(new CollectionReplacedEventArgs<T>(OldItems, NewItems));
    }

    private void Replace(T Old, T New, bool BreakFirst)
    {
        List<T> Cloned = new List<T>(this.Items);
        int i = 0;
        foreach (T Item in Cloned)
        {
            if (Item.Equals(Old))
            {
                this.Items.Remove(Item);
                this.Items.Insert(i, New);
                if (BreakFirst) break;
            }
            i++;
        }
    }

    /// <summary> 
    /// Replaces the first occurence of a single item with specified item.
    /// </summary> 
    public void Replace(T Old, T New)
    {
        this.Check(Old, New);
        this.Replace(Old, New, true);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
    }

    #endregion

    #region  New Methods

    /// <summary>
    /// Removes a single item.
    /// </summary>
    /// <param name="Item"></param>
    public new void Remove(T Item)
    {
        this.Check(Item);
        base.Remove(Item);
        OnItemRemoved(new ItemRemovedEventArgs<T>(Item));
    }

    /// <summary>
    /// Removes a single item at specified index.
    /// </summary>
    /// <param name="i"></param>
    public new void RemoveAt(int i)
    {
        T OldItem = this.Items[i]; //This will throw first if null
        base.RemoveAt(i);
        OnItemRemoved(new ItemRemovedEventArgs<T>(OldItem));
    }

    /// <summary>
    /// Clears this.
    /// </summary>
    public new void Clear()
    {
        IEnumerable<T> OldItems = new List<T>(this.Items);
        this.Items.Clear();
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnCleared(new ItemsClearedEventArgs<T>(OldItems));
    }

    /// <summary>
    /// Adds a single item to end of this.
    /// </summary>
    /// <param name="t"></param>
    public new void Add(T Item)
    {
        this.Check(Item);
        base.Add(Item);
        this.OnItemAdded(new ItemAddedEventArgs<T>(Item));
    }

    /// <summary>
    /// Inserts a single item at specified index.
    /// </summary>
    /// <param name="i"></param>
    /// <param name="t"></param>
    public new void Insert(int i, T Item)
    {
        this.Check(Item);
        base.Insert(i, Item);
        this.OnItemInserted(new ItemInsertedEventArgs<T>(Item, i));
    }

    /// <summary>
    /// Returns list of T.ToString().
    /// </summary>
    /// <returns></returns>
    public new IEnumerable<string> ToString()
    {
        foreach (T Item in this) yield return Item.ToString();
    }

    #endregion

    #region Event Methods

    private void OnItemAdded(ItemAddedEventArgs<T> i)
    {
        if (this.ItemAdded != null) this.ItemAdded(this, new ItemAddedEventArgs<T>(i.NewItem));
    }

    private void OnItemInserted(ItemInsertedEventArgs<T> i)
    {
        if (this.ItemInserted != null) this.ItemInserted(this, new ItemInsertedEventArgs<T>(i.NewItem, i.Index));
    }

    private void OnItemRemoved(ItemRemovedEventArgs<T> i)
    {
        if (this.ItemRemoved != null) this.ItemRemoved(this, new ItemRemovedEventArgs<T>(i.OldItem));
    }

    private void OnItemReplaced(ItemReplacedEventArgs<T> i)
    {
        if (this.ItemReplaced != null) this.ItemReplaced(this, new ItemReplacedEventArgs<T>(i.OldItem, i.NewItem));
    }

    private void OnItemsAdded(ItemsAddedEventArgs<T> i)
    {
        if (this.ItemsAdded != null) this.ItemsAdded(this, new ItemsAddedEventArgs<T>(i.NewItems));
    }

    private void OnItemsRemoved(ItemsRemovedEventArgs<T> i)
    {
        if (this.ItemsRemoved != null) this.ItemsRemoved(this, new ItemsRemovedEventArgs<T>(i.OldItems));
    }

    private void OnItemsReplaced(ItemsReplacedEventArgs<T> i)
    {
        if (this.ItemsReplaced != null) this.ItemsReplaced(this, new ItemsReplacedEventArgs<T>(i.OldItems, i.NewItems));
    }

    private void OnCleared(ItemsClearedEventArgs<T> i)
    {
        if (this.ItemsCleared != null) this.ItemsCleared(this, new ItemsClearedEventArgs<T>(i.OldItems));
    }

    private void OnReplaced(CollectionReplacedEventArgs<T> i)
    {
        if (this.CollectionReplaced != null) this.CollectionReplaced(this, new CollectionReplacedEventArgs<T>(i.OldItems, i.NewItems));
    }

    #endregion

    #region RangeCollection

    /// <summary> 
    /// Initializes a new instance. 
    /// </summary> 
    public RangeCollection() : base() { }

    /// <summary> 
    /// Initializes a new instance from specified enumerable. 
    /// </summary> 
    public RangeCollection(IEnumerable<T> Collection) : base(Collection) { }

    /// <summary> 
    /// Initializes a new instance from specified list.
    /// </summary> 
    public RangeCollection(List<T> List) : base(List) { }

    /// <summary>
    /// Initializes a new instance with variable T.
    /// </summary>
    public RangeCollection(params T[] Items) : base()
    {
        this.AddRange(Items);
    }

    /// <summary>
    /// Initializes a new instance with variable enumerable.
    /// </summary>
    public RangeCollection(params IEnumerable<T>[] Items) : base()
    {
        this.AddRange(Items);
    }

    #endregion
}

Events Classes:

public class CollectionReplacedEventArgs<T> : ReplacedEventArgs<T>
{
    public CollectionReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}

public class ItemAddedEventArgs<T> : EventArgs
{
    public T NewItem;
    public ItemAddedEventArgs(T t)
    {
        this.NewItem = t;
    }
}

public class ItemInsertedEventArgs<T> : EventArgs
{
    public int Index;
    public T NewItem;
    public ItemInsertedEventArgs(T t, int i)
    {
        this.NewItem = t;
        this.Index = i;
    }
}

public class ItemRemovedEventArgs<T> : EventArgs
{
    public T OldItem;
    public ItemRemovedEventArgs(T t)
    {
        this.OldItem = t;
    }
}

public class ItemReplacedEventArgs<T> : EventArgs
{
    public T OldItem;
    public T NewItem;
    public ItemReplacedEventArgs(T Old, T New)
    {
        this.OldItem = Old;
        this.NewItem = New;
    }
}

public class ItemsAddedEventArgs<T> : EventArgs
{
    public IEnumerable<T> NewItems;
    public ItemsAddedEventArgs(IEnumerable<T> t)
    {
        this.NewItems = t;
    }
}

public class ItemsClearedEventArgs<T> : RemovedEventArgs<T>
{
    public ItemsClearedEventArgs(IEnumerable<T> Old) : base(Old) { }
}

public class ItemsRemovedEventArgs<T> : RemovedEventArgs<T>
{
    public ItemsRemovedEventArgs(IEnumerable<T> Old) : base(Old) { }
}

public class ItemsReplacedEventArgs<T> : ReplacedEventArgs<T>
{
    public ItemsReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}

public class RemovedEventArgs<T> : EventArgs
{
    public IEnumerable<T> OldItems;
    public RemovedEventArgs(IEnumerable<T> Old)
    {
        this.OldItems = Old;
    }
}

public class ReplacedEventArgs<T> : EventArgs
{
    public IEnumerable<T> OldItems;
    public IEnumerable<T> NewItems;
    public ReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New)
    {
        this.OldItems = Old;
        this.NewItems = New;
    }
}

Note: I did not manually raise OnCollectionChanged in the base methods because it appears only to be possible to create a CollectionChangedEventArgs using the Reset action. If you try to raise OnCollectionChanged using Reset for a single item change, your items control will appear to flicker, which is something you want to avoid.

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

Centering the pagination in bootstrap

It works for me:

<div class="text-center">
<ul class="pagination pagination-lg">
   <li>
  <a href="#" aria-label="Previous">
    <span aria-hidden="true">&laquo;</span>
  </a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
  <a href="#" aria-label="Next">
    <span aria-hidden="true">&raquo;</span>
  </a>
</li>
</ul>

Microsoft Excel ActiveX Controls Disabled?

From other forums, I have learned that it is due to the MS Update and that a good fix is to simply delete the file MSForms.exd from any Temp subfolder in the user's profile. For instance:

C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\MSForms.exd

C:\Users\[user.name]\AppData\Local\Temp\VBE\MSForms.exd

C:\Users\[user.name]\AppData\Local\Temp\Word8.0\MSForms.exd

Of course the application (Excel, Word...) must be closed in order to delete this file.

Notice: Undefined offset: 0 in

You are asking for the value at key 0 of $votes. It is an array that does not contain that key.

The array $votes is not set, so when PHP is trying to access the key 0 of the array, it encounters an undefined offset for [0] and [1] and throws the error.

If you have an array:

$votes = array('1','2','3');

We can now access:

$votes[0];
$votes[1];
$votes[2];

If we try and access:

$votes[3];

We will get the error "Notice: Undefined offset: 3"

Custom exception type

I often use an approach with prototypal inheritance. Overriding toString() gives you the advantage that tools like Firebug will log the actual information instead of [object Object] to the console for uncaught exceptions.

Use instanceof to determine the type of exception.

main.js

// just an exemplary namespace
var ns = ns || {};

// include JavaScript of the following
// source files here (e.g. by concatenation)

var someId = 42;
throw new ns.DuplicateIdException('Another item with ID ' +
    someId + ' has been created');
// Firebug console:
// uncaught exception: [Duplicate ID] Another item with ID 42 has been created

Exception.js

ns.Exception = function() {
}

/**
 * Form a string of relevant information.
 *
 * When providing this method, tools like Firebug show the returned 
 * string instead of [object Object] for uncaught exceptions.
 *
 * @return {String} information about the exception
 */
ns.Exception.prototype.toString = function() {
    var name = this.name || 'unknown';
    var message = this.message || 'no description';
    return '[' + name + '] ' + message;
};

DuplicateIdException.js

ns.DuplicateIdException = function(message) {
    this.name = 'Duplicate ID';
    this.message = message;
};

ns.DuplicateIdException.prototype = new ns.Exception();

How to find children of nodes using BeautifulSoup

Yet another method - create a filter function that returns True for all desired tags:

def my_filter(tag):
    return (tag.name == 'a' and
        tag.parent.name == 'li' and
        'test' in tag.parent['class'])

Then just call find_all with the argument:

for a in soup(my_filter): # or soup.find_all(my_filter)
    print a

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

From the command prompt run the command adb kill-server. This will shutdown ADB and android studio or Eclipse if you were to use that, would show Waiting for ADB as you said.

Once ADB has shutdown down run adb start-server or run adb devices which will automatically start the adb service and show that your android emulator or development devices has successfully connected.

Key hash for Android-Facebook app

The simplest solution:

  1. Don't add the hash key, implement everything else
  2. When facebook login is pressed, you will get an error saying "Invalid key hash. The key hash "xxx" does not match any stored key. ..."
  3. Open the facebook app dashboard and add the hash "xxx=" ("xxx" hash from the error + "=" sign)

Auto reloading python Flask app upon code changes

from the terminal u can simply say

expoort FLASK_APP=app_name.py
export FLASK_ENV=development
flask run

or in ur file

if __name__ == "__main__":
    app.run(debug=True)

Updating Python on Mac

I recommend using pyenv to manage your local python versions (both 2.x and 3.x) instead of installing new versions directly with homebrew or building new python versions from source manually. Essentially, pyenv can do two key things for you:

  • Install different python versions under some directory. Doing pyenv install 3.8.1 will install python 3.8.1 under ~/.pyenv/versions/3.8.1.
  • Modify your shell environment (PATH) with shims so that when you do pyenv local 3.8.1, calling python will invoke the new interpreter instead of your system python.

MacOSX Specific Installation

The pyenv repo is pretty detailed on how to install for different systems and what it's actually doing, but here's the basic steps for mac:

  1. Install homebrew if you don't already have it and use it to install pyenv with brew install pyenv
  2. Once you have pyenv installed, update your .bash_profile file to include:
if command -v pyenv 1>/dev/null 2>&1; then
    eval "$(pyenv init -)"
fi

Now install some python using pyenv and then switch to it with the pyenv local command (you can see all your versions with pyenv versions).

pyenv install 3.8.1 && pyenv local 3.8.1

Note: you may need to create a new shell or reload your bash_profile in your current shell for the pyenv initialization to do its thing (set up shims).

With this setup, you'll be able to keep your system macosx python and switch to whatever new version of python you want available through pyenv.

'python' is not recognized as an internal or external command

Try "py" instead of "python" from command line:

C:\Users\Cpsa>py
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

Are you trying to run your .exe file from the cmd? This was my mistake. Just run the .exe file by double clicking it. If it's a .NET Core SCD for Windows 8.1/Windows Server 2012 R2 x64.

Selenium IDE - Command to wait for 5 seconds

One that I've found works for the site I test is this one:

waitForCondition | selenium.browserbot.getUserWindow().$.active==0 | 20000

Klendathu

How do I remove a CLOSE_WAIT socket connection

Even though too much of CLOSE_WAIT connections means there is something wrong with your code in the first and this is accepted not good practice.

You might want to check out: https://github.com/rghose/kill-close-wait-connections

What this script does is send out the ACK which the connection was waiting for.

This is what worked for me.

store return json value in input hidden field

It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).

Anyway, if that is an array wrapper, you'll want something like this:

$('#my-hidden-field').val(theObject[0].id);

You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,

$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;

This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

compareTo with primitives -> Integer / int

They're already ints. Why not just use subtraction?

compare = a - b;

Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.

Ruby, remove last N characters from a string?

x = "my_test"
last_char = x.split('').last

The split() method in Java does not work on a dot (.)

The documentation on split() says:

Splits this string around matches of the given regular expression.

(Emphasis mine.)

A dot is a special character in regular expression syntax. Use Pattern.quote() on the parameter to split() if you want the split to be on a literal string pattern:

String[] words = temp.split(Pattern.quote("."));

What's a good hex editor/viewer for the Mac?

On http://www.synalysis.net/ you can get the hex editor I'm developing for the Mac - Synalyze It!. It costs 7 € / 40 € (Pro version) and offers some extra features like histogram, incremental search, support of many text encodings and interactive definition of a "grammar" for your file format.

The grammar helps to interpret the files and colors the hex view for easier analysis.

Synalyze It!

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

I was compiling my application targeting any CPU and main problem turned out that adobe reader was installed older v10.x needs to upgrade v11.x, this is the way how I get to resolve this issue.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

How to insert a timestamp in Oracle?

Inserting date in sql

insert
into tablename (timestamp_value)
values ('dd-mm-yyyy hh-mm-ss AM');

If suppose we wanted to insert system date

insert
into tablename (timestamp_value)
values (sysdate);

What does the C++ standard state the size of int, long type to be?

As you mentioned - it largely depends upon the compiler and the platform. For this, check the ANSI standard, http://home.att.net/~jackklein/c/inttypes.html

Here is the one for the Microsoft compiler: Data Type Ranges.

How does #include <bits/stdc++.h> work in C++?

That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.

Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

Remove directory which is not empty

graph-fs


Install

npm i graph-fs

Use

const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");

directory.delete(); // <--

How can you integrate a custom file browser/uploader with CKEditor?

An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:

So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:

window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);

For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:

<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage); </script>

If the upload failed, set the errorMessage to some non-zero-length string and empty the url, and vice versa on success.

Exception in thread "main" java.lang.Error: Unresolved compilation problems

You have to Import the Scanner and Timer Package Properly using the java.util classes.

import java.util.Scanner;
import java.util.Timer;

What is the difference between angular-route and angular-ui-router?

ngRoute is a basic routing library, where you can specify just one view and controller for any route.

With ui-router, you can specify multiple views, both parallel and nested. So if your application requires (or may require in future) any kind of complex routing/views, then go ahead with ui-router.

This is best getting started guide for AngularUI Router.

TypeError: p.easing[this.easing] is not a function

You need to include jQueryUI for the extended easing options.

I think there may be an option to only include the easing in the download, or at least just the base library plus easing.

MySQL error 1241: Operand should contain 1 column(s)

Just remove the ( and the ) on your SELECT statement:

insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;

How to thoroughly purge and reinstall postgresql on ubuntu?

I was following the replies, When editing /etc/group I also deleted this line:

ssl-cert:x:112:postgres

then, when trying to install postgresql, I got this error

Preconfiguring packages ...
dpkg: unrecoverable fatal error, aborting:
 syntax error: unknown group 'ssl-cert' in statoverride file
E: Sub-process /usr/bin/dpkg returned an error code (2)

Putting the "ssl-cert:x:112:postgres" line back in /etc/group seems to fix it (so I was able to install postgresql)

How to display an error message in an ASP.NET Web Application

Roughly you can do it like that :

try
{
    //do something
}
catch (Exception ex)
{
    string script = "<script>alert('" + ex.Message + "');</script>";
    if (!Page.IsStartupScriptRegistered("myErrorScript"))
    {
         Page.ClientScript.RegisterStartupScript("myErrorScript", script);
    }
}

But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.

Highlighting Text Color using Html.fromHtml() in Android?

font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")

Java :Add scroll into text area

The Easiest way to implement scrollbar using java swing is as below :

  1. Navigate to Design view
  2. right click on textArea
  3. Select surround with JScrollPane

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

How do I duplicate a line or selection within Visual Studio Code?

For those migrating from WebStorm/PhpStorm,

You could install IntelliJ IDEA Keybindings to keep using almost all the keyboard shortcuts as you did in Webstorm/Phpstorm.

So,

  • Duplicate lines => CTRL + D
  • Move a line/selection of code Up/Down => Ctrl + Shift + UP/DOWN

Also, here is a list of recommended VS Code extensions that will make your transition from WebStorm/Phpstorm much easier.

Open file by its full path in C++

You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.

#include <fstream>
#include <iostream>
using namespace std;

int main() {
   ifstream ifs( "c:/demo.txt" );       // note no mode needed
   if ( ! ifs.is_open() ) {                 
      cout <<" Failed to open" << endl;
   }
   else {
      cout <<"Opened OK" << endl;
   }
}

What does this code produce on your system?

React-Native: Application has not been registered error

I guess it is an error caused by not matching name of project and your registered component.

You have inited project with one name, i.e.

react-native init AwesomeApp

But in your index.ios.js file you register other component

AppRegistry.registerComponent('Bananas', () => Bananas);

When it must be

AppRegistry.registerComponent('AwesomeApp', () => Bananas);

If your component name does match, ensure you don't have any other react-native/node process running in another terminal.

ASP.net page without a code behind

File: logdate.aspx

<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%

StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());

tsw.Close();
%>

Done

Get skin path in Magento?

To get that file use the below code.

include(Mage::getBaseDir('skin').'myfunc.php');

But it is not a correct way. To add your custom functions you can use the below file.

app/code/core/Mage/core/functions.php

Kindly avoid to use the PHP function under skin dir.

How to mock location on device?

Maybe it's not 'programmer' approach, but if you want save your time and get working solution instant try one of the apps which are dedicated to mock location available in Google Play:

Fake GPS Location Spoofer

Mock Locations

Fake GPS location

Python and SQLite: insert into table

Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:

def sqlite_insert(conn, table, row):
    cols = ', '.join('"{}"'.format(col) for col in row.keys())
    vals = ', '.join(':{}'.format(col) for col in row.keys())
    sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
    conn.cursor().execute(sql, row)
    conn.commit()

Example of use:

sqlite_insert(conn, 'stocks', {
        'created_at': '2016-04-17',
        'type': 'BUY',
        'amount': 500,
        'price': 45.00})

Note, that table name and column names should be validated beforehand.

How to update record using Entity Framework 6?

Try It....

UpdateModel(book);

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            UpdateModel(book);
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

How to get the latest file in a folder?

I have tried to use the above suggestions and my program crashed, than I figured out the file I'm trying to identify was used and when trying to use 'os.path.getctime' it crashed. what finally worked for me was:

    files_before = glob.glob(os.path.join(my_path,'*'))
    **code where new file is created**
    new_file = set(files_before).symmetric_difference(set(glob.glob(os.path.join(my_path,'*'))))

this codes gets the uncommon object between the two sets of file lists its not the most elegant, and if multiple files are created at the same time it would probably won't be stable

MySQL/Writing file error (Errcode 28)

I had same problem but disk space was okay (only 40% full). Problem were inodes, I had too many small files and my inodes were full.

You can check inode status with df -i

Android studio Gradle icon error, Manifest Merger

In your .gradle change MinSDK, for example:

  • build.gradle (Module: app)
    • before: minSdkVersion 9
    • after: minSdkVersion 14

etc.

Git SSH error: "Connect to host: Bad file number"

You can also try to:

telnet example.com 22

to see if you have connectivity to the server. I saw this message and it ended up being the VPN I was on was blocking access. Disconnected from the VPN and I was good to go.

TypeScript typed array usage

You could try either of these. They are not giving me errors.

It is also the suggested method from typescript for array declaration.

By using the Array<Thing> it is making use of the generics in typescript. It is similar to asking for a List<T> in c# code.

// Declare with default value
private _possessions: Array<Thing> = new Array<Thing>();
// or
private _possessions: Array<Thing> = [];
// or -> prefered by ts-lint
private _possessions: Thing[] = [];

or

// declare
private _possessions: Array<Thing>;
// or -> preferd by ts-lint
private _possessions: Thing[];

constructor(){
    //assign
    this._possessions = new Array<Thing>();
    //or
    this._possessions = [];
}

stale element reference: element is not attached to the page document

The thing here is that you're using a for loop outside of your conditional statement.

After the conditions in your IF statement are met you probably navigate to another page, thus when the for loop attempts to iterate once more, you get the stale element error because you're on a different page.

You can add a break at the end of your if statement, this worked for me.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

You could also create your own conversion function, inside which you can use exception blocks:

CREATE OR REPLACE FUNCTION convert_to_integer(v_input text)
RETURNS INTEGER AS $$
DECLARE v_int_value INTEGER DEFAULT NULL;
BEGIN
    BEGIN
        v_int_value := v_input::INTEGER;
    EXCEPTION WHEN OTHERS THEN
        RAISE NOTICE 'Invalid integer value: "%".  Returning NULL.', v_input;
        RETURN NULL;
    END;
RETURN v_int_value;
END;
$$ LANGUAGE plpgsql;

Testing:

=# select convert_to_integer('1234');
 convert_to_integer 
--------------------
               1234
(1 row)

=# select convert_to_integer('');
NOTICE:  Invalid integer value: "".  Returning NULL.
 convert_to_integer 
--------------------

(1 row)

=# select convert_to_integer('chicken');
NOTICE:  Invalid integer value: "chicken".  Returning NULL.
 convert_to_integer 
--------------------

(1 row)

Improving bulk insert performance in Entity framework

There is opportunity for several improvements (if you are using DbContext):

Set:

yourContext.Configuration.AutoDetectChangesEnabled = false;
yourContext.Configuration.ValidateOnSaveEnabled = false;

Do SaveChanges() in packages of 100 inserts... or you can try with packages of 1000 items and see the changes in performance.

Since during all this inserts, the context is the same and it is getting bigger, you can rebuild your context object every 1000 inserts. var yourContext = new YourContext(); I think this is the big gain.

Doing this improvements in an importing data process of mine, took it from 7 minutes to 6 seconds.

The actual numbers... could not be 100 or 1000 in your case... try it and tweak it.

How can I define an array of objects?

You are better off using a native array instead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.

What you are looking for here is an inline interface definition for your array that defines every element in that array, whether initially present or introduced later:

let userTestStatus: { id: number, name: string }[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:

let userTestStatus = [
    { "id": 0, "name": "Available" },
    ...
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

Load and execute external js file in node.js with access to local variables?

If you are writing code for Node, using Node modules as described by Ivan is without a doubt the way to go.

However, if you need to load JavaScript that has already been written and isn't aware of node, the vm module is the way to go (and definitely preferable to eval).

For example, here is my execfile module, which evaluates the script at path in either context or the global context:

var vm = require("vm");
var fs = require("fs");
module.exports = function(path, context) {
  var data = fs.readFileSync(path);
  vm.runInNewContext(data, context, path);
}

Also note: modules loaded with require(…) don't have access to the global context.

How can I merge two commits into one if I already started rebase?

If you want to combine the two most recent commits and just use the older commit's message, you can automate the process using expect.

I assume:

  • You're using vi as your editor
  • Your commits are one-line each

I tested with git version 2.14.3 (Apple Git-98).


#!/usr/bin/env expect
spawn git rebase -i HEAD~2

# change the second "pick" to "squash"
# down, delete word, insert 's' (for squash), Escape, save and quit
send "jdwis \033:wq\r"

expect "# This is a"

# skip past first commit message (assumed to be one line), delete rest of file
# down 4, delete remaining lines, save and quit
send "4jdG\r:wq\r"

interact

Parsing jQuery AJAX response

Imagine that this is your Json response

{"Visit":{"VisitId":8,"Description":"visit8"}}

This is how you parse the response and access the values

    Ext.Ajax.request({
    headers: {
        'Content-Type': 'application/json'
    },
    url: 'api/fullvisit/getfullvisit/' + visitId,
    method: 'GET',
    dataType: 'json',
    success: function (response, request) {
        obj = JSON.parse(response.responseText);
        alert(obj.Visit.VisitId);
    }
});

This will alert the VisitId field

ASP.NET MVC3 - textarea with @Html.EditorFor

You could use the [DataType] attribute on your view model like this:

public class MyViewModel
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
}

and then you could have a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
}

and a view which does what you want:

@model AppName.Models.MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Text)
    <input type="submit" value="OK" />
}

How can I use onItemSelected in Android?

Joseph: spinner.setOnItemSelectedListener(this) should be below Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1); on onCreate

Find unused npm packages in package.json

if you want to choose upon which giant's shoulders you will stand

here is a link to generate a short list of options available to npm; it filters on the keywords unused packages

https://www.npmjs.com/search?q=unused%20packages

jquery disable form submit on enter

Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :

var keyCode = e.keyCode || e.which;
if (keyCode === 13 && !$(document.activeElement).is('textarea')) {
  e.preventDefault();
  return false;
}

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

AngularJS : How do I switch views from a controller function?

This little function has served me well:

    //goto view:
    //useage -  $scope.gotoView("your/path/here", boolean_open_in_new_window)
    $scope.gotoView = function (st_view, is_newWindow)
    {

        console.log('going to view: ' + '#/' + st_view, $window.location);
        if (is_newWindow)
        {
            $window.open($window.location.origin + $window.location.pathname + '' + '#/' + st_view, '_blank');
        }
        else
        {
            $window.location.hash = '#/' + st_view;
        }


    };

You dont need the full path, just the view you are switching to

How to generate random colors in matplotlib?

Based on Ali's and Champitoad's answer:

If you want to try different palettes for the same, you can do this in a few lines:

cmap=plt.cm.get_cmap(plt.cm.viridis,143)

^143 being the number of colours you're sampling

I picked 143 because the entire range of colours on the colormap comes into play here. What you can do is sample the nth colour every iteration to get the colormap effect.

n=20 for i,(x,y) in enumerate(points): plt.scatter(x,y,c=cmap(n*i))

How to indent a few lines in Markdown markup?

If you're working with bullet points, try this:

<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
      <li>Black tea</li>
      <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

This is the method I use when styling markdown.

How to set a selected option of a dropdown list control using angular JS

This is the code what I used for the set selected value

_x000D_
_x000D_
countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];_x000D_
 _x000D_
 _x000D_
 for (var j = 0; j < countryList.length; j++) {_x000D_
      //debugger_x000D_
      if (countryList[j].text == "Australia") {_x000D_
          console.log(countryList[j].text); _x000D_
          countryList[j].isSelected = 'selected';_x000D_
      }_x000D_
      }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>_x000D_
<label>Country</label>_x000D_
<select class="custom-select col-12" id="Country" name="Country"   >_x000D_
<option value="0" selected>Choose...</option>_x000D_
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}"   > {{country.text}}</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

try this on an angular framework

What to gitignore from the .idea folder?

For a couple of years I was a supporter of using a specific .gitignore for IntelliJ with this suggested configuration.

Not anymore.

IntelliJ is updated quite frequently, internal config file specs change more often than I would like and JetBrains flagship excels at auto-configuring itself based on maven/gradle/etc build files.

So my suggestion would be to leave all editor config files out of project and have users configure editor to their liking. Things like code styling can and should be configured at build level; say using Google Code Style or CheckStyle directly on Maven/Gradle/sbt/etc.

This ensures consistency and leaves editor files out of source code that, in my personal opinion, is where they should be.

How to use: while not in

Using sets will be screaming fast if you have any volume of data

If you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.

MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])

while not MyList.isdisjoint(MyOper):
    print "No boolean Operator"

http://docs.python.org/library/stdtypes.html#set.isdisjoint

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

Add error bars to show standard deviation on a plot in R

In addition to @csgillespie's answer, segments is also vectorised to help with this sort of thing:

plot (x, y, ylim=c(0,6))
segments(x,y-sd,x,y+sd)
epsilon <- 0.02
segments(x-epsilon,y-sd,x+epsilon,y-sd)
segments(x-epsilon,y+sd,x+epsilon,y+sd)

enter image description here

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

HTML forms support GET and POST. (HTML5 at one point added PUT/DELETE, but those were dropped.)

XMLHttpRequest supports every method, including CHICKEN, though some method names are matched against case-insensitively (methods are case-sensitive per HTTP) and some method names are not supported at all for security reasons (e.g. CONNECT).

Browsers are slowly converging on the rules specified by XMLHttpRequest, but as the other comment pointed out there are still some differences.

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

How to clear Flutter's Build cache?

Build cache is generated on application run time when a temporary file automatically generated in dart-tools folder, android folder and iOS folder. Clear command will delete the build tools and dart directories in flutter project so when we re-compile the project it will start from beginning. This command is mostly used when our project is showing debug error or running related error. In this answer we would Clear Build Cache in Flutter Android iOS App and Rebuild Project structure again.

  1. Open your flutter project folder in Command Prompt or Terminal. and type flutter clean command and press enter.

  2. After executing flutter clean command we would see that it will delete the dart-tools folder, android folder and iOS folder in our application with debug file. This might take some time depending upon your system speed to clean the project.

For more info, see https://flutter-examples.com/clear-build-cache-in-flutter-app/

struct in class

You should define the struct out of the class like this:

#include <iostream>
using namespace std;
struct X
{
        int v;
};
class E
{
public: 
      X var;
};

int main(){

E object;
object.var.v=10; 

return 0;
}

Select rows from a data frame based on values in a vector

Similar to above, using filter from dplyr:

filter(df, fct %in% vc)

How to sort a list of strings numerically?

real problem is that sort sorts things alphanumerically. So if you have a list ['1', '2', '10', '19'] and run sort you get ['1', '10'. '19', '2']. ie 10 comes before 2 because it looks at the first character and sorts starting from that. It seems most methods in python return things in that order. For example if you have a directory named abc with the files labelled as 1.jpg, 2.jpg etc say up to 15.jpg and you do file_list=os.listdir(abc) the file_list is not ordered as you expect but rather as file_list=['1.jpg', '11.jpg'---'15.jpg', '2.jpg]. If the order in which files are processed is important (presumably that's why you named them numerically) the order is not what you think it will be. You can avoid this by using "zeros" padding. For example if you have a list alist=['01', '03', '05', '10', '02','04', '06] and you run sort on it you get the order you wanted. alist=['01', '02' etc] because the first character is 0 which comes before 1. The amount of zeros padding you need is determined by the largest value in the list.For example if the largest is say between 100 and 1000 you need to pad single digits as 001, 002 ---010,011--100, 101 etc.

Writing outputs to log file and console

I tried joonty's answer, but I also got the

exec: 1: not found

error. This is what works best for me (confirmed to work in zsh also):

#!/bin/bash
LOG_FILE=/tmp/both.log
exec > >(tee ${LOG_FILE}) 2>&1
echo "this is stdout"
chmmm 77 /makeError

The file /tmp/both.log afterwards contains

this is stdout
chmmm command not found 

The /tmp/both.log is appended unless you remove the -a from tee.

Hint: >(...) is a process substitution. It lets the exec to the tee command as if it were a file.