Programs & Examples On #Mouseevent

A general tag for user-interface events that are generated by the mouse. This includes pressing/releasing a button, clicking (including double/triple-clicks), moving, dragging, etc.

jQuery get mouse position within an element

@AbdulRahim answer is almost correct. But I suggest the function below as substitute (for futher reference):

function getXY(evt, element) {
                var rect = element.getBoundingClientRect();
                var scrollTop = document.documentElement.scrollTop?
                                document.documentElement.scrollTop:document.body.scrollTop;
                var scrollLeft = document.documentElement.scrollLeft?                   
                                document.documentElement.scrollLeft:document.body.scrollLeft;
                var elementLeft = rect.left+scrollLeft;  
                var elementTop = rect.top+scrollTop;

                x = evt.pageX-elementLeft;
                y = evt.pageY-elementTop;

                return {x:x, y:y};
            }




            $('#main-canvas').mousemove(function(e){
                var m=getXY(e, this);
                console.log(m.x, m.y);
            });

How to close a web page on a button click, a hyperlink or a link button click?

Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.

Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close

    private void myNewButton_Click(object sender, EventArgs e) {
        this.Close();
    }

And that should be it.

The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.

How to completely DISABLE any MOUSE CLICK

You can add a simple css3 rule in the body or in specific div, use pointer-events: none; property.

change cursor to finger pointer

You can do this in CSS:

a.menu_links {
    cursor: pointer;
}

This is actually the default behavior for links. You must have either somehow overridden it elsewhere in your CSS, or there's no href attribute in there (it's missing from your example).

How to get the mouse position without events (without moving the mouse)?

You could try something similar to what Tim Down suggested - but instead of having elements for each pixel on the screen, create just 2-4 elements (boxes), and change their location, width, height dynamically to divide the yet possible locations on screen by 2-4 recursively, thus finding the mouse real location quickly.

For example - first elements take right and left half of screen, afterwards the upper and lower half. By now we already know in which quarter of screen the mouse is located, are able to repeat - discover which quarter of this space...

When to choose mouseover() and hover() function?

From the official jQuery documentation

  • .mouseover()
    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • .hover() Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

    Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);


  • .mouseenter()

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

    mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.


What this means

Because of this, .mouseover() is not the same as .hover(), for the same reason .mouseover() is not the same as .mouseenter().

$('selector').mouseover(over_function) // may fire multiple times

// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function) 

How to simulate a click by using x,y coordinates in JavaScript?

For security reasons, you can't move the mouse pointer with javascript, nor simulate a click with it.

What is it that you are trying to accomplish?

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I personally use Style It for inline-style in React or keep my style separately in a CSS or SASS file...

But if you are really interested doing it inline, look at the library, I share some of the usages below:

In the component:

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
        {`
          .intro {
            font-size: 40px;
          }
        `}

        <p className="intro">CSS-in-JS made simple -- just Style It.</p>
      </Style>
    );
  }
}

export default Intro;

Output:

    <p class="intro _scoped-1">
      <style type="text/css">
        ._scoped-1.intro {
          font-size: 40px;
        }
      </style>

      CSS-in-JS made simple -- just Style It.
    </p>


Also you can use JavaScript variables with hover in your CSS as below :

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    const fontSize = 13;

    return Style.it(`
      .intro {
        font-size: ${ fontSize }px;  // ES2015 & ES6 Template Literal string interpolation
      }
      .package {
        color: blue;
      }
      .package:hover {
        color: aqua;
      }
    `,
      <p className="intro">CSS-in-JS made simple -- just Style It.</p>
    );
  }
}

export default Intro;

And the result as below:

<p class="intro _scoped-1">
  <style type="text/css">
    ._scoped-1.intro {
      font-size: 13px;
    }
    ._scoped-1 .package {
      color: blue;
    }
    ._scoped-1 .package:hover {
      color: aqua;
    }
  </style>

  CSS-in-JS made simple -- just Style It.
</p>

How do I add a .click() event to an image?

Enclose <img> in <a> tag.

<a href="http://www.google.com.pk"><img src="smiley.gif"></a>

it will open link on same tab, and if you want to open link on new tab then use target="_blank"

<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>

Access to the path is denied

Maybe it'il help you.

string tempDirectoryPath = @"C:\Users\HOPE\Desktop\Test Folder";
string zipFilePath = @"C:\Users\HOPE\Desktop\7za920.zip";
Directory.CreateDirectory(tempDirectoryPath);
ZipFile.ExtractToDirectory(zipFilePath, tempDirectoryPath);

How does OkHttp get Json string?

As I observed in my code. If once the value is fetched of body from Response, its become blank.

String str = response.body().string();  // {response:[]}

String str1  = response.body().string();  // BLANK

So I believe after fetching once the value from body, it become empty.

Suggestion : Store it in String, that can be used many time.

Using grep to search for a string that has a dot in it

There are so many answers here suggesting to escape the dot with \. but I have been running into this issue over and over again: \. gives me the same result as .

However, these two expressions work for me:

$ grep -r 0\\.49 *

And:

$ grep -r 0[.]49 *

I'm using a "normal" bash shell on Ubuntu and Archlinux.

Edit, or, according to comments:

$ grep -r '0\.49' *

Note, the single-quotes doing the difference here.

Function overloading in Javascript - Best practices

Here is an approach that allows real method overloading using parameter types, shown below:

Func(new Point());
Func(new Dimension());
Func(new Dimension(), new Point());
Func(0, 0, 0, 0);

Edit (2018): Since this was written in 2011, the speed of direct method calls has greatly increased while the speed of overloaded methods have not.

It is not an approach I would recommend, but it is a worthwhile thought exercise to think about how you can solve these types of problems.


Here is a benchmark of the different approaches - https://jsperf.com/function-overloading. It shows that function overloading (taking types into account) can be around 13 times slower in Google Chrome's V8 as of 16.0(beta).

As well as passing an object (i.e. {x: 0, y: 0}), one can also take the C approach when appropriate, naming the methods accordingly. For example, Vector.AddVector(vector), Vector.AddIntegers(x, y, z, ...) and Vector.AddArray(integerArray). You can look at C libraries, such as OpenGL for naming inspiration.

Edit: I've added a benchmark for passing an object and testing for the object using both 'param' in arg and arg.hasOwnProperty('param'), and function overloading is much faster than passing an object and checking for properties (in this benchmark at least).

From a design perspective, function overloading is only valid or logical if the overloaded parameters correspond to the same action. So it stands to reason that there ought to be an underlying method that is only concerned with specific details, otherwise that may indicate inappropriate design choices. So one could also resolve the use of function overloading by converting data to a respective object. Of course one must consider the scope of the problem as there's no need in making elaborate designs if your intention is just to print a name, but for the design of frameworks and libraries such thought is justified.

My example comes from a Rectangle implementation - hence the mention of Dimension and Point. Perhaps Rectangle could add a GetRectangle() method to the Dimension and Point prototype, and then the function overloading issue is sorted. And what about primitives? Well, we have argument length, which is now a valid test since objects have a GetRectangle() method.

function Dimension() {}
function Point() {}

var Util = {};

Util.Redirect = function (args, func) {
  'use strict';
  var REDIRECT_ARGUMENT_COUNT = 2;

  if(arguments.length - REDIRECT_ARGUMENT_COUNT !== args.length) {
    return null;
  }

  for(var i = REDIRECT_ARGUMENT_COUNT; i < arguments.length; ++i) {
    var argsIndex = i-REDIRECT_ARGUMENT_COUNT;
    var currentArgument = args[argsIndex];
    var currentType = arguments[i];
    if(typeof(currentType) === 'object') {
      currentType = currentType.constructor;
    }
    if(typeof(currentType) === 'number') {
      currentType = 'number';
    }
    if(typeof(currentType) === 'string' && currentType === '') {
      currentType = 'string';
    }
    if(typeof(currentType) === 'function') {
      if(!(currentArgument instanceof currentType)) {
        return null;
      }
    } else {
      if(typeof(currentArgument) !== currentType) {
        return null;
      }
    } 
  }
  return [func.apply(this, args)];
}

function FuncPoint(point) {}
function FuncDimension(dimension) {}
function FuncDimensionPoint(dimension, point) {}
function FuncXYWidthHeight(x, y, width, height) { }

function Func() {
  Util.Redirect(arguments, FuncPoint, Point);
  Util.Redirect(arguments, FuncDimension, Dimension);
  Util.Redirect(arguments, FuncDimensionPoint, Dimension, Point);
  Util.Redirect(arguments, FuncXYWidthHeight, 0, 0, 0, 0);
}

Func(new Point());
Func(new Dimension());
Func(new Dimension(), new Point());
Func(0, 0, 0, 0);

Video auto play is not working in Safari and Chrome desktop browser

After using jQuery play() or DOM maniupulation as suggested by the other answers, it was not still working (Video wasn't autoplaying) in the Chrome for Android (Version 56.0).

As per this post in developers.google.com, From Chrome 53, the autoplay option is respected by the browser, if the video is muted.

So using autoplay muted attributes in video tag enables the video to be autoplayed in Chrome browsers from version 53.

Excerpt from the above link:

Muted autoplay for video is supported by Chrome for Android as of version 53. Playback will start automatically for a video element once it comes into view if both autoplay and muted are set[...]

<video autoplay muted>
    <source src="video.webm" type="video/webm" />
    <source src="video.mp4" type="video/mp4" />
</video>
  • Muted autoplay is supported by Safari on iOS 10 and later.
  • Autoplay, whether muted or not, is already supported on Android by Firefox and UC Browser: they do not block any kind of autoplay.

Websocket onerror - how to read error description?

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

This one's already accepted, but if there are any other dummies out there (like me) that didn't immediately get it from the presently accepted answer, here's a bit more detail.

The model class referenced by the ForeignKey needs to have a __unicode__ method within it, like here:

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

That made the difference for me, and should apply to the above scenario. This works on Django 1.0.2.

Selecting the first "n" items with jQuery

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

Difference between RUN and CMD in a Dockerfile

I found this article very helpful to understand the difference between them:

RUN - RUN instruction allows you to install your application and packages required for it. It executes any commands on top of the current image and creates a new layer by committing the results. Often you will find multiple RUN instructions in a Dockerfile.

CMD - CMD instruction allows you to set a default command, which will be executed only when you run container without specifying a command. If Docker container runs with a command, the default command will be ignored. If Dockerfile has more than one CMD instruction, all but last
CMD instructions are ignored.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I've made a short code to do that and I want to share it with you.

Here the main code:

public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{

  MailMessage email = new MailMessage();
  email.From = new MailAddress(from);
  email.To.Add(to);
  email.Subject = subject;
  email.Body = Message;
  SmtpClient smtp = new SmtpClient(host, port);
  smtp.UseDefaultCredentials = false;
  NetworkCredential nc = new NetworkCredential(from, password);
  smtp.Credentials = nc;
  smtp.EnableSsl = true;
  email.IsBodyHtml = true;
  email.Priority = MailPriority.Normal;
  email.BodyEncoding = Encoding.UTF8;

  if (file.Length > 0)
  {
    Attachment attachment;
    attachment = new Attachment(file);
    email.Attachments.Add(attachment);
  }

  // smtp.Send(email);
  smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
  string userstate = "sending ...";
  smtp.SendAsync(email, userstate);
}

private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
  string result = "";
  if (e.Cancelled)
  {    
    MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
  }
  else if (e.Error != null)
  {
    MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }
  else {
    MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }

}

In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example

using (OpenFileDialog attachement = new OpenFileDialog()
{
  Filter = "Exel Client|*.png",
  ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
  Send("[email protected]", "gmail_password", 
       "[email protected]", "just smile ", "mail with attachement",
       "smtp.gmail.com", 587, attachement.FileName);

}
}

How do I show my global Git configuration?

You can also use cat ~/.gitconfig.

PHP header redirect 301 - what are the implications?

The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)

After the redirect put exit(); to stop the rest of the script to execute

header("HTTP/1.1 301 Moved Permanently"); 
header("Location: /option-a"); 
exit();

Android Lint contentDescription warning

Since I need the ImageView to add an icon just for aesthetics I've added tools:ignore="ContentDescription" within each ImageView I had in my xml file.

I'm no longer getting any error messages

JavaScript backslash (\) in variables is causing an error

The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).

In order to output a literal backslash, you need to escape it. That means \\ will output a single backslash (and \\\\ will output two, and so on). The reason "aa ///\" doesn't work is because the backslash escapes the " (which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\" won't work, because the last backslash again escapes the quote.

Just remember, for each backslash you want to output, you need to give Javascript two.

What is "entropy and information gain"?

I really recommend you read about Information Theory, bayesian methods and MaxEnt. The place to start is this (freely available online) book by David Mackay:

http://www.inference.phy.cam.ac.uk/mackay/itila/

Those inference methods are really far more general than just text mining and I can't really devise how one would learn how to apply this to NLP without learning some of the general basics contained in this book or other introductory books on Machine Learning and MaxEnt bayesian methods.

The connection between entropy and probability theory to information processing and storing is really, really deep. To give a taste of it, there's a theorem due to Shannon that states that the maximum amount of information you can pass without error through a noisy communication channel is equal to the entropy of the noise process. There's also a theorem that connects how much you can compress a piece of data to occupy the minimum possible memory in your computer to the entropy of the process that generated the data.

I don't think it's really necessary that you go learning about all those theorems on communication theory, but it's not possible to learn this without learning the basics about what is entropy, how it's calculated, what is it's relationship with information and inference, etc...

How do I remove the last comma from a string using PHP?

its as simple as:

$commaseparated_string = name,name2,name3,;
$result = rtrim($commaseparated_string,',');

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

you can download and install db2client and looking for - db2jcc.jar - db2jcc_license_cisuz.jar - db2jcc_license_cu.jar - and etc. at C:\Program Files (x86)\IBM\SQLLIB\java

ng-if, not equal to?

I don't like "hacks" but in a quick pinch for a deadline I have done this

<li ng-if="edit === false && filtered.length === 0">
    <p ng-if="group.title != 'Dispatcher News'" style="padding: 5px">No links in group.</p>
</li>

Yes, I have another inner nested ng-if, I just didn't like too many conditions on one line.

What are MVP and MVC and what is the difference?

There is this nice video from Uncle Bob where he briefly explains MVC & MVP at the end.

IMO, MVP is an improved version of MVC where you basically separate the concern of what you're gonna show (the data) from how you're gonna show (the view). The presenter includes kinda the business logic of your UI, implicitly imposes what data should be presented and gives you a list of dumb view models. And when the time comes to show the data, you simply plug your view (probably includes the same id's) into your adapter and set the relevant view fields using those view models with a minimum amount of code being introduced (just using setters). Its main benefit is you can test your UI business logic against many/various views like showing items in a horizontal list or vertical list.

In MVC, we talk through interfaces (boundaries) to glue different layers. A controller is a plug-in to our architecture but it has no such a restriction to impose what to show. In that sense, MVP is kind of an MVC with a concept of views being pluggable to the controller over adapters.

I hope this helps better.

ImportError: No Module named simplejson

For anyone coming across this years later:

TL;DR check your pip version (2 vs 3)

I had this same issue and it was not fixed by running pip install simplejson despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.

> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)

Installing with the correct version of pip is as easy as using pip2:

> pip2 install simplejson

and then python 2 can import simplejson fine.

Embed website into my site

Put content from other site in iframe

<iframe src="/othersiteurl" width="100%" height="300">
  <p>Your browser does not support iframes.</p>
</iframe>

CSS3 transition doesn't work with display property

You cannot use height: 0 and height: auto to transition the height. auto is always relative and cannot be transitioned towards. You could however use max-height: 0 and transition that to max-height: 9999px for example.

Sorry I couldn't comment, my rep isn't high enough...

How to run .jar file by double click on Windows 7 64-bit?

This is my way:

  1. Create file bat (example openJar.bat).

    @echo off
    start javaw -jar "%1" %*
    exit
    
  2. Cut it and paste to C:\Program Files\Java\\bin (this step is unnecessary, but you should it).

  3. Right click jar file > Properties > Choose open with (Change button ) and select your file bat.
  4. Double click your jar file to test it.

Query for documents where array size is greater than 1

I believe this is the fastest query that answers your question, because it doesn't use an interpreted $where clause:

{$nor: [
    {name: {$exists: false}},
    {name: {$size: 0}},
    {name: {$size: 1}}
]}

It means "all documents except those without a name (either non existant or empty array) or with just one name."

Test:

> db.test.save({})
> db.test.save({name: []})
> db.test.save({name: ['George']})
> db.test.save({name: ['George', 'Raymond']})
> db.test.save({name: ['George', 'Raymond', 'Richard']})
> db.test.save({name: ['George', 'Raymond', 'Richard', 'Martin']})
> db.test.find({$nor: [{name: {$exists: false}}, {name: {$size: 0}}, {name: {$size: 1}}]})
{ "_id" : ObjectId("511907e3fb13145a3d2e225b"), "name" : [ "George", "Raymond" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225c"), "name" : [ "George", "Raymond", "Richard" ] }
{ "_id" : ObjectId("511907e3fb13145a3d2e225d"), "name" : [ "George", "Raymond", "Richard", "Martin" ] }
>

Creating a system overlay window (always on top)

by using service you can achieve this :

public class PopupService extends Service{

    private static final String TAG = PopupService.class.getSimpleName();
    WindowManager mWindowManager;
    View mView;
    String type ;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        registerOverlayReceiver();
        type = intent.getStringExtra("type");
        Utils.printLog("type = "+type);
        showDialog(intent.getStringExtra("msg"));
        return super.onStartCommand(intent, flags, startId);
    }

    private void showDialog(String aTitle)
    {
        if(type.equals("when screen is off") | type.equals("always"))
        {
            Utils.printLog("type = "+type);
            PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
            WakeLock mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "YourServie");
            mWakeLock.acquire();
            mWakeLock.release();
        }

        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mView = View.inflate(getApplicationContext(), R.layout.dialog_popup_notification_received, null);
        mView.setTag(TAG);

        int top = getApplicationContext().getResources().getDisplayMetrics().heightPixels / 2;

        LinearLayout dialog = (LinearLayout) mView.findViewById(R.id.pop_exit);
//        android.widget.LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) dialog.getLayoutParams();
//        lp.topMargin = top;
//        lp.bottomMargin = top;
//        mView.setLayoutParams(lp);

        final EditText etMassage = (EditText) mView.findViewById(R.id.editTextInPopupMessageReceived);

        ImageButton imageButtonSend = (ImageButton) mView.findViewById(R.id.imageButtonSendInPopupMessageReceived);
//        lp = (LayoutParams) imageButton.getLayoutParams();
//        lp.topMargin = top - 58;
//        imageButton.setLayoutParams(lp);
        imageButtonSend.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.printLog("clicked");
//                mView.setVisibility(View.INVISIBLE);
                if(!etMassage.getText().toString().equals(""))
                {
                    Utils.printLog("sent");
                    etMassage.setText("");
                }
            }
        });

        TextView close = (TextView) mView.findViewById(R.id.TextViewCloseInPopupMessageReceived);
        close.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                hideDialog();   
            }
        });

        TextView view = (TextView) mView.findViewById(R.id.textviewViewInPopupMessageReceived);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                hideDialog();   
            }
        });

        TextView message = (TextView) mView.findViewById(R.id.TextViewMessageInPopupMessageReceived);
        message.setText(aTitle);

        final WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT, 0, 0,
        WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
//                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON ,
        PixelFormat.RGBA_8888);

        mView.setVisibility(View.VISIBLE);
        mWindowManager.addView(mView, mLayoutParams);
        mWindowManager.updateViewLayout(mView, mLayoutParams);

    }

    private void hideDialog(){
        if(mView != null && mWindowManager != null){
            mWindowManager.removeView(mView);
            mView = null;
        }
    }
}

How to find the mysql data directory from command line in windows

public function variables($variable="")
{
  return empty($variable) ? mysql_query("SHOW VARIABLES") : mysql_query("SELECT @@$variable");
}

/*get datadir*/
$res = variables("datadir");

/*or get all variables*/
$res = variables();

HTML display result in text (input) field?

With .value and INPUT tag

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').value = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
    </FORM>

  </BODY>
</HTML>

with innerHTML and DIV

<HTML>
  <HEAD>
    <TITLE>Sum</TITLE>

    <script type="text/javascript">
      function sum()
      {

         var num1 = document.myform.number1.value;
         var num2 = document.myform.number2.value;
         var sum = parseInt(num1) + parseInt(num2);
         document.getElementById('add').innerHTML = sum;
      }
    </script>
  </HEAD>

  <BODY>
    <FORM NAME="myform">
      <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
      <INPUT TYPE="text" NAME="number2" VALUE=""/>
      <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
      <DIV  ID="add"></DIV>
    </FORM>

  </BODY>
</HTML>

How to hide html source & disable right click and text copy?

I think, here, right click is not mentioned, @Jishnu V S.

_x000D_
_x000D_
document.onkeydown = function(e) {
    if(e.keyCode == 123) {
     return false;
    }
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){
     return false;
    }
    if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){
     return false;
    }
    if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){
     return false;
    }

    if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)){
     return false;
    }      
 }
_x000D_
_x000D_
_x000D_

Create Log File in Powershell

A function that takes these principles a little further.

  1. Add's timestamps - can't have a log without timestamps.
  2. Add's a level (uses INFO by default) meaning you can highlight big issues.
  3. Allows for optional console output. If you don't set a log destination, it simply pumps it out.

    Function Write-Log {
        [CmdletBinding()]
        Param(
        [Parameter(Mandatory=$False)]
        [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
        [String]
        $Level = "INFO",
    
        [Parameter(Mandatory=$True)]
        [string]
        $Message,
    
        [Parameter(Mandatory=$False)]
        [string]
        $logfile
        )
    
        $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
        $Line = "$Stamp $Level $Message"
        If($logfile) {
            Add-Content $logfile -Value $Line
        }
        Else {
            Write-Output $Line
        }
    }
    

Can I stretch text using CSS?

Technically, no. But what you can do is use a font size that is as tall as you would like the stretched font to be, and then condense it horizontally with font-stretch.

Mac OS X - EnvironmentError: mysql_config not found

The problem in my case was that I was running the command inside a python virtual environment and it didn't had the path to /usr/local/mysql/bin though I have put it in the .bash_profile file. Just exporting the path in the virtual env worked for me.

For your info sql_config resides inside bin directory.

How to style a checkbox using CSS

Simple to implement and easily customizable solution

After a lot of search and testing I got this solution which is simple to implement and easier to customize. In this solution:

  1. You don't need external libraries and files
  2. You don't need to add extra HTML in your page
  3. You don't need to change checkbox names and id

Simple put the flowing CSS at the top of your page and all checkboxes style will change like this:

Enter image description here

_x000D_
_x000D_
input[type=checkbox] {
  transform: scale(1.5);
}

input[type=checkbox] {
  width: 30px;
  height: 30px;
  margin-right: 8px;
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  margin-left: 10px;
  padding-bottom: 5px;
  color: #00BFF0;
  width: 22px;
  height: 25px;
  visibility: visible;
  border: 1px solid #00BFF0;
  padding-left: 3px;
  border-radius: 5px;
}

input[type=checkbox]:checked:after {
  content: "\2714";
  padding: -5px;
  font-weight: bold;
}
_x000D_
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Checkbox</label>
_x000D_
_x000D_
_x000D_

Retrieving JSON Object Literal from HttpServletRequest

are you looking for this ?

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = request.getReader();
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } finally {
        reader.close();
    }
    System.out.println(sb.toString());
}

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

How to turn NaN from parseInt into 0 for an empty string?

Here is a tryParseInt method that I am using, this takes the default value as second parameter so it can be anything you require.

function tryParseInt(str, defaultValue) {
    return parseInt(str) == str ? parseInt(str) : defaultValue;
}

tryParseInt("", 0);//0 
tryParseInt("string", 0);//0 
tryParseInt("558", 0);//558

Apache Prefork vs Worker MPM

You can tell whether Apache is using preform or worker by issuing the following command

apache2ctl -l

In the resulting output, look for mentions of prefork.c or worker.c

How to set the opacity/alpha of a UIImage?

Set the opacity of its view it is showed in.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"SomeName.png"]];
imageView.alpha = 0.5; //Alpha runs from 0.0 to 1.0

Use this in an animation. You can change the alpha in an animation for an duration.

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
//Set alpha
[UIView commitAnimations];

Date Comparison using Java

This is one of the ways:

String toDate = "05/11/2010";

if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

A bit more easy interpretable:

String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;

if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

Oh, as a bonus, the JodaTime's variant:

String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();

if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

MySQL Error: #1142 - SELECT command denied to user

This error happened on my server when I imported a view with an invalid definer.

Removing the faulty view fixed the error.

The error message didn't say anything about the view in question, but was "complaining" about one of the tables, that was used in the view.

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

Input and output numpy arrays to h5py

h5py provides a model of datasets and groups. The former is basically arrays and the latter you can think of as directories. Each is named. You should look at the documentation for the API and examples:

http://docs.h5py.org/en/latest/quick.html

A simple example where you are creating all of the data upfront and just want to save it to an hdf5 file would look something like:

In [1]: import numpy as np
In [2]: import h5py
In [3]: a = np.random.random(size=(100,20))
In [4]: h5f = h5py.File('data.h5', 'w')
In [5]: h5f.create_dataset('dataset_1', data=a)
Out[5]: <HDF5 dataset "dataset_1": shape (100, 20), type "<f8">

In [6]: h5f.close()

You can then load that data back in using: '

In [10]: h5f = h5py.File('data.h5','r')
In [11]: b = h5f['dataset_1'][:]
In [12]: h5f.close()

In [13]: np.allclose(a,b)
Out[13]: True

Definitely check out the docs:

http://docs.h5py.org

Writing to hdf5 file depends either on h5py or pytables (each has a different python API that sits on top of the hdf5 file specification). You should also take a look at other simple binary formats provided by numpy natively such as np.save, np.savez etc:

http://docs.scipy.org/doc/numpy/reference/routines.io.html

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I also met the error message in raspberry pi 3, but my solution is reload kernel of camera after search on google, hope it can help you.

sudo modprobe bcm2835-v4l2

BTW, for this error please check your camera and file path is workable or not

How to display all elements in an arraylist?

Arraylist uses Iterator interface to traverse the elements Use this

public void display(ArrayList<Integer> v) {
        Iterator vEnum = v.iterator();
        System.out.println("\nElements in vector:");
        while (vEnum.hasNext()) {
            System.out.print(vEnum.next() + " ");
        }
    }

Squash my last X commits together using Git

Simple one-liner that always works, given that you are currently on the branch you want to squash, master is the branch it originated from, and the latest commit contains the commit message and author you wish to use:

git reset --soft $(git merge-base HEAD master) && git commit --reuse-message=HEAD@{1}

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How to set a Timer in Java?

Use this

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception

FAIL - Application at context path /Hello could not be started

Your web.xml ends with <web-app>, but must end with </web-app>

Which by the way is almost literally what the exception tells you.

Button Center CSS

when all else fails I just

<center> content </center>

I know its not "up to standards" any more, but if it works it works

mysql said: Cannot connect: invalid settings. xampp

Opsss. after I change user to 'admin', it doesn't have privelege to add database.. so I change back the user to 'root'.

Then I change the password from the browser.

  1. Go to http://localhost/security/ and then click on the link http://localhost/security/xamppsecurity.php . After that change pasword for superuser to 'root'.

  2. After that open your http://localhost/phpmyadmin/

    Now it works.

How to parse a JSON object to a TypeScript Object

If you use a TypeScript interface instead of a class, things are simpler:

export interface Employee {
    typeOfEmployee_id: number;
    department_id: number;
    permissions_id: number;
    maxWorkHours: number;
    employee_id: number;
    firstname: string;
    lastname: string;
    username: string;
    birthdate: Date;
    lastUpdate: Date;
}

let jsonObj: any = JSON.parse(employeeString); // string to generic object first
let employee: Employee = <Employee>jsonObj;

If you want a class, however, simple casting won't work. For example:

class Foo {
    name: string;
    public pump() { }
}

let jsonObj: any = JSON.parse('{ "name":"hello" }');
let fObj: Foo = <Foo>jsonObj;
fObj.pump(); // crash, method is undefined!

For a class, you'll have to write a constructor which accepts a JSON string/object and then iterate through the properties to assign each member manually, like this:

class Foo {
    name: string;

    constructor(jsonStr: string) {
        let jsonObj: any = JSON.parse(jsonStr);
        for (let prop in jsonObj) {
            this[prop] = jsonObj[prop];
        }
    }
}

let fObj: Foo = new Foo(theJsonString);

ImportError: No module named 'google'

  1. Close Anaconda/Spyder
  2. Open command prompt and run the below command
  3. conda update --all
  4. Start the app again and this time it should work.

Note - You need not have to uninstall/reinstall anything.

.NET Core vs Mono

This is no more .NET Core vs. Mono. It's unified.

Update as of November 2020 - .NET 5 released that unifies .NET Framework and .NET Core

.NET and Mono will be unified under .NET 6 that would be released in November 2021

  • .NET 6.0 will add net6.0-ios and net6.0-android.
  • The OS-specific names can include OS version numbers, like net6.0-ios14.

Check below articles:

Delete last commit in bitbucket

If you are not working with others (or are happy to cause them significant annoyance), then it is possible to remove commits from bitbucket branches.

If you're trying to change a non-master branch:

git reset HEAD^               # remove the last commit from the branch history
git push origin :branch_name  # delete the branch from bitbucket
git push origin branch_name   # push the branch back up again, without the last commit

if you're trying to change the master branch

In git generally, the master branch is not special - it's just a convention. However, bitbucket and github and similar sites usually require there to be a main branch (presumably because it's easier than writing more code to handle the event that a repository has no branches - not sure). So you need to create a new branch, and make that the main branch:

# on master:
git checkout -b master_temp  
git reset HEAD^              # undo the bad commit on master_temp
git push origin master_temp  # push the new master to Bitbucket

On Bitbucket, go to the repository settings, and change the "Main branch" to master_temp (on Github, change the "Default branch").

git push origin :master     # delete the original master branch from Bitbucket
git checkout master
git reset master_temp       # reset master to master_temp (removing the bad commit)
git push origin master      # re-upload master to bitbucket

Now go to Bitbucket, and you should see the history that you want. You can now go to the settings page and change the Main branch back to master.

This process will also work with any other history changes (e.g. git filter-branch). You just have to make sure to reset to appropriate commits, before the new history split off from the old.

edit: apparently you don't need to go to all this hassle on github, as you can force-push a reset branch.

Dealing with annoyed collaborators

Next time anyone tries to pull from your repository, (if they've already pulled the bad commit), the pull will fail. They will manually have to reset to a commit before the changed history, and then pull again.

git reset HEAD^
git pull

If they have pulled the bad commit, and committed on top of it, then they will have to reset, and then git cherry-pick the good commits that they want to create, effectively re-creating the whole branch without the bad commit.

If they never pulled the bad commit, then this whole process won't affect them, and they can pull as normal.

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

Make Sure to keep Your Google play services dependencies and Firebase dependencies to latest version.

Also check all your gradle files, module level and project level, there has to be only one common version of dependency across all modules. Can be solved by keeping those versions in project level gradle variable.

Check here for Google play services update version

Google Play Services Latest

Check here for Firebase updated version

Firebase Latest

Check here for Firebase updated version for Android

Firebase Android Latest

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

If you (or a helpful admin) runs Set-ExecutionPolicy as administrator, the policy will be set for all users. (I would suggest "remoteSigned" rather than "unrestricted" as a safety measure.)

NB.: On a 64-bit OS you need to run Set-ExecutionPolicy for 32-bit and 64-bit PowerShell separately.

Using Environment Variables with Vue.js

  1. Create two files in root folder (near by package.json) .env and .env.production
  2. Add variables to theese files with prefix VUE_APP_ eg: VUE_APP_WHATEVERYOUWANT
  3. serve uses .env and build uses .env.production
  4. In your components (vue or js), use process.env.VUE_APP_WHATEVERYOUWANT to call value
  5. Don't forget to restart serve if it is currently running
  6. Clear browser cache

Be sure you are using vue-cli version 3 or above

For more information: https://cli.vuejs.org/guide/mode-and-env.html

How can I check that two objects have the same set of property names?

If you want deep validation like @speculees, here's an answer using deep-keys (disclosure: I'm sort of a maintainer of this small package)

// obj1 should have all of obj2's properties
var deepKeys = require('deep-keys');
var _ = require('underscore');
assert(0 === _.difference(deepKeys(obj2), deepKeys(obj1)).length);

// obj1 should have exactly obj2's properties
var deepKeys = require('deep-keys');
var _ = require('lodash');
assert(0 === _.xor(deepKeys(obj2), deepKeys(obj1)).length);

or with chai:

var expect = require('chai').expect;
var deepKeys = require('deep-keys');
// obj1 should have all of obj2's properties
expect(deepKeys(obj1)).to.include.members(deepKeys(obj2));
// obj1 should have exactly obj2's properties
expect(deepKeys(obj1)).to.have.members(deepKeys(obj2));

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

Given you've set up a git daemon on <url> and an empty repository:

cd <localdir>
git init
git add .
git commit -m 'message'
git remote add origin <url>
git push -u origin master

Can I set background image and opacity in the same property?

#main {
    position: relative;
}
#main:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url(/wp-content/uploads/2010/11/tandem.jpg); 
    width: 100%;
    height: 100%;
    opacity : 0.2;
    z-index: -1;
}

What is the default initialization of an array in Java?

JLS clearly says

An array initializer creates an array and provides initial values for all its components.

and this is irrespective of whether the array is an instance variable or local variable or class variable.

Default values for primitive types : docs

For objects default values is null.

Filtering a list of strings based on contents

This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

How to convert int to float in python?

You can literally convert it into float using:


float_value = float(integer_value)

Likewise, you can convert an integer back to float datatype with:


integer_value = int(float_value)

Hope it helped. I advice you to read "Build-In Functions of Python" at this link: https://docs.python.org/2/library/functions.html

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

MySQL select with CONCAT condition

Use CONCAT_WS().

SELECT CONCAT_WS(' ',firstname,lastname) as firstlast FROM users 
WHERE firstlast = "Bob Michael Jones";

The first argument is the separator for the rest of the arguments.

Why AVD Manager options are not showing in Android Studio

I had installed Android studio and was not able to access the AVD Manager directly. I had to follow the steps as mentioned below:

  1. Created a blank project using Android Studio
  2. Once the Project is ready to use I tried open action using the shortcut ctrl+shift+a option and searched for AVD Manager AVD Manager
  3. On double clicking the AVD Manager I got a few errors in console about the missing libararies along with the link to install the neccessary dependencies. On clicking the links which was displayed with the error message few packages which were needed were installed. Once all the required packages were installed the AVD Manager icon becomes active.

enter image description here

Error: could not find function ... in R

If you are using parallelMap you'll need to export custom functions to the slave jobs, otherwise you get an error "could not find function ".

If you set a non-missing level on parallelStart the same argument should be passed to parallelExport, else you get the same error. So this should be strictly followed:

parallelStart(mode = "<your mode here>", N, level = "<task.level>")
parallelExport("<myfun>", level = "<task.level>")

Check if value exists in enum in TypeScript

There is a very simple and easy solution to your question:

var districtId = 210;

if (DistrictsEnum[districtId] != null) {

// Returns 'undefined' if the districtId not exists in the DistrictsEnum 
    model.handlingDistrictId = districtId;
}

using extern template (C++11)

Wikipedia has the best description

In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.

C++03 has this syntax to oblige the compiler to instantiate a template:

  template class std::vector<MyClass>;

C++11 now provides this syntax:

  extern template class std::vector<MyClass>;

which tells the compiler not to instantiate the template in this translation unit.

The warning: nonstandard extension used...

Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.

Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.

Javascript Array of Functions

up above we saw some with iteration. Let's do the same thing using forEach:

var funcs = [function () {
        console.log(1)
  },
  function () {
        console.log(2)
  }
];

funcs.forEach(function (func) {
  func(); // outputs  1, then 2
});
//for (i = 0; i < funcs.length; i++) funcs[i]();

How to use a table type in a SELECT FROM statement?

You can't do it in a single query inside the package - you can't mix the SQL and PL/SQL types, and would need to define the types in the SQL layer as Tony, Marcin and Thio have said.

If you really want this done locally, and you can index the table type by VARCHAR instead of BINARY_INTEGER, you can do something like this:

-- dummy ITEM table as we don't know what the real ones looks like
create table item(
    item_num number,
    currency varchar2(9)
)
/   

insert into item values(1,'GBP');
insert into item values(2,'AUD');
insert into item values(3,'GBP');
insert into item values(4,'AUD');
insert into item values(5,'CDN');

create package so_5165580 as
    type exch_row is record(
        exch_rt_eur number,
        exch_rt_usd number);
    type exch_tbl is table of exch_row index by varchar2(9);
    exch_rt exch_tbl;
    procedure show_items;
end so_5165580;
/

create package body so_5165580 as
    procedure populate_rates is
        rate exch_row;
    begin
        rate.exch_rt_eur := 0.614394;
        rate.exch_rt_usd := 0.8494;
        exch_rt('GBP') := rate;
        rate.exch_rt_eur := 0.9817;
        rate.exch_rt_usd := 1.3572;
        exch_rt('AUD') := rate;
    end;

    procedure show_items is
        cursor c0 is
            select i.*
            from item i;
    begin
        for r0 in c0 loop
            if exch_rt.exists(r0.currency) then
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' EUR ' || exch_rt(r0.currency).exch_rt_eur
                    || ' USD ' || exch_rt(r0.currency).exch_rt_usd);
            else
                dbms_output.put_line('Item ' || r0.item_num
                    || ' Currency ' || r0.currency
                    || ' ** no rates defined **');
            end if;
        end loop;
    end;
begin
    populate_rates;
end so_5165580;
/

So inside your loop, wherever you would have expected to use r0.exch_rt_eur you instead use exch_rt(r0.currency).exch_rt_eur, and the same for USD. Testing from an anonymous block:

begin
    so_5165580.show_items;
end;
/

Item 1 Currency GBP EUR .614394 USD .8494
Item 2 Currency AUD EUR .9817 USD 1.3572
Item 3 Currency GBP EUR .614394 USD .8494
Item 4 Currency AUD EUR .9817 USD 1.3572
Item 5 Currency CDN ** no rates defined **

Based on the answer Stef posted, this doesn't need to be in a package at all; the same results could be achieved with an insert statement. Assuming EXCH holds exchange rates of other currencies against the Euro, including USD with currency_key=1:

insert into detail_items
with rt as (select c.currency_cd as currency_cd,
        e.exch_rt as exch_rt_eur,
        (e.exch_rt / usd.exch_rt) as exch_rt_usd
    from exch e,
        currency c,
        (select exch_rt from exch where currency_key = 1) usd
    where c.currency_key = e.currency_key)
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

With items valued at 19.99 GBP and 25.00 AUD, you get detail_items:

DOC DOC_CURRENCY NET_VALUE         NET_VALUE_IN_USD  NET_VALUE_IN_EURO
--- ------------ ----------------- ----------------- -----------------
1   GBP          19.99             32.53611          23.53426
2   AUD          25                25.46041          18.41621

If you want the currency stuff to be more re-usable you could create a view:

create view rt as
select c.currency_cd as currency_cd,
    e.exch_rt as exch_rt_eur,
    (e.exch_rt / usd.exch_rt) as exch_rt_usd
from exch e,
    currency c,
    (select exch_rt from exch where currency_key = 1) usd
where c.currency_key = e.currency_key;

And then insert using values from that:

insert into detail_items
select i.doc,
    i.doc_currency,
    i.net_value,
    i.net_value / rt.exch_rt_usd AS net_value_in_usd,
    i.net_value / rt.exch_rt_eur as net_value_in_euro
from item i
join rt on i.doc_currency = rt.currency_cd;

Position buttons next to each other in the center of page

.wrapper{
  float: left;
  width: 100%;
  text-align: center;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.button{
  display:inline-block;
}
<div class="wrapper">
  <button class="button">Button1</button>
  <button class="button">Button2</button>
</div>

Automatically accept all SDK licences

Note: This is only for Mac users

I had same issue but none of the answers posted helped since there was no tools folder present in Library/Android/sdk. (I'm using Android 3.6.3 on Mac OS 10.14.4)

error screenshot

Below steps helped me to overcome licensing problem error:

  1. Open Android Studio
  2. Press cmd + shift + A. This opens Actions pop-up window.
  3. Search for SDK Manager and hit enter to open.
  4. This opens pop-up for Android SDK. Select some other version of Android apart from already installed one. (In my case Android 10.0 was already installed so I selected Android 9.0)
  5. Then select Apply button. This will install corresponding SDK.

Solution

  1. Now run your app it should work without any exception.

success screenshot

How can I see the raw SQL queries Django is running?

I put this function in a util file in one of the apps in my project:

import logging
import re

from django.db import connection

logger = logging.getLogger(__name__)

def sql_logger():
    logger.debug('TOTAL QUERIES: ' + str(len(connection.queries)))
    logger.debug('TOTAL TIME: ' + str(sum([float(q['time']) for q in connection.queries])))

    logger.debug('INDIVIDUAL QUERIES:')
    for i, query in enumerate(connection.queries):
        sql = re.split(r'(SELECT|FROM|WHERE|GROUP BY|ORDER BY|INNER JOIN|LIMIT)', query['sql'])
        if not sql[0]: sql = sql[1:]
        sql = [(' ' if i % 2 else '') + x for i, x in enumerate(sql)]
        logger.debug('\n### {} ({} seconds)\n\n{};\n'.format(i, query['time'], '\n'.join(sql)))

Then, when needed, I just import it and call it from whatever context (usually a view) is necessary, e.g.:

# ... other imports
from .utils import sql_logger

class IngredientListApiView(generics.ListAPIView):
    # ... class variables and such

    # Main function that gets called when view is accessed
    def list(self, request, *args, **kwargs):
        response = super(IngredientListApiView, self).list(request, *args, **kwargs)

        # Call our function
        sql_logger()

        return response

It's nice to do this outside the template because then if you have API views (usually Django Rest Framework), it's applicable there too.

Can you split a stream into two streams?

I stumbled across this question while looking for a way to filter certain elements out of a stream and log them as errors. So I did not really need to split the stream so much as attach a premature terminating action to a predicate with unobtrusive syntax. This is what I came up with:

public class MyProcess {
    /* Return a Predicate that performs a bail-out action on non-matching items. */
    private static <T> Predicate<T> withAltAction(Predicate<T> pred, Consumer<T> altAction) {
    return x -> {
        if (pred.test(x)) {
            return true;
        }
        altAction.accept(x);
        return false;
    };

    /* Example usage in non-trivial pipeline */
    public void processItems(Stream<Item> stream) {
        stream.filter(Objects::nonNull)
              .peek(this::logItem)
              .map(Item::getSubItems)
              .filter(withAltAction(SubItem::isValid,
                                    i -> logError(i, "Invalid")))
              .peek(this::logSubItem)
              .filter(withAltAction(i -> i.size() > 10,
                                    i -> logError(i, "Too large")))
              .map(SubItem::toDisplayItem)
              .forEach(this::display);
    }
}

Relation between CommonJS, AMD and RequireJS?

CommonJS is more than that - it's a project to define a common API and ecosystem for JavaScript. One part of CommonJS is the Module specification. Node.js and RingoJS are server-side JavaScript runtimes, and yes, both of them implement modules based on the CommonJS Module spec.

AMD (Asynchronous Module Definition) is another specification for modules. RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.

AMD is generally more used in client-side (in-browser) JavaScript development due to this, and CommonJS Modules are generally used server-side. However, you can use either module spec in either environment - for example, RequireJS offers directions for running in Node.js and browserify is a CommonJS Module implementation that can run in the browser.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

Difference between View and ViewGroup in Android

View

  1. View objects are the basic building blocks of User Interface(UI) elements in Android.
  2. View is a simple rectangle box which responds to the user's actions.
  3. Examples are EditText, Button, CheckBox etc..
  4. View refers to the android.view.View class, which is the base class of all UI classes.

ViewGroup

  1. ViewGroup is the invisible container. It holds View and ViewGroup
  2. For example, LinearLayout is the ViewGroup that contains Button(View), and other Layouts also.
  3. ViewGroup is the base class for Layouts.

jQuery addClass onClick

Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!

For example, you might use in css:

button:active {/*your style here*/}

Instead of (probably not working):

.active {/*style*/} (.active is not a pseudo-class)

Hope it helps!

Make content horizontally scroll inside a div

Same as what clairesuzy answered, except you can get a similar result by adding display: flex instead of white-space: nowrap. Using display: flex will collapse the img "margins", in case that behavior is preferred.

How to implement a property in an interface

You should use abstract class to initialize a property. You can't inititalize in Inteface .

How to execute UNION without sorting? (SQL)

The sort is used to eliminate the duplicates, and is implicit for DISTINCT and UNION queries (but not UNION ALL) - you could still specify the columns you'd prefer to order by if you need them sorted by specific columns.

For example, if you wanted to sort by the result sets, you could introduce an additional column, and sort by that first:

SELECT foo, bar, 1 as ResultSet
FROM Foo
WHERE bar = 1
UNION
SELECT foo, bar, 2 as ResultSet
FROM Foo
WHERE bar = 3
UNION
SELECT foo, bar, 3 as ResultSet
FROM Foo
WHERE bar = 2
ORDER BY ResultSet

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

Mock a constructor with parameter

Mockito has limitations testing final, static, and private methods.

with jMockit testing library, you can do few stuff very easy and straight-forward as below:

Mock constructor of a java.io.File class:

new MockUp<File>(){
    @Mock
    public void $init(String pathname){
        System.out.println(pathname);
        // or do whatever you want
    }
};
  • the public constructor name should be replaced with $init
  • arguments and exceptions thrown remains same
  • return type should be defined as void

Mock a static method:

  • remove static from the method mock signature
  • method signature remains same otherwise

Cygwin Make bash command not found

Follow these steps:

  1. Go to the installer again
  2. Do the initial setup.
  3. Under library - go to devel.
  4. under devel scroll and find make.
  5. install all of library with name make.
  6. click next, will take some time to install.
  7. this will solve the problem.

how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

Setting focus to iframe contents

document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();

Disable all Database related auto configuration in Spring Boot

I had the same problem here, solved like this:

Just add another application-{yourprofile}.yml where "yourprofile" could be "client".

In my case I just wanted to remove Redis in a Dev profile, so I added a application-dev.yml next to the main application.yml and it did the job.

In this file I put:

spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration

this should work with properties files as well.

I like the fact that there is no need to change the application code to do that.

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

How to join two sets in one line without using "|"

If by join you mean union, try this:

set(list(s) + list(t))

It's a bit of a hack, but I can't think of a better one liner to do it.

How do I determine the dependencies of a .NET application?

To browse .NET code dependencies, you can use the capabilities of the tool NDepend. The tool proposes:

For example such query can look like:

from m in Methods 
let depth = m.DepthOfIsUsing("NHibernate.NHibernateUtil.Entity(Type)") 
where depth  >= 0 && m.IsUsing("System.IDisposable")
orderby depth
select new { m, depth }

And its result looks like: (notice the code metric depth, 1 is for direct callers, 2 for callers of direct callers...) (notice also the Export to Graph button to export the query result to a Call Graph)

NDepend dependencies browsing through C# LINQ query

The dependency graph looks like:

NDepend Dependency Graph

The dependency matrix looks like:

NDepend Dependency Matrix

The dependency matrix is de-facto less intuitive than the graph, but it is more suited to browse complex sections of code like:

NDepend Matrix vs Graph

Disclaimer: I work for NDepend

Creating SVG elements dynamically with javascript inside HTML

Add this to html:

<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>

Try this function and adapt for you program:

var svgNS = "http://www.w3.org/2000/svg";  

function createCircle()
{
    var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
    myCircle.setAttributeNS(null,"id","mycircle");
    myCircle.setAttributeNS(null,"cx",100);
    myCircle.setAttributeNS(null,"cy",100);
    myCircle.setAttributeNS(null,"r",50);
    myCircle.setAttributeNS(null,"fill","black");
    myCircle.setAttributeNS(null,"stroke","none");

    document.getElementById("mySVG").appendChild(myCircle);
}     

Getting an option text/value with JavaScript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

How do I convert a float number to a whole number in JavaScript?

One more possible way — use XOR operation:

_x000D_
_x000D_
console.log(12.3 ^ 0); // 12
console.log("12.3" ^ 0); // 12
console.log(1.2 + 1.3 ^ 0); // 2
console.log(1.2 + 1.3 * 2 ^ 0); // 3
console.log(-1.2 ^ 0); // -1
console.log(-1.2 + 1 ^ 0); // 0
console.log(-1.2 - 1.3 ^ 0); // -2
_x000D_
_x000D_
_x000D_

Priority of bitwise operations is less then priority of math operations, it's useful. Try on https://jsfiddle.net/au51uj3r/

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

How to display loading image while actual image is downloading

Just add a background image to all images using css:

img {
  background: url('loading.gif') no-repeat;
}

Combining node.js and Python

I've had a lot of success using thoonk.js along with thoonk.py. Thoonk leverages Redis (in-memory key-value store) to give you feed (think publish/subscribe), queue and job patterns for communication.

Why is this better than unix sockets or direct tcp sockets? Overall performance may be decreased a little, however Thoonk provides a really simple API that simplifies having to manually deal with a socket. Thoonk also helps make it really trivial to implement a distributed computing model that allows you to scale your python workers to increase performance, since you just spin up new instances of your python workers and connect them to the same redis server.

Using Spring RestTemplate in generic method with generic parameter

As Sotirios explains, you can not use the ParameterizedTypeReference, but ParameterizedTypeReference is used only to provide Type to the object mapper, and as you have the class that is removed when type erasure happens, you can create your own ParameterizedType and pass that to RestTemplate, so that the object mapper can reconstruct the object you need.

First you need to have the ParameterizedType interface implemented, you can find an implementation in Google Gson project here. Once you add the implementation to your project, you can extend the abstract ParameterizedTypeReference like this:

class FakeParameterizedTypeReference<T> extends ParameterizedTypeReference<T> {

@Override
public Type getType() {
    Type [] responseWrapperActualTypes = {MyClass.class};
    ParameterizedType responseWrapperType = new ParameterizedTypeImpl(
        ResponseWrapper.class,
        responseWrapperActualTypes,
        null
        );
    return responseWrapperType;
    }
}

And then you can pass that to your exchange function:

template.exchange(
    uri,
    HttpMethod.POST,
    null,
    new FakeParameterizedTypeReference<ResponseWrapper<T>>());

With all the type information present object mapper will properly construct your ResponseWrapper<MyClass> object

how to get the attribute value of an xml node using java

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

we Can try this code using method

Cannot invoke an expression whose type lacks a call signature

I had the same issue with numeral, a JS library. The fix was to install the typings again with this command:

npm install --save @types/numeral

How to get a List<string> collection of values from app.config in WPF?

There's actually a very little known class in the BCL for this purpose exactly: CommaDelimitedStringCollectionConverter. It serves as a middle ground of sorts between having a ConfigurationElementCollection (as in Richard's answer) and parsing the string yourself (as in Adam's answer).

For example, you could write the following configuration section:

public class MySection : ConfigurationSection
{
    [ConfigurationProperty("MyStrings")]
    [TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
    public CommaDelimitedStringCollection MyStrings
    {
        get { return (CommaDelimitedStringCollection)base["MyStrings"]; }
    }
}

You could then have an app.config that looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="foo" type="ConsoleApplication1.MySection, ConsoleApplication1"/>
  </configSections>
  <foo MyStrings="a,b,c,hello,world"/>
</configuration>

Finally, your code would look like this:

var section = (MySection)ConfigurationManager.GetSection("foo");
foreach (var s in section.MyStrings)
    Console.WriteLine(s); //for example

EL access a map value by Integer key

If you just happen to have a Map with Integer keys you cannot change, you could write a custom EL function to convert a Long to Integer. This would allow you to do something like:

<c:out value="${map[myLib:longToInteger(1)]}"/>

How do I compute derivative using Numpy?

To calculate gradients, the machine learning community uses Autograd:

"Efficiently computes derivatives of numpy code."

To install:

pip install autograd

Here is an example:

import autograd.numpy as np
from autograd import grad

def fct(x):
    y = x**2+1
    return y

grad_fct = grad(fct)
print(grad_fct(1.0))

It can also compute gradients of complex functions, e.g. multivariate functions.

Explicit vs implicit SQL joins

Performance wise, they are exactly the same (at least in SQL Server) but be aware that they are deprecating this join syntax and it's not supported by sql server2005 out of the box.

I think you are thinking of the deprecated *= and =* operators vs. "outer join".

I have just now tested the two formats given, and they work properly on a SQL Server 2008 database. In my case they yielded identical execution plans, but I couldn't confidently say that this would always be true.

python pandas convert index to datetime

It should work as expected. Try to run the following example.

import pandas as pd
import io

data = """value          
"2015-09-25 00:46"    71.925000
"2015-09-25 00:47"    71.625000
"2015-09-25 00:48"    71.333333
"2015-09-25 00:49"    64.571429
"2015-09-25 00:50"    72.285714"""

df = pd.read_table(io.StringIO(data), delim_whitespace=True)

# Converting the index as date
df.index = pd.to_datetime(df.index)

# Extracting hour & minute
df['A'] = df.index.hour
df['B'] = df.index.minute
df

#                          value  A   B
# 2015-09-25 00:46:00  71.925000  0  46
# 2015-09-25 00:47:00  71.625000  0  47
# 2015-09-25 00:48:00  71.333333  0  48
# 2015-09-25 00:49:00  64.571429  0  49
# 2015-09-25 00:50:00  72.285714  0  50

Import text file as single character string

readChar doesn't have much flexibility so I combined your solutions (readLines and paste).

I have also added a space between each line:

con <- file("/Users/YourtextFile.txt", "r", blocking = FALSE)
singleString <- readLines(con) # empty
singleString <- paste(singleString, sep = " ", collapse = " ")
close(con)

PostgreSQL "DESCRIBE TABLE"

When your table is not part of the default schema, you should write:

\d+ schema_name.table_name

Otherwise, you would get the error saying that "the relation doesn not exist."

How to work with complex numbers in C?

Complex types are in the C language since C99 standard (-std=c99 option of GCC). Some compilers may implement complex types even in more earlier modes, but this is non-standard and non-portable extension (e.g. IBM XL, GCC, may be intel,... ).

You can start from http://en.wikipedia.org/wiki/Complex.h - it gives a description of functions from complex.h

This manual http://pubs.opengroup.org/onlinepubs/009604499/basedefs/complex.h.html also gives some info about macros.

To declare a complex variable, use

  double _Complex  a;        // use c* functions without suffix

or

  float _Complex   b;        // use c*f functions - with f suffix
  long double _Complex c;    // use c*l functions - with l suffix

To give a value into complex, use _Complex_I macro from complex.h:

  float _Complex d = 2.0f + 2.0f*_Complex_I;

(actually there can be some problems here with (0,-0i) numbers and NaNs in single half of complex)

Module is cabs(a)/cabsl(c)/cabsf(b); Real part is creal(a), Imaginary is cimag(a). carg(a) is for complex argument.

To directly access (read/write) real an imag part you may use this unportable GCC-extension:

 __real__ a = 1.4;
 __imag__ a = 2.0;
 float b = __real__ a;

How to delete all instances of a character in a string in python?

>>> x = 'it is icy'.replace('i', '', 1)
>>> x
't is icy'

Since your code would only replace the first instance, I assumed that's what you wanted. If you want to replace them all, leave off the 1 argument.

Since you cannot replace the character in the string itself, you have to reassign it back to the variable. (Essentially, you have to update the reference instead of modifying the string.)

DELETE ... FROM ... WHERE ... IN

Try adding parentheses around the row in table1 e.g.

DELETE 
  FROM table1
 WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);

The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.

Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:

MERGE INTO table1 AS t1
   USING table2 AS s1
      ON t1.stn = s1.stn
         AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;

Adjusting and image Size to fit a div (bootstrap)

Just a heads up that Bootstrap 4 now uses img-fluid instead of img-responsive, so double check which version you're using if you're having problems.

Sleep for milliseconds

In C++11, you can do this with standard library facilities:

#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(x));

Clear and readable, no more need to guess at what units the sleep() function takes.

How to add new column to an dataframe (to the front not end)?

cbind inherents order by its argument order.

User your first column(s) as your first argument

cbind(fst_col , df)

  fst_col   df_col1   df_col2
1 0             0.2      -0.1
2 0             0.2      -0.1
3 0             0.2      -0.1
4 0             0.2      -0.1
5 0             0.2      -0.1

cbind(df, last_col)

  df_col1   df_col2  last_col
1 0.2      -0.1             0
2 0.2      -0.1             0
3 0.2      -0.1             0
4 0.2      -0.1             0
5 0.2      -0.1             0

Sass .scss: Nesting and multiple classes?

Christoph's answer is perfect. Sometimes however you may want to go more classes up than one. In this case you could try the @at-root and #{} css features which would enable two root classes to sit next to each other using &.

This wouldn't work (due to the nothing before & rule):

_x000D_
_x000D_
container {_x000D_
    background:red;_x000D_
    color:white;_x000D_
    _x000D_
    .desc& {_x000D_
      background: blue;_x000D_
    }_x000D_
_x000D_
    .hello {_x000D_
        padding-left:50px;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

But this would (using @at-root plus #{&}):

_x000D_
_x000D_
container {_x000D_
    background:red;_x000D_
    color:white;_x000D_
    _x000D_
    @at-root .desc#{&} {_x000D_
      background: blue;_x000D_
    }_x000D_
_x000D_
    .hello {_x000D_
        padding-left:50px;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How to list the files in current directory?

There is nothing wrong with your code. It should list all of the files and directories directly contained by the nominated directory.

The problem is most likely one of the following:

  • The "." directory is not what you expect it to be. The "." pathname actually means the "current directory" or "working directory" for the JVM. You can verify what directory "." actually is by printing out dir.getCanonicalPath().

  • You are misunderstanding what dir.listFiles() returns. It doesn't return all objects in the tree beneath dir. It only returns objects (files, directories, symlinks, etc) that are directly in dir.

The ".classpath" file suggests that you are looking at an Eclipse project directory, and Eclipse projects are normally configured with the Java files in a subdirectory such as "./src". I wouldn't expect to see any Java source code in the "." directory.


Can anyone explain to me why src isn't the current folder?"

Assuming that you are launching an application in Eclipse, then the current folder defaults to the project directory. You can change the default current directory via one of the panels in the Launcher configuration wizard.

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

Apply global variable to Vuejs

In VueJS 3 with createApp() you can use app.config.globalProperties

Like this:

const app = createApp(App);

app.config.globalProperties.foo = 'bar';

app.use(store).use(router).mount('#app');

and call your variable like this:

app.component('child-component', {
  mounted() {
    console.log(this.foo) // 'bar'
  }
})

doc: https://v3.vuejs.org/api/application-config.html#warnhandler

If your data is reactive, you may want to use VueX.

MySQL: how to get the difference between two timestamps in seconds

How about "TIMESTAMPDIFF":

SELECT TIMESTAMPDIFF(SECOND,'2009-05-18','2009-07-29') from `post_statistics`

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timestampdiff

Convert JsonNode into POJO

String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
    new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);

If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)

mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

Ok, so this might not fix your issue but it definitely worked for me.

So you've created your Mysql user I take it? Go to user privileges on PhpMyAdmin and click edit next to the user your using for Symfony. Scroll down to near the bottom and where it says which host you want to use make sure you've selected LocalHost not % Any.

Then in your config file swap 127.0.0.1 for localhost. Hopefully that will work for you. Just worked for me as I was having the same issue.

How to append to New Line in Node.js

use \r\n combination to append a new line in node js

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

Strip off URL parameter with PHP

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

Second line will just replace && to &

Check whether an array is empty

There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:

$errors = array_filter($errors);

if (!empty($errors)) {
}

array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.

Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.

Hyphen, underscore, or camelCase as word delimiter in URIs?

It is recommended to use the spinal-case (which is highlighted by RFC3986), this case is used by Google, PayPal, and other big companies.

source:- https://blog.restcase.com/5-basic-rest-api-design-guidelines/

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

How to clear cache of Eclipse Indigo

You can always create a new Eclipse workspace. The Eclipse.exe -clean option is not sufficient in some cases, for example, if the local history becomes a problem.

Edit:

Eclipse is mostly a collection of third party plugins. And each of those plugins can add some extra useful, useless or problematic information to the central Eclipse workspace meta-data folder.

The problem is that not every plugin participates during the user-issued cleanup routine. Therefore, I'd say that it is a problem in the system design of Eclipse, that it allows plugins to misbehave like this.

And therefore, I'd recommend to make yourself comfortable with the idea of using multiple workspaces and linking-in external project entities into each workspace. Because, this is the only workaround for the given system design, to handle faulty plugins that spam your workspace.

Start an external application from a Google Chrome Extension?

Previously, you would do this through NPAPI plugins.

However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.

Adding days to a date in Python

Sometimes we need to use searching by from date & to date. If we use date__range then we need to add 1 day to to_date otherwise queryset will be empty.

Example:

from datetime import timedelta  

from_date  = parse_date(request.POST['from_date'])

to_date    = parse_date(request.POST['to_date']) + timedelta(days=1)

attendance_list = models.DailyAttendance.objects.filter(attdate__range = [from_date, to_date])

Android: No Activity found to handle Intent error? How it will resolve

in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)

<activity
        android:name=".MyBrowser"
        android:label="MyBrowser Activity" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="com.dsociety.activities.MyBrowser" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
        </intent-filter>
    </activity>

when i code the following, the same Exception is thrown at run time :

Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com"));    // should be http://www.google.com
startActivity(intent);

Write to file, but overwrite it if it exists

Despite NylonSmile's answer, which is "sort of" correct.. I was unable to overwrite files, in this manner..

echo "i know about Pipes, girlfriend" > thatAnswer

zsh: file exists: thatAnswer

to solve my issues.. I had to use... >!, á la..

[[ $FORCE_IT == 'YES' ]] && echo "$@" >! "$X" || echo "$@" > "$X"

Obviously, be careful with this...

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

How to style components using makeStyles and still have lifecycle methods in Material UI?

What we ended up doing is stopped using the class components and created Functional Components, using useEffect() from the Hooks API for lifecycle methods. This allows you to still use makeStyles() with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.

Example:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: theme.spacing(1)
  },
  highlight: {
    backgroundColor: 'red',
  }
}));

// Highlight is a bool
const Welcome = ({highlight}) => { 
  const [userName, setUserName] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  useEffect(() => {
    axios.get('example.com/api/username/12')
         .then(res => setUserName(res.userName));
  }, []);

  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
   </Container>
   );
  }
}

export default Welcome;

Python iterating through object attributes

Iterate over an objects attributes in python:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"    

for attr, value in C.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Prints:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:

Oracle "(+)" Operator

The (+) operator indicates an outer join. This means that Oracle will still return records from the other side of the join even when there is no match. For example if a and b are emp and dept and you can have employees unassigned to a department then the following statement will return details of all employees whether or not they've been assigned to a department.

select * from emp, dept where emp.dept_id=dept.dept_id(+)

So in short, removing the (+) may make a significance difference but you might not notice for a while depending on your data!

remove None value from a list without removing the 0 value

Iteration vs Space, usage could be an issue. In different situations profiling may show either to be "faster" and/or "less memory" intensive.

# first
>>> L = [0, 23, 234, 89, None, 0, 35, 9, ...]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9, ...]

# second
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> for i in range(L.count(None)): L.remove(None)
[0, 23, 234, 89, 0, 35, 9, ...]

The first approach (as also suggested by @jamylak, @Raymond Hettinger, and @Dipto) creates a duplicate list in memory, which could be costly of memory for a large list with few None entries.

The second approach goes through the list once, and then again each time until a None is reached. This could be less memory intensive, and the list will get smaller as it goes. The decrease in list size could have a speed up for lots of None entries in the front, but the worst case would be if lots of None entries were in the back.

The second approach would likely always be slower than the first approach. That does not make it an invalid consideration.

Parallelization and in-place techniques are other approaches, but each have their own complications in Python. Knowing the data and the runtime use-cases, as well profiling the program are where to start for intensive operations or large data.

Choosing either approach will probably not matter in common situations. It becomes more of a preference of notation. In fact, in those uncommon circumstances, numpy (example if L is numpy.array: L = L[L != numpy.array(None) (from here)) or cython may be worthwhile alternatives instead of attempting to micromanage Python optimizations.

How to determine if a string is a number with C++?

Few months ago, I implemented a way to determine if any string is integer, hexadecimal or double.

enum{
        STRING_IS_INVALID_NUMBER=0,
        STRING_IS_HEXA,
        STRING_IS_INT,
        STRING_IS_DOUBLE
};

bool isDigit(char c){
    return (('0' <= c) && (c<='9'));
}

bool isHexaDigit(char c){
    return ((('0' <= c) && (c<='9')) || ((tolower(c)<='a')&&(tolower(c)<='f')));
}


char *ADVANCE_DIGITS(char *aux_p){

    while(CString::isDigit(*aux_p)) aux_p++;
    return aux_p;
}

char *ADVANCE_HEXADIGITS(char *aux_p){

    while(CString::isHexaDigit(*aux_p)) aux_p++;
    return aux_p;
}


int isNumber(const string & test_str_number){
    bool isHexa=false;
    char *str = (char *)test_str_number.c_str();

    switch(*str){
    case '-': str++; // is negative number ...
               break;
    case '0': 
              if(tolower(*str+1)=='x')  {
                  isHexa = true;
                  str+=2;
              }
              break;
    default:
            break;
    };

    char *start_str = str; // saves start position...
    if(isHexa) { // candidate to hexa ...
        str = ADVANCE_HEXADIGITS(str);
        if(str == start_str)
            return STRING_IS_INVALID_NUMBER;

        if(*str == ' ' || *str == 0) 
            return STRING_IS_HEXA;

    }else{ // test if integer or float
        str = ADVANCE_DIGITS(str);
        if(*str=='.') { // is candidate to double
            str++;
            str = ADVANCE_DIGITS(str);
            if(*str == ' ' || *str == 0)
                return STRING_IS_DOUBLE;

            return STRING_IS_INVALID_NUMBER;
        }

        if(*str == ' ' || *str == 0)
            return STRING_IS_INT;

    }

    return STRING_IS_INVALID_NUMBER;


}

Then in your program you can easily convert the number in function its type if you do the following,

string val; // the string to check if number...

switch(isNumber(val)){
   case STRING_IS_HEXA: 
   // use strtol(val.c_str(), NULL, 16); to convert it into conventional hexadecimal
   break;
   case STRING_IS_INT: 
   // use (int)strtol(val.c_str(), NULL, 10); to convert it into conventional integer
   break;
   case STRING_IS_DOUBLE:
   // use atof(val.c_str()); to convert it into conventional float/double
   break;
}

You can realise that the function will return a 0 if the number wasn't detected. The 0 it can be treated as false (like boolean).

How to add constraints programmatically using Swift

Would like to add some theoretical concept to Imanou Petit’s answer, so that one can understand how auto layout works.

To understand auto layout consider your view as rubber's object which is shrinked initially.

To place an object on screen we need 4 mandatory things :

  • X coordinate of object (horizontal position).

  • Y coordinate of object (vertical position )

  • Object’s Width

  • Object’s Height.

1 X coordinate: There are multiple ways of giving x coordinates to a view.

Such as Leading constraint, Trailing constraint , Horizontally centre etc.

2 Y coordinate: There are multiple ways of giving y coordinates to a view :

Such as Top constraint, Bottom constraint , Vertical centre etc.

3 Object's width: There are two ways of giving width constrain to a view :

a. Add fixed width constraint (consider this constraint as iron rod of fixed width and you have hooked your rubber’s object horizontally with it so rubber’s object don’t shrink or expand)

b. Do not add any width constraint but add x coordinate constraint to both end of view trailing and leading, these two constraints will expand/shrink your rubber’s object by pulling/pushing it from both end, leading and trailing.

4 Object's height: Similar to width, there are two ways of giving height constraint to a view as well :

a. Add fixed height constraint (consider this constraints as iron rod of fixed height and you have hooked your rubber’s object vertically with it so rubber’s object don’t shrink or expand)

b. Do not add any height constraint but add x coordinate constraint to both end of view top and bottom, these two constraints will expand/shrink your rubber’s object pulling/pushing it from both end, top and bottom.

Make a UIButton programmatically in Swift

Swift: Ui Button create programmatically,

var button: UIButton = UIButton(type: .Custom)

button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0)

button.addTarget(self, action: #selector(self.aMethod), forControlEvents: .TouchUpInside)

button.tag=2

button.setTitle("Hallo World", forState: .Normal)

view.addSubview(button)


func aMethod(sender: AnyObject) {
    print("you clicked on button \(sender.tag)")
}

Animate element to auto height with jQuery

Basically the height auto is only available for you after the element is rendered. If you set a fixed height, or if your element is not displayed you can't access it without any tricks.

Luckily there are some tricks you may use.

Clone the element, display it outside of the view give it height auto and you can take it from the clone and use it later for the main element. I use this function and seems to work well.

jQuery.fn.animateAuto = function(prop, speed, callback){
    var elem, height, width;

    return this.each(function(i, el){
        el = jQuery(el), elem =    el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
        height = elem.css("height"),
        width = elem.css("width"),
        elem.remove();

        if(prop === "height")
            el.animate({"height":height}, speed, callback);
        else if(prop === "width")
            el.animate({"width":width}, speed, callback);  
        else if(prop === "both")
            el.animate({"width":width,"height":height}, speed, callback);
    });   
}

USAGE:

$(".animateHeight").bind("click", function(e){
    $(".test").animateAuto("height", 1000); 
});

$(".animateWidth").bind("click", function(e){
    $(".test").animateAuto("width", 1000);  
});

$(".animateBoth").bind("click", function(e){
    $(".test").animateAuto("both", 1000); 
});

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

I took all these answers and wrote a script to 1. validate each of the results (see assertion below) and 2. see which is the fastest. Code and results are below:

# Imports
import numpy as np
import scipy.sparse as sp
from scipy.spatial.distance import squareform, pdist
from sklearn.metrics.pairwise import linear_kernel
from sklearn.preprocessing import normalize
from sklearn.metrics.pairwise import cosine_similarity

# Create an adjacency matrix
np.random.seed(42)
A = np.random.randint(0, 2, (10000, 100)).astype(float).T

# Make it sparse
rows, cols = np.where(A)
data = np.ones(len(rows))
Asp = sp.csr_matrix((data, (rows, cols)), shape = (rows.max()+1, cols.max()+1))

print "Input data shape:", Asp.shape

# Define a function to calculate the cosine similarities a few different ways
def calc_sim(A, method=1):
    if method == 1:
        return 1 - squareform(pdist(A, metric='cosine'))
    if method == 2:
        Anorm = A / np.linalg.norm(A, axis=-1)[:, np.newaxis]
        return np.dot(Anorm, Anorm.T)
    if method == 3:
        Anorm = A / np.linalg.norm(A, axis=-1)[:, np.newaxis]
        return linear_kernel(Anorm)
    if method == 4:
        similarity = np.dot(A, A.T)

        # squared magnitude of preference vectors (number of occurrences)
        square_mag = np.diag(similarity)

        # inverse squared magnitude
        inv_square_mag = 1 / square_mag

        # if it doesn't occur, set it's inverse magnitude to zero (instead of inf)
        inv_square_mag[np.isinf(inv_square_mag)] = 0

        # inverse of the magnitude
        inv_mag = np.sqrt(inv_square_mag)

        # cosine similarity (elementwise multiply by inverse magnitudes)
        cosine = similarity * inv_mag
        return cosine.T * inv_mag
    if method == 5:
        '''
        Just a version of method 4 that takes in sparse arrays
        '''
        similarity = A*A.T
        square_mag = np.array(A.sum(axis=1))
        # inverse squared magnitude
        inv_square_mag = 1 / square_mag

        # if it doesn't occur, set it's inverse magnitude to zero (instead of inf)
        inv_square_mag[np.isinf(inv_square_mag)] = 0

        # inverse of the magnitude
        inv_mag = np.sqrt(inv_square_mag).T

        # cosine similarity (elementwise multiply by inverse magnitudes)
        cosine = np.array(similarity.multiply(inv_mag))
        return cosine * inv_mag.T
    if method == 6:
        return cosine_similarity(A)

# Assert that all results are consistent with the first model ("truth")
for m in range(1, 7):
    if m in [5]: # The sparse case
        np.testing.assert_allclose(calc_sim(A, method=1), calc_sim(Asp, method=m))
    else:
        np.testing.assert_allclose(calc_sim(A, method=1), calc_sim(A, method=m))

# Time them:
print "Method 1"
%timeit calc_sim(A, method=1)
print "Method 2"
%timeit calc_sim(A, method=2)
print "Method 3"
%timeit calc_sim(A, method=3)
print "Method 4"
%timeit calc_sim(A, method=4)
print "Method 5"
%timeit calc_sim(Asp, method=5)
print "Method 6"
%timeit calc_sim(A, method=6)

Results:

Input data shape: (100, 10000)
Method 1
10 loops, best of 3: 71.3 ms per loop
Method 2
100 loops, best of 3: 8.2 ms per loop
Method 3
100 loops, best of 3: 8.6 ms per loop
Method 4
100 loops, best of 3: 2.54 ms per loop
Method 5
10 loops, best of 3: 73.7 ms per loop
Method 6
10 loops, best of 3: 77.3 ms per loop

Python None comparison: should I use "is" or ==?

Summary:

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

Explanation:

You can have custom classes where my_var == None will return True

e.g:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is checks for object identity. There is only 1 object None, so when you do my_var is None, you're checking whether they actually are the same object (not just equivalent objects)

In other words, == is a check for equivalence (which is defined from object to object) whereas is checks for object identity:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects

URL encoding in Android

Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:

for (int i = 0; i < urlAsString.length(); i++) {
    if (urlAsString.charAt(i) > 255) {
        urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
    }
}
encodedURL = urlAsString;

How to iterate for loop in reverse order in swift?

as for Swift 2.2 , Xcode 7.3 (10,June,2016) :

for (index,number) in (0...10).enumerate() {
    print("index \(index) , number \(number)")
}

for (index,number) in (0...10).reverse().enumerate() {
    print("index \(index) , number \(number)")
}

Output :

index 0 , number 0
index 1 , number 1
index 2 , number 2
index 3 , number 3
index 4 , number 4
index 5 , number 5
index 6 , number 6
index 7 , number 7
index 8 , number 8
index 9 , number 9
index 10 , number 10


index 0 , number 10
index 1 , number 9
index 2 , number 8
index 3 , number 7
index 4 , number 6
index 5 , number 5
index 6 , number 4
index 7 , number 3
index 8 , number 2
index 9 , number 1
index 10 , number 0

How to install popper.js with Bootstrap 4?

Two different ways I got this working.

Option 1: Add these 3 <script> tags to your .html file, just before the closing </body> tag:

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> 

Option 2 (Option 2 works with Angular, not sure about other frameworks)

Step 1: Install the 3 libraries using NPM:

npm install bootstrap --save

npm install popper.js --save

npm install jquery --save

Step 2: Update the script: array(s) in your angular.json file like this:

"scripts": ["node_modules/jquery/dist/jquery.min.js", "node_modules/popper.js/dist/umd/popper.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js"]

(thanks to @rakeshk-khanapure above in the comments)

Creating a chart in Excel that ignores #N/A or blank cells

If you use PowerPivot and PivotChart, you will exclude non-existing rows.

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

How do I get user IP address in django?

here is a short one liner to accomplish this:

request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '')).split(',')[0].strip()

How to fix '.' is not an internal or external command error

Just leave out the "dot-slash" ./:

D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"

Though, if you wanted to, you could use .\ and it would work.

D:\Gesture Recognition\Gesture Recognition\Debug>.\"Gesture Recognition.exe"

Does a valid XML file require an XML declaration?

Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.

Best way to show a loading/progress indicator?

Use ProgressDialog

ProgressDialog.show(Context context, CharSequence title, CharSequence message);

enter image description here

However this is considered as an anti pattern today (2013): http://www.youtube.com/watch?v=pEGWcMTxs3I

How to print a string multiple times?

EDIT: Old answer erased in response to updated question.

You just store the string in a variable:

separator = "!" * int(raw_input("Enter number: "))
print separator
do_stuff()
print separator
other_stuff()
print separator

grep a tab in UNIX

This is not exactly what you are looking for, but might work in your case

grep '[[:blank:]]'

Equivalent to

grep -P '[ \t]'

So it will find Space and Tab.

§ Character classes

Note, it is not advertised in my man grep, but still works

$ man grep | grep blank | wc
      0       0       0

Java 8 NullPointerException in Collectors.toMap

Yep, a late answer from me, but I think it may help to understand what's happening under the hood in case anyone wants to code some other Collector-logic.

I tried to solve the problem by coding a more native and straight forward approach. I think it's as direct as possible:

public class LambdaUtilities {

  /**
   * In contrast to {@link Collectors#toMap(Function, Function)} the result map
   * may have null values.
   */
  public static <T, K, U, M extends Map<K, U>> Collector<T, M, M> toMapWithNullValues(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
    return toMapWithNullValues(keyMapper, valueMapper, HashMap::new);
  }

  /**
   * In contrast to {@link Collectors#toMap(Function, Function, BinaryOperator, Supplier)}
   * the result map may have null values.
   */
  public static <T, K, U, M extends Map<K, U>> Collector<T, M, M> toMapWithNullValues(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, Supplier<Map<K, U>> supplier) {
    return new Collector<T, M, M>() {

      @Override
      public Supplier<M> supplier() {
        return () -> {
          @SuppressWarnings("unchecked")
          M map = (M) supplier.get();
          return map;
        };
      }

      @Override
      public BiConsumer<M, T> accumulator() {
        return (map, element) -> {
          K key = keyMapper.apply(element);
          if (map.containsKey(key)) {
            throw new IllegalStateException("Duplicate key " + key);
          }
          map.put(key, valueMapper.apply(element));
        };
      }

      @Override
      public BinaryOperator<M> combiner() {
        return (left, right) -> {
          int total = left.size() + right.size();
          left.putAll(right);
          if (left.size() < total) {
            throw new IllegalStateException("Duplicate key(s)");
          }
          return left;
        };
      }

      @Override
      public Function<M, M> finisher() {
        return Function.identity();
      }

      @Override
      public Set<Collector.Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
      }

    };
  }

}

And the tests using JUnit and assertj:

  @Test
  public void testToMapWithNullValues() throws Exception {
    Map<Integer, Integer> result = Stream.of(1, 2, 3)
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null));

    assertThat(result)
        .isExactlyInstanceOf(HashMap.class)
        .hasSize(3)
        .containsEntry(1, 1)
        .containsEntry(2, null)
        .containsEntry(3, 3);
  }

  @Test
  public void testToMapWithNullValuesWithSupplier() throws Exception {
    Map<Integer, Integer> result = Stream.of(1, 2, 3)
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null, LinkedHashMap::new));

    assertThat(result)
        .isExactlyInstanceOf(LinkedHashMap.class)
        .hasSize(3)
        .containsEntry(1, 1)
        .containsEntry(2, null)
        .containsEntry(3, 3);
  }

  @Test
  public void testToMapWithNullValuesDuplicate() throws Exception {
    assertThatThrownBy(() -> Stream.of(1, 2, 3, 1)
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null)))
            .isExactlyInstanceOf(IllegalStateException.class)
            .hasMessage("Duplicate key 1");
  }

  @Test
  public void testToMapWithNullValuesParallel() throws Exception {
    Map<Integer, Integer> result = Stream.of(1, 2, 3)
        .parallel() // this causes .combiner() to be called
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null));

    assertThat(result)
        .isExactlyInstanceOf(HashMap.class)
        .hasSize(3)
        .containsEntry(1, 1)
        .containsEntry(2, null)
        .containsEntry(3, 3);
  }

  @Test
  public void testToMapWithNullValuesParallelWithDuplicates() throws Exception {
    assertThatThrownBy(() -> Stream.of(1, 2, 3, 1, 2, 3)
        .parallel() // this causes .combiner() to be called
        .collect(LambdaUtilities.toMapWithNullValues(Function.identity(), x -> x % 2 == 1 ? x : null)))
            .isExactlyInstanceOf(IllegalStateException.class)
            .hasCauseExactlyInstanceOf(IllegalStateException.class)
            .hasStackTraceContaining("Duplicate key");
  }

And how do you use it? Well, just use it instead of toMap() like the tests show. This makes the calling code look as clean as possible.

EDIT:
implemented Holger's idea below, added a test method

Using a global variable with a thread

You just need to declare a as a global in thread2, so that you aren't modifying an a that is local to that function.

def thread2(threadname):
    global a
    while True:
        a += 1
        time.sleep(1)

In thread1, you don't need to do anything special, as long as you don't try to modify the value of a (which would create a local variable that shadows the global one; use global a if you need to)>

def thread1(threadname):
    #global a       # Optional if you treat a as read-only
    while a < 10:
        print a

Delete element in a slice

Rather than thinking of the indices in the [a:]-, [:b]- and [a:b]-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0 before the element indexed as 0.

enter image description here

Looking at just the blue numbers, it's much easier to see what is going on: [0:3] encloses everything, [3:3] is empty and [1:2] would yield {"B"}. Then [a:] is just the short version of [a:len(arrayOrSlice)], [:b] the short version of [0:b] and [:] the short version of [0:len(arrayOrSlice)]. The latter is commonly used to turn an array into a slice when needed.

Removing u in list

Please Use map() python function.

Input: In case of list of values

index = [u'CARBO1004' u'CARBO1006' u'CARBO1008' u'CARBO1009' u'CARBO1020']

encoded_string = map(str, index)

Output: ['CARBO1004', 'CARBO1006', 'CARBO1008', 'CARBO1009', 'CARBO1020']

For a Single string input:

index = u'CARBO1004'
# Use Any one of the encoding scheme.
index.encode("utf-8")  # To utf-8 encoding scheme
index.encode('ascii', 'ignore')  # To Ignore Encoding Errors and set to default scheme

Output: 'CARBO1004'

How to Specify "Vary: Accept-Encoding" header in .htaccess

Many hours spent to clarify what was that. Please, read this post to get the advanced .HTACCESS codes and learn what they do.

You can use:

Header append Vary "Accept-Encoding"
#or
Header set Vary "Accept-Encoding"

How to read an external local JSON file in JavaScript?

Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/

Once your file is loaded, you can retrieve the data using:

var jsonData = JSON.parse(theTextContentOfMyFile);

Accessing items in an collections.OrderedDict by index

Do you have to use an OrderedDict or do you specifically want a map-like type that's ordered in some way with fast positional indexing? If the latter, then consider one of Python's many sorted dict types (which orders key-value pairs based on key sort order). Some implementations also support fast indexing. For example, the sortedcontainers project has a SortedDict type for just this purpose.

>>> from sortedcontainers import SortedDict
>>> sd = SortedDict()
>>> sd['foo'] = 'python'
>>> sd['bar'] = 'spam'
>>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
'bar'
>>> # If you want the value, then simple do a key lookup:
>>> print sd[sd.iloc[1]]
'python'

How do I match any character across multiple lines in a regular expression?

It depends on the language, but there should be a modifier that you can add to the regex pattern. In PHP it is:

/(.*)<FooBar>/s

The s at the end causes the dot to match all characters including newlines.

How to read/write arbitrary bits in C/C++

You need to shift and mask the value, so for example...

If you want to read the first two bits, you just need to mask them off like so:

int value = input & 0x3;

If you want to offset it you need to shift right N bits and then mask off the bits you want:

int value = (intput >> 1) & 0x3;

To read three bits like you asked in your question.

int value = (input >> 1) & 0x7;

Removing the textarea border in HTML

This one is great:

<style type="text/css">
textarea.test
{  
width: 100%;
height: 100%;
border-color: Transparent;     
}
</style>
<textarea class="test"></textarea>

Install Android App Bundle on device

If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.

  1. Go to Edit Configurations
    enter image description here
  2. Select the Deploy dropdown and change it from "Default apk" to "APK from app bundle".enter image description here
  3. Apply the changes and then run it on the device connected. Build time will increase after making this change.

This will install an apk directly on the device connected from the aab.

Update GCC on OSX

The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:

$ brew tap SynthiNet/synthinet
$ brew install gcc47

Found it on a post here.

REST API Best practice: How to accept list of parameter values as input

First:

I think you can do it 2 ways

http://our.api.com/Product/<id> : if you just want one record

http://our.api.com/Product : if you want all records

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

Or the one I like most is:

You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product that should return the equivalent urls of http://our.api.com/Product/<id> and call them after this.

Second

When you have to do queries on the url calls. I would suggest using HATEOAS again.

1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black

2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red

3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

I would add to the accepted answer that you would also want to add the Accept header to the httpClient:

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Detect and exclude outliers in Pandas data frame

scipy.stats has methods trim1() and trimboth() to cut the outliers out in a single row, according to the ranking and an introduced percentage of removed values.

How to give a Linux user sudo access?

This answer will do what you need, although usually you don't add specific usernames to sudoers. Instead, you have a group of sudoers and just add your user to that group when needed. This way you don't need to use visudo more than once when giving sudo permission to users.

If you're on Ubuntu, the group is most probably already set up and called admin:

$ sudo cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#

...

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

On other distributions, like Arch and some others, it's usually called wheel and you may need to set it up: Arch Wiki

To give users in the wheel group full root privileges when they precede a command with "sudo", uncomment the following line: %wheel ALL=(ALL) ALL

Also note that on most systems visudo will read the EDITOR environment variable or default to using vi. So you can try to do EDITOR=vim visudo to use vim as the editor.

To add a user to the group you should run (as root):

# usermod -a -G groupname username

where groupname is your group (say, admin or wheel) and username is the username (say, john).

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

  • NOLOCK is local to the table (or views etc)
  • READ UNCOMMITTED is per session/connection

As for guidelines... a random search from StackOverflow and the electric interweb...

Generate your own Error code in swift 3

Implement LocalizedError:

struct StringError : LocalizedError
{
    var errorDescription: String? { return mMsg }
    var failureReason: String? { return mMsg }
    var recoverySuggestion: String? { return "" }
    var helpAnchor: String? { return "" }

    private var mMsg : String

    init(_ description: String)
    {
        mMsg = description
    }
}

Note that simply implementing Error, for instance, as described in one of the answers, will fail (at least in Swift 3), and calling localizedDescription will result in the string "The operation could not be completed. (.StringError error 1.)"

How to define constants in Visual C# like #define in C?

in c language: #define (e.g. #define counter 100)

in assembly language: equ (e.g. counter equ 100)

in c# language: according to msdn refrence: You use #define to define a symbol. When you use the symbol as the expression that's passed to the #if directive, the expression will evaluate to true, as the following example shows:

# define DEBUG

The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.

How do I catch a PHP fatal (`E_ERROR`) error?

PHP doesn't provide conventional means for catching and recovering from fatal errors. This is because processing should not typically be recovered after a fatal error. String matching an output buffer (as suggested by the original post the technique described on PHP.net) is definitely ill-advised. It's simply unreliable.

Calling the mail() function from within an error handler method prove to be problematic, too. If you had a lot of errors, your mail server would be loaded with work, and you could find yourself with a gnarly inbox. To avoid this, you might consider running a cron to scan error logs periodically and send notifications accordingly. You might also like to look into system monitoring software, such as Nagios.


To speak to the bit about registering a shutdown function:

It's true that you can register a shutdown function, and that's a good answer.

The point here is that we typically shouldn't try to recover from fatal errors, especially not by using a regular expression against your output buffer. I was responding to the accepted answer, which linked to a suggestion on php.net which has since been changed or removed.

That suggestion was to use a regex against the output buffer during exception handling, and in the case of a fatal error (detected by the matching against whatever configured error text you might be expecting), try to do some sort of recovery or continued processing. That would not be a recommended practice (I believe that's why I can't find the original suggestion, too. I'm either overlooking it, or the php community shot it down).

It might be worth noting that the more recent versions of PHP (around 5.1) seem to call the shutdown function earlier, before the output buffering callback is envoked. In version 5 and earlier, that order was the reverse (the output buffering callback was followed by the shutdown function). Also, since about 5.0.5 (which is much earlier than the questioner's version 5.2.3), objects are unloaded well before a registered shutdown function is called, so you won't be able to rely on your in-memory objects to do much of anything.

So registering a shutdown function is fine, but the sort of tasks that ought to be performed by a shutdown function are probably limited to a handful of gentle shutdown procedures.

The key take-away here is just some words of wisdom for anyone who stumbles upon this question and sees the advice in the originally accepted answer. Don't regex your output buffer.

Trying to use Spring Boot REST to Read JSON String from POST

To further work with array of maps, the followings could help:

@RequestMapping(value = "/process", method = RequestMethod.POST, headers = "Accept=application/json")
public void setLead(@RequestBody Collection<? extends Map<String, Object>> payload) throws Exception {

  List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
  maps.addAll(payload);

}

How can I make SMTP authenticated in C#

In my case even after following all of the above. I had to upgrade my project from .net 3.5 to .net 4 to authorize against our internal exchange 2010 mail server.

Node.js global proxy setting

Unfortunately, it seems that proxy information must be set on each call to http.request. Node does not include a mechanism for global proxy settings.

The global-tunnel-ng module on NPM appears to handle this, however:

var globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  proxyAuth: 'userId:password', // optional authentication
  sockets: 50 // optional pool size for each http and https
});

After the global settings are establish with a call to initialize, both http.request and the request library will use the proxy information.

The module can also use the http_proxy environment variable:

process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();

Android ListView headers

Here's how I do it, the keys are getItemViewType and getViewTypeCount in the Adapter class. getViewTypeCount returns how many types of items we have in the list, in this case we have a header item and an event item, so two. getItemViewType should return what type of View we have at the input position.

Android will then take care of passing you the right type of View in convertView automatically.

Here what the result of the code below looks like:

First we have an interface that our two list item types will implement

public interface Item {
    public int getViewType();
    public View getView(LayoutInflater inflater, View convertView);
}

Then we have an adapter that takes a list of Item

public class TwoTextArrayAdapter extends ArrayAdapter<Item> {
    private LayoutInflater mInflater;

    public enum RowType {
        LIST_ITEM, HEADER_ITEM
    }

    public TwoTextArrayAdapter(Context context, List<Item> items) {
        super(context, 0, items);
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getViewTypeCount() {
        return RowType.values().length;

    }

    @Override
    public int getItemViewType(int position) {
        return getItem(position).getViewType();
    }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
   return getItem(position).getView(mInflater, convertView);
}

EDIT Better For Performance.. can be noticed when scrolling

private static final int TYPE_ITEM = 0; 
private static final int TYPE_SEPARATOR = 1; 

public View getView(int position, View convertView, ViewGroup parent)  {
    ViewHolder holder = null;
    int rowType = getItemViewType(position);
    View View;
    if (convertView == null) {
        holder = new ViewHolder();
        switch (rowType) {
            case TYPE_ITEM:
                convertView = mInflater.inflate(R.layout.task_details_row, null);
                holder.View=getItem(position).getView(mInflater, convertView);
                break;
            case TYPE_SEPARATOR:
                convertView = mInflater.inflate(R.layout.task_detail_header, null);
                holder.View=getItem(position).getView(mInflater, convertView);
                break;
        }
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }
    return convertView; 
} 

public static class ViewHolder {
    public  View View; } 
}

Then we have classes the implement Item and inflate the correct layouts. In your case you'll have something like a Header class and a ListItem class.

   public class Header implements Item {
    private final String         name;

    public Header(String name) {
        this.name = name;
    }

    @Override
    public int getViewType() {
        return RowType.HEADER_ITEM.ordinal();
    }

    @Override
    public View getView(LayoutInflater inflater, View convertView) {
        View view;
        if (convertView == null) {
            view = (View) inflater.inflate(R.layout.header, null);
            // Do some initialization
        } else {
            view = convertView;
        }

        TextView text = (TextView) view.findViewById(R.id.separator);
        text.setText(name);

        return view;
    }

}

And then the ListItem class

    public class ListItem implements Item {
    private final String         str1;
    private final String         str2;

    public ListItem(String text1, String text2) {
        this.str1 = text1;
        this.str2 = text2;
    }

    @Override
    public int getViewType() {
        return RowType.LIST_ITEM.ordinal();
    }

    @Override
    public View getView(LayoutInflater inflater, View convertView) {
        View view;
        if (convertView == null) {
            view = (View) inflater.inflate(R.layout.my_list_item, null);
            // Do some initialization
        } else {
            view = convertView;
        }

        TextView text1 = (TextView) view.findViewById(R.id.list_content1);
        TextView text2 = (TextView) view.findViewById(R.id.list_content2);
        text1.setText(str1);
        text2.setText(str2);

        return view;
    }

}

And a simple Activity to display it

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<Item> items = new ArrayList<Item>();
        items.add(new Header("Header 1"));
        items.add(new ListItem("Text 1", "Rabble rabble"));
        items.add(new ListItem("Text 2", "Rabble rabble"));
        items.add(new ListItem("Text 3", "Rabble rabble"));
        items.add(new ListItem("Text 4", "Rabble rabble"));
        items.add(new Header("Header 2"));
        items.add(new ListItem("Text 5", "Rabble rabble"));
        items.add(new ListItem("Text 6", "Rabble rabble"));
        items.add(new ListItem("Text 7", "Rabble rabble"));
        items.add(new ListItem("Text 8", "Rabble rabble"));

        TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(this, items);
        setListAdapter(adapter);
    }

}

Layout for R.layout.header

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        style="?android:attr/listSeparatorTextViewStyle"
        android:id="@+id/separator"
        android:text="Header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#757678"
        android:textColor="#f5c227" />

</LinearLayout>

Layout for R.layout.my_list_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/list_content1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_margin="5dip"
        android:clickable="false"
        android:gravity="center"
        android:longClickable="false"
        android:paddingBottom="1dip"
        android:paddingTop="1dip"
        android:text="sample"
        android:textColor="#ff7f1d"
        android:textSize="17dip"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/list_content2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_margin="5dip"
        android:clickable="false"
        android:gravity="center"
        android:linksClickable="false"
        android:longClickable="false"
        android:paddingBottom="1dip"
        android:paddingTop="1dip"
        android:text="sample"
        android:textColor="#6d6d6d"
        android:textSize="17dip" />

</LinearLayout>

Layout for R.layout.activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

You can also get fancier and use ViewHolders, load stuff asynchronously, or whatever you like.

javascript: get a function's variable's value within another function

the OOP way to do this in ES5 is to make that variable into a property using the this keyword.

function first(){
    this.nameContent=document.getElementById('full_name').value;
}

function second() {
    y=new first();
    alert(y.nameContent);
}

How to get the Android Emulator's IP address?

Like this:

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Check the docs for more info: NetworkInterface.

Getting absolute URLs using ASP.NET Core

If you simply want a Uri for a method that has a route annotation, the following worked for me.

Steps

Get Relative URL

Noting the Route name of the target action, get the relative URL using the controller's URL property as follows:

var routeUrl = Url.RouteUrl("*Route Name Here*", new { *Route parameters here* });

Create an absolute URL

var absUrl = string.Format("{0}://{1}{2}", Request.Scheme,
            Request.Host, routeUrl);

Create a new Uri

var uri = new Uri(absUrl, UriKind.Absolute)

Example

[Produces("application/json")]
[Route("api/Children")]
public class ChildrenController : Controller
{
    private readonly ApplicationDbContext _context;

    public ChildrenController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: api/Children
    [HttpGet]
    public IEnumerable<Child> GetChild()
    {
        return _context.Child;
    }

    [HttpGet("uris")]
    public IEnumerable<Uri> GetChildUris()
    {
        return from c in _context.Child
               select
                   new Uri(
                       $"{Request.Scheme}://{Request.Host}{Url.RouteUrl("GetChildRoute", new { id = c.ChildId })}",
                       UriKind.Absolute);
    }


    // GET: api/Children/5
    [HttpGet("{id}", Name = "GetChildRoute")]
    public IActionResult GetChild([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return HttpBadRequest(ModelState);
        }

        Child child = _context.Child.Single(m => m.ChildId == id);

        if (child == null)
        {
            return HttpNotFound();
        }

        return Ok(child);
    }
}

How can I change the color of a Google Maps marker?

The simplest way I found is to use BitmapDescriptorFactory.defaultMarker() the documentation even has an example of setting the color. From my own code:

MarkerOptions marker = new MarkerOptions()
            .title(formatInfo(data))
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
            .position(new LatLng(data.getLatitude(), data.getLongitude()))

Send data from a textbox into Flask?

Declare a Flask endpoint to accept POST input type and then do necessary steps. Use jQuery to post the data.

from flask import request

@app.route('/parse_data', methods=['GET', 'POST'])
def parse_data(data):
    if request.method == "POST":
         #perform action here
var value = $('.textbox').val();
$.ajax({
  type: 'POST',
  url: "{{ url_for('parse_data') }}",
  data: JSON.stringify(value),
  contentType: 'application/json',
  success: function(data){
    // do something with the received data
  }
});

React PropTypes : Allow different types of PropTypes for one prop

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

How can I disable mod_security in .htaccess file?

Just to update this question for mod_security 2.7.0+ - they turned off the ability to mitigate modsec via htaccess unless you compile it with the --enable-htaccess-config flag. Most hosts do not use this compiler option since it allows too lax security. Instead, vhosts in httpd.conf are your go-to option for controlling modsec.

Even if you do compile modsec with htaccess mitigation, there are less directives available. SecRuleEngine can no longer be used there for example. Here is a list that is available to use by default in htaccess if allowed (keep in mind a host may further limit this list with AllowOverride):

    - SecAction
    - SecRule

    - SecRuleRemoveByMsg
    - SecRuleRemoveByTag
    - SecRuleRemoveById

    - SecRuleUpdateActionById
    - SecRuleUpdateTargetById
    - SecRuleUpdateTargetByTag
    - SecRuleUpdateTargetByMsg

More info on the official modsec wiki

As an additional note for 2.x users: the IfModule should now look for mod_security2.c instead of the older mod_security.c

How to check if a process is in hang state (Linux)

you could check the files

/proc/[pid]/task/[thread ids]/status

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

Creating a new list and populating valid values in new list worked for me.

Code throwing error -

List<String> list = new ArrayList<>();
   for (String s: list) {
     if(s is null or blank) {
        list.remove(s);
     }
   }
desiredObject.setValue(list);

After fix -

 List<String> list = new ArrayList<>();
 List<String> newList= new ArrayList<>();
 for (String s: list) {
   if(s is null or blank) {
      continue;
   }
   newList.add(s);
 }
 desiredObject.setValue(newList);

How to play ringtone/alarm sound in Android

You could use this sample code:

Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtoneSound = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri)

if (ringtoneSound != null) {
    ringtoneSound.play();
}

How to multiply values using SQL

Why use GROUP BY at all?

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

HTML entity for check mark

HTML and XML entities are just a way of referencing a Unicode code-point in a way that reliably works regardless of the encoding of the actual page, making them useful for using esoteric Unicode characters in a page using 7-bit ASCII or some other encoding scheme, ideally on a one-off basis. They're also used to escape the <, >, " and & characters as these are reserved in SGML.

Anyway, Unicode has a number of tick/check characters, as per Wikipedia ( http://en.wikipedia.org/wiki/Tick_(check_mark) ).

Ideally you should save/store your HTML in a Unicode format like UTF-8 or 16, thus obviating the need to use HTML entities to represent a Unicode character. Nonetheless use: &#x2714; ✔.

&#x2714;

Is using hex notation and is the same as

$#10004;

(as 2714 in base 16 is the same as 10004 in base 10)

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

If you are not using annotation based Servlet then please remove annotation @WebServlet("/YourServletName") from the starting of the servlet. This annotation confuses the mapping with web.xml, after removing this annotation Tomcat server will work properly.

RedirectToAction with parameter

This might be years ago but anyways, this also depends on your Global.asax map route since you may add or edit parameters to fit what you want.

eg.

Global.asax

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            //new { controller = "Home", action = "Index", id = UrlParameter.Optional 
            new { controller = "Home", action = "Index", id = UrlParameter.Optional,
                  extraParam = UrlParameter.Optional // extra parameter you might need
        });
    }

then the parameters you'll need to pass will change to:

return RedirectToAction( "Main", new RouteValueDictionary( 
    new { controller = controllerName, action = "Main", Id = Id, extraParam = someVariable } ) );

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

How to check if a DateTime field is not null or empty?

DateTime is not standard nullable type. If you want assign null to DateTime type of variable, you have to use DateTime? type which supports null value.

If you only want test your variable to be set (e.g. variable holds other than default value), you can use keyword "default" like in following code:

if (dateTimeVariable == default(DateTime))
{
    //do work for dateTimeVariable == null situation
}

Redirect all to index.php using htaccess

After doing that don't forget to change your href in, <a href="{the chosen redirected name}"> home</a>

Example:

.htaccess file

RewriteEngine On

RewriteRule ^about/$ /about.php

PHP file:

<a href="about/"> about</a>

Get div's offsetTop positions in React

Eugene's answer uses the correct function to get the data, but for posterity I'd like to spell out exactly how to use it in React v0.14+ (according to this answer):

  import ReactDOM from 'react-dom';
  //...
  componentDidMount() {
    var rect = ReactDOM.findDOMNode(this)
      .getBoundingClientRect()
  }

Is working for me perfectly, and I'm using the data to scroll to the top of the new component that just mounted.