Programs & Examples On #Pygame

pygame is a set of Python modules designed for writing video games. Use this tag only if you are using the pygame library and not if you have a question about programming a game in python in general.

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff

How to get keyboard input in pygame?

Try this:

keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    if count == 10:
        location-=1
        count=0
    else:
        count +=1
    if location==-1:
        location=0
if keys[K_RIGHT]:
    if count == 10:
        location+=1
        count=0
    else:
        count +=1
    if location==5:
        location=4

This will mean you only move 1/10 of the time. If it still moves to fast you could try increasing the value you set "count" too.

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

ImportError: No module named 'pygame'

I am a quite newbie to python and I was having same issue. (windows x64 os) I have solved, doing below steps

  1. I removed python (x64 version) and pygame
  2. I have downloaded and installed python 2.6.6 x86: https://www.python.org/ftp/python/2.6.6/python-2.6.6.msi
  3. I have downloaded and installed pygame (when installing, I have chosen the directory that I installed python): http://pygame.org/ftp/pygame-1.9.1.win32-py2.6.msi
  4. Works well :)

Python display text with font & color?

Yes. It is possible to draw text in pygame:

# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)

# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))

How to display text in pygame?

When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

import pygame

def text_to_screen(screen, text, x, y, size = 50,
            color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
    try:

        text = str(text)
        font = pygame.font.Font(font_type, size)
        text = font.render(text, True, color)
        screen.blit(text, (x, y))

    except Exception, e:
        print 'Font Error, saw it coming'
        raise e

Then when that has been imported when I want to display text taht updates E.G score I do:

Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)

If it is just normal text that isn't being updated:

Funk.text_to_screen(screen, 'Text', xpos, ypos)

You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

Pygame mouse clicking detection

The pygame documentation for mouse events is here. You can either use the pygame.mouse.get_pressed method in collaboration with the pygame.mouse.get_pos (if needed). But please use the mouse click event via a main event loop. The reason why the event loop is better is due to "short clicks". You may not notice these on normal machines, but computers that use tap-clicks on trackpads have excessively small click periods. Using the mouse events will prevent this.

EDIT: To perform pixel perfect collisions use pygame.sprite.collide_rect() found on their docs for sprites.

Pygame Drawing a Rectangle

here's how:

import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
pygame.quit()

How can I scroll a web page using selenium webdriver in python?

You can use send_keys to simulate an END (or PAGE_DOWN) key press (which normally scroll the page):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.END)

Change select box option background color

Here it goes what I've learned about the subject!

The CSS 2 specification did not address the problem of how form elements should be presented to users period!

Read here: smashing magazine

Eventually, you will never find any technical article from w3c or other addressed to this topic. Styling form elements in particular select boxes is not fully supported however, you can drive around... with some effort!

Styling HTML Form Elements

Building Custom Widgets

Don't waste time with hacks e such read the links and learn how pros get the job done!

'Source code does not match the bytecode' when debugging on a device

This is the steps that worked for me (For both Mac and Windows):

  1. Click on "File"
  2. Click on "Invalidate Caches / Restart ..."
  3. Choose: "Invalidate and Restart"
  4. Wait for 20 minutes

apache redirect from non www to www

<VirtualHost *:80>
    ServerAlias example.com
    RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>

What is the HTML unicode character for a "tall" right chevron?

I use ? (0x25B8) for the right arrow, often to show a collapsed list; and I pair it with ? (0x25BE) to show the list opened up. Both are unobtrusive.

Using request.setAttribute in a JSP page

The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.

A 'for' loop to iterate over an enum in Java

Try to use a for each

for ( Direction direction : Direction.values()){
  System.out.println(direction.toString());
}

invalid command code ., despite escaping periods, using sed

You simply forgot to supply an argument to -i. Just change -i to -i ''.

Of course that means you don't want your files to be backed up; otherwise supply your extension of choice, like -i .bak.

Change tab bar item selected color in a storyboard

put this code in the viewDidLoad of the view controller that you want to change the color of

[[UITabBar appearance] setSelectedImageTintColor:[UIColor whiteColor]];

How can I get query parameters from a URL in Vue.js?

If your url looks something like this:

somesite.com/something/123

Where '123' is a parameter named 'id' (url like /something/:id), try with:

this.$route.params.id

Access nested dictionary items via a list of keys?

Very late to the party, but posting in case this may help someone in the future. For my use case, the following function worked the best. Works to pull any data type out of dictionary

dict is the dictionary containing our value

list is a list of "steps" towards our value

def getnestedvalue(dict, list):

    length = len(list)
    try:
        for depth, key in enumerate(list):
            if depth == length - 1:
                output = dict[key]
                return output
            dict = dict[key]
    except (KeyError, TypeError):
        return None

    return None

Finding duplicate values in MySQL

SELECT t.*,(select count(*) from city as tt
  where tt.name=t.name) as count
  FROM `city` as t
  where (
     select count(*) from city as tt
     where tt.name=t.name
  ) > 1 order by count desc

Replace city with your Table. Replace name with your field name

How to specify a port number in SQL Server connection string?

Use a comma to specify a port number with SQL Server:

mycomputer.test.xxx.com,1234

It's not necessary to specify an instance name when specifying the port.

Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

Bootstrap Navbar toggle button not working

Your code looks great, the only thing i see is that you did not include the collapsed class in your button selector. http://www.bootply.com/cpHugxg2f8 Note: Requires JavaScript plugin If JavaScript is disabled and the viewport is narrow enough that the navbar collapses, it will be impossible to expand the navbar and view the content within the .navbar-collapse.

The responsive navbar requires the collapse plugin to be included in your version of Bootstrap.

<div class="navbar-wrapper">
      <div class="container">

        <nav class="navbar navbar-inverse navbar-static-top">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Project name</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav">
                    <li><a href="">Page 1</a>
                    </li>
                    <li><a href="">Page 2</a>
                    </li>
                    <li><a href="">Page 3</a>
                    </li>

              </ul>
            </div>
          </div>
        </nav>

      </div>
    </div>

What is float in Java?

Make it

float b= 3.6f;

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

Multiline editing in Visual Studio Code

Use Ctrl + D to use multi word edit of same words in Windows and Linux.

Use CMD + D for Mac.

1067 error on attempt to start MySQL

I also get log with Table 'mysql.plugin' doesn't exist if install MYSQL Server 5.1 by 'msiexec.exe' DataDir I put as C:\MYSQL\MySQL_Server_5_1\data\

but to my surprise was create data in a C:\MYSQL\MySQL_Server_5_1\data\data

There are was add word data . So I change my.ini file from

datadir="C:/MySQL/MySQL_Server_5_1/Data/" .

to the

datadir="C:/MySQL/MySQL_Server_5_1/Data/data"

and then I can use net start MYSQL51 and then mysqld.exe run and appear in a Task Manager

String strip() for JavaScript?

Use this:

if(typeof(String.prototype.trim) === "undefined")
{
    String.prototype.trim = function() 
    {
        return String(this).replace(/^\s+|\s+$/g, '');
    };
}

The trim function will now be available as a first-class function on your strings. For example:

" dog".trim() === "dog" //true

EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.

Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

I got same kind of issue in iOS 9.x version

ISSUE IS: App crashes as soon as I open the app with below error.

dyld: Library not loaded: /System/Library/Frameworks/UserNotifications.framework/UserNotifications Referenced from: /var/containers/Bundle/Application/######/TestApp.app/TestApp Reason: image not found

I have resolved this issue by changing Required to Optional in Linked Frameworks and Libraries for UserNotifications.framework framework.

How can I get a list of users from active directory?

If you want to filter y active accounts add this to Harvey's code:

 UserPrincipal userPrin = new UserPrincipal(context);
 userPrin.Enabled = true;

after the first using. Then add

  searcher.QueryFilter = userPrin;

before the find all. And that should get you the active ones.

Importing a Maven project into Eclipse from Git

After checking out my branch in Egit, I switched to the Java View, then used File-->Import, Git-->Projects from Git, then selected the top level maven directory. This was with Eclipse Kepler.

Laravel-5 how to populate select box from database with id value and name value

Laravel 5.3 use pluck($value, $key )

$value is displayed in your drop list and $key is id

controller

$products = Product::pluck('name', 'id');

return view('main.index', compact('products'));

view

{{ Form::select('id', $products, null, ['class' => 'form-control']) }}

Convert Enumeration to a Set/List

When using guava (See doc) there is Iterators.forEnumeration. Given an Enumeration x you can do the following:

to get a immutable Set:

ImmutableSet.copyOf(Iterators.forEnumeration(x));

to get a immutable List:

ImmutableList.copyOf(Iterators.forEnumeration(x));

to get a hashSet:

Sets.newHashSet(Iterators.forEnumeration(x));

How to add text to an existing div with jquery

Very easy from My side:-

<html>
<head>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("input").click(function() {
            $('<input type="text" name="name" value="value"/>').appendTo('#testdiv');
        });

    });
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <div id="testdiv"></div>
    <input type="button" value="Add" />
</body>
</html>

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

Methods for Aligning Flex Items along the Main Axis

As stated in the question:

To align flex items along the main axis there is one property: justify-content

To align flex items along the cross axis there are three properties: align-content, align-items and align-self.

The question then asks:

Why are there no justify-items and justify-self properties?

One answer may be: Because they're not necessary.

The flexbox specification provides two methods for aligning flex items along the main axis:

  1. The justify-content keyword property, and
  2. auto margins

justify-content

The justify-content property aligns flex items along the main axis of the flex container.

It is applied to the flex container but only affects flex items.

There are five alignment options:

  • flex-start ~ Flex items are packed toward the start of the line.

    enter image description here

  • flex-end ~ Flex items are packed toward the end of the line.

    enter image description here

  • center ~ Flex items are packed toward the center of the line.

    enter image description here

  • space-between ~ Flex items are evenly spaced, with the first item aligned to one edge of the container and the last item aligned to the opposite edge. The edges used by the first and last items depends on flex-direction and writing mode (ltr or rtl).

    enter image description here

  • space-around ~ Same as space-between except with half-size spaces on both ends.

    enter image description here


Auto Margins

With auto margins, flex items can be centered, spaced away or packed into sub-groups.

Unlike justify-content, which is applied to the flex container, auto margins go on flex items.

They work by consuming all free space in the specified direction.


Align group of flex items to the right, but first item to the left

Scenario from the question:

  • making a group of flex items align-right (justify-content: flex-end) but have the first item align left (justify-self: flex-start)

    Consider a header section with a group of nav items and a logo. With justify-self the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.

enter image description here

enter image description here


Other useful scenarios:

enter image description here

enter image description here

enter image description here


Place a flex item in the corner

Scenario from the question:

  • placing a flex item in a corner .box { align-self: flex-end; justify-self: flex-end; }

enter image description here


Center a flex item vertically and horizontally

enter image description here

margin: auto is an alternative to justify-content: center and align-items: center.

Instead of this code on the flex container:

.container {
    justify-content: center;
    align-items: center;
}

You can use this on the flex item:

.box56 {
    margin: auto;
}

This alternative is useful when centering a flex item that overflows the container.


Center a flex item, and center a second flex item between the first and the edge

A flex container aligns flex items by distributing free space.

Hence, in order to create equal balance, so that a middle item can be centered in the container with a single item alongside, a counterbalance must be introduced.

In the examples below, invisible third flex items (boxes 61 & 68) are introduced to balance out the "real" items (box 63 & 66).

enter image description here

enter image description here

Of course, this method is nothing great in terms of semantics.

Alternatively, you can use a pseudo-element instead of an actual DOM element. Or you can use absolute positioning. All three methods are covered here: Center and bottom-align flex items

NOTE: The examples above will only work – in terms of true centering – when the outermost items are equal height/width. When flex items are different lengths, see next example.


Center a flex item when adjacent items vary in size

Scenario from the question:

  • in a row of three flex items, affix the middle item to the center of the container (justify-content: center) and align the adjacent items to the container edges (justify-self: flex-start and justify-self: flex-end).

    Note that values space-around and space-between on justify-content property will not keep the middle item centered in relation to the container if the adjacent items have different widths (see demo).

As noted, unless all flex items are of equal width or height (depending on flex-direction), the middle item cannot be truly centered. This problem makes a strong case for a justify-self property (designed to handle the task, of course).

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
.box {_x000D_
  height: 50px;_x000D_
  width: 75px;_x000D_
  background-color: springgreen;_x000D_
}_x000D_
.box1 {_x000D_
  width: 100px;_x000D_
}_x000D_
.box3 {_x000D_
  width: 200px;_x000D_
}_x000D_
#center {_x000D_
  text-align: center;_x000D_
  margin-bottom: 5px;_x000D_
}_x000D_
#center > span {_x000D_
  background-color: aqua;_x000D_
  padding: 2px;_x000D_
}
_x000D_
<div id="center">_x000D_
  <span>TRUE CENTER</span>_x000D_
</div>_x000D_
_x000D_
<div id="container">_x000D_
  <div class="box box1"></div>_x000D_
  <div class="box box2"></div>_x000D_
  <div class="box box3"></div>_x000D_
</div>_x000D_
_x000D_
<p>The middle box will be truly centered only if adjacent boxes are equal width.</p>
_x000D_
_x000D_
_x000D_

Here are two methods for solving this problem:

Solution #1: Absolute Positioning

The flexbox spec allows for absolute positioning of flex items. This allows for the middle item to be perfectly centered regardless of the size of its siblings.

Just keep in mind that, like all absolutely positioned elements, the items are removed from the document flow. This means they don't take up space in the container and can overlap their siblings.

In the examples below, the middle item is centered with absolute positioning and the outer items remain in-flow. But the same layout can be achieved in reverse fashion: Center the middle item with justify-content: center and absolutely position the outer items.

enter image description here

Solution #2: Nested Flex Containers (no absolute positioning)

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
.box {_x000D_
  flex: 1;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
.box71 > span { margin-right: auto; }_x000D_
.box73 > span { margin-left: auto;  }_x000D_
_x000D_
/* non-essential */_x000D_
.box {_x000D_
  align-items: center;_x000D_
  border: 1px solid #ccc;_x000D_
  background-color: lightgreen;_x000D_
  height: 40px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box box71"><span>71 short</span></div>_x000D_
  <div class="box box72"><span>72 centered</span></div>_x000D_
  <div class="box box73"><span>73 loooooooooooooooong</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's how it works:

  • The top-level div (.container) is a flex container.
  • Each child div (.box) is now a flex item.
  • Each .box item is given flex: 1 in order to distribute container space equally.
  • Now the items are consuming all space in the row and are equal width.
  • Make each item a (nested) flex container and add justify-content: center.
  • Now each span element is a centered flex item.
  • Use flex auto margins to shift the outer spans left and right.

You could also forgo justify-content and use auto margins exclusively.

But justify-content can work here because auto margins always have priority. From the spec:

8.1. Aligning with auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.


justify-content: space-same (concept)

Going back to justify-content for a minute, here's an idea for one more option.

  • space-same ~ A hybrid of space-between and space-around. Flex items are evenly spaced (like space-between), except instead of half-size spaces on both ends (like space-around), there are full-size spaces on both ends.

This layout can be achieved with ::before and ::after pseudo-elements on the flex container.

enter image description here

(credit: @oriol for the code, and @crl for the label)

UPDATE: Browsers have begun implementing space-evenly, which accomplishes the above. See this post for details: Equal space between flex items


PLAYGROUND (includes code for all examples above)

JOptionPane Yes or No window

Something along these lines ....

   //default icon, custom title
int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION);

String result = "?";
switch (n) {
case JOptionPane.YES_OPTION:
  result = "YES";
  break;
case JOptionPane.NO_OPTION:
  result = "NO";
  break;
default:
  ;
}
System.out.println("Replace? " + result);

you may also want to look at DialogDemo

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

Repeating a function every few seconds

For this the System.Timers.Timer works best

// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it        
myTimer.Enabled = true;

// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }

See Timer Class (.NET 4.6 and 4.5) for details

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

install django-registration-redux==1.1 instead django-registration, if you using django 1.7

Which passwordchar shows a black dot (•) in a winforms textbox?

One more solution to use this Unicode black circle >>

Start >> All Programs >> Accessories >> System Tools >> Character Map

Then select Arial font and choose the Black circle copy it and paste it into PasswordChar property of the textbox.

That's it....

How do I redirect in expressjs while passing some context?

I had to find another solution because none of the provided solutions actually met my requirements, for the following reasons:

  • Query strings: You may not want to use query strings because the URLs could be shared by your users, and sometimes the query parameters do not make sense for a different user. For example, an error such as ?error=sessionExpired should never be displayed to another user by accident.

  • req.session: You may not want to use req.session because you need the express-session dependency for this, which includes setting up a session store (such as MongoDB), which you may not need at all, or maybe you are already using a custom session store solution.

  • next(): You may not want to use next() or next("router") because this essentially just renders your new page under the original URL, it's not really a redirect to the new URL, more like a forward/rewrite, which may not be acceptable.

So this is my fourth solution that doesn't suffer from any of the previous issues. Basically it involves using a temporary cookie, for which you will have to first install cookie-parser. Obviously this means it will only work where cookies are enabled, and with a limited amount of data.

Implementation example:

var cookieParser = require("cookie-parser");

app.use(cookieParser());

app.get("/", function(req, res) {
    var context = req.cookies["context"];
    res.clearCookie("context", { httpOnly: true });
    res.render("home.jade", context); // Here context is just a string, you will have to provide a valid context for your template engine
});

app.post("/category", function(req, res) {
    res.cookie("context", "myContext", { httpOnly: true });
    res.redirect("/");
}

How do I parse a string into a number with Dart?

You can parse a string into an integer with int.parse(). For example:

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345

Note that int.parse() accepts 0x prefixed strings. Otherwise the input is treated as base-10.

You can parse a string into a double with double.parse(). For example:

var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45

parse() will throw FormatException if it cannot parse the input.

How to grant permission to users for a directory using command line in Windows?

  1. navigate to top level directory you want to set permissions to with explorer
  2. type cmd in the address bar of your explorer window
  3. enter icacls . /grant John:(OI)(CI)F /T where John is the username
  4. profit

Just adding this because it seemed supremely easy this way and others may profit - all credit goes to Calin Darie.

How to fix a locale setting warning from Perl

Setting the LC_TYPE environment variable to the default locale language "C" will help to suppress this warning.

Run export LC_CTYPE="C" and try to run the perl command.

P.S: You need to set this variable in one of file /etc/environment or file /etc/default/locale for a permanent solution.

How to set the 'selected option' of a select dropdown list with jquery

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#YourID option[value="3"]').attr("selected", "selected");_x000D_
  $('#YourID option:selected').attr("selected",null);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<select id="YourID">_x000D_
  <option value="1">A</option>_x000D_
  <option value="2">B</option>_x000D_
  <option value="3">C</option>_x000D_
  <option value="4">D</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I center floated elements?

<!DOCTYPE html>
<html>
<head>
    <title>float object center</title>
    <style type="text/css">
#warp{
    width:500px;
    margin:auto;
}
.ser{
width: 200px;
background-color: #ffffff;
display: block;
float: left;
margin-right: 50px;
}
.inim{
    width: 120px;
    margin-left: 40px;
}

    </style>
</head>
<body>



<div id="warp">
            <div class="ser">
              <img class="inim" src="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">

              </div>
           <div class="ser">
             <img class="inim" sr`enter code here`c="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">

             </div>
        </div>

</body>
</html>

step 1

create two or more div's you want and give them a definite width like 100px for each then float it left or right

step 2

then warp these two div's in another div and give it the width of 200px. to this div apply margin auto. boom it works pretty well. check the above example.

Prevent wrapping of span or div

Try this:

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
    white-space: nowrap;_x000D_
}_x000D_
.slide {_x000D_
    display: inline-block;_x000D_
    width: 600px;_x000D_
    white-space: normal;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <span class="slide">Some content</span>_x000D_
    <span class="slide">More content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>_x000D_
    <span class="slide">Even more content!</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you can omit .slideContainer { overflow-x: scroll; } (which browsers may or may not support when you read this), and you'll get a scrollbar on the window instead of on this container.

The key here is display: inline-block. This has decent cross-browser support nowadays, but as usual, it's worth testing in all target browsers to be sure.

how to pass command line arguments to main method dynamically

We can pass string value to main method as argument without using commandline argument concept in java through Netbean

 package MainClass;
 import java.util.Scanner;
 public class CmdLineArgDemo {

static{
 Scanner readData = new Scanner(System.in);   
 System.out.println("Enter any string :");
 String str = readData.nextLine();
 String [] str1 = str.split(" ");
 // System.out.println(str1.length);
 CmdLineArgDemo.main(str1);
}  

   public static void main(String [] args){
      for(int i = 0 ; i<args.length;i++) {
        System.out.print(args[i]+" ");
      }
    }
  }

Output

Enter any string : 
Coders invent Digital World 
Coders invent Digital World

Select a row from html table and send values onclick of a button

$("#table tr").click(function(){
   $(this).addClass('selected').siblings().removeClass('selected');    
   var value=$(this).find('td:first').html();
   alert(value);    
});

$('.ok').on('click', function(e){
    alert($("#table tr.selected td:first").html());
});

Demo:

http://jsfiddle.net/65JPw/2/

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

How can I convert a date into an integer?

Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:

var dates_as_int = dates.map(Date.parse);

Jar mismatch! Fix your dependencies

  1. Jar mismatch comes when you use library projects in your application and both projects are using same jar with different version so just check all library projects attached in your application. if some mismatch exist then remove it.

  2. if above process is not working then just do remove project dependency from build path and again add library projects and build the application.

Select all 'tr' except the first one

I'm surprised nobody mentioned the use of sibling combinators, which are supported by IE7 and later:

tr + tr /* CSS2, adjacent sibling */
tr ~ tr /* CSS3, general sibling */

They both function in exactly the same way (in the context of HTML tables anyway) as:

tr:not(:first-child)

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

In case you don't want to use API 21 as the target API, and thus you don' t want to use the Material Theme, you have to use an older revision belonging to API 19 >

compile "com.android.support:appcompat-v7:19.0.+"

This also helps solving your problem, it only depends on what you want to achieve.

How to add extra whitespace in PHP?

to make your code look better when viewing source

$variable = 'foo';
echo "this is my php variable $variable \n";
echo "this is another php echo here $variable\n";

your code when view source will look like, with nice line returns thanks to \n

this is my php variable foo
this is another php echo here foo

How to remove an element from a list by index

If you want to remove the specific position element in a list, like the 2th, 3th and 7th. you can't use

del my_list[2]
del my_list[3]
del my_list[7]

Since after you delete the second element, the third element you delete actually is the fourth element in the original list. You can filter the 2th, 3th and 7th element in the original list and get a new list, like below:

new list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.

  • this is against Facebook policy, so depending on the country where you live, this may not be legal
  • you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
  • when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
  • this is bypassing the OAuth concept
  • on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API

Sample implementation using WatiN:

class FacebookUser
{
  public string Name { get; set; }
  public long Id { get; set; }
}

public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
  var users = new List<FacebookUser>();
  Settings.Instance.MakeNewIeInstanceVisible = false;
  using (var browser = new IE("https://www.facebook.com"))
  {
    try
    {
      browser.TextField(Find.ByName("email")).Value = email;
      browser.TextField(Find.ByName("pass")).Value = password;
      browser.Form(Find.ById("login_form")).Submit();
      browser.WaitForComplete();
    }
    catch (ElementNotFoundException)
    {
      // We're already logged in
    }
    browser.GoTo("https://www.facebook.com/friends");
    var watch = new Stopwatch();
    watch.Start();

    Link previousLastLink = null;
    while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
    {
      var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
                       && l.GetAttributeValue("data-hovercard").Contains("user.php")
                       && l.Text != null
                     ).LastOrDefault();

      if (lastLink == null || previousLastLink == lastLink)
      {
        break;
      }

      var ieElement = lastLink.NativeElement as IEElement;
      if (ieElement != null)
      {
        var htmlElement = ieElement.AsHtmlElement;
        htmlElement.scrollIntoView();
        browser.WaitForComplete();
      }

      previousLastLink = lastLink;
    }

    var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
      && l.GetAttributeValue("data-hovercard").Contains("user.php")
      && l.Text != null
    ).ToList();

    var idRegex = new Regex("id=(?<id>([0-9]+))");
    foreach (var link in links)
    {
      string hovercard = link.GetAttributeValue("data-hovercard");
      var match = idRegex.Match(hovercard);
      long id = 0;
      if (match.Success)
      {
        id = long.Parse(match.Groups["id"].Value);
      }
      users.Add(new FacebookUser
      {
        Name = link.Text,
        Id = id
      });
    }
  }
  return users;
}

Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

Here is my Approach based on DarKalimHero's Suggestion by selecting only on Explorer.exe processes

Function Get-RdpSessions 
{
    param(
        [string]$computername 
    )

    $processinfo = Get-WmiObject -Query "select * from win32_process where name='explorer.exe'" -ComputerName $computername

    $processinfo | ForEach-Object { $_.GetOwner().User } | Sort-Object -Unique | ForEach-Object { New-Object psobject -Property @{Computer=$computername;LoggedOn=$_} } | Select-Object Computer,LoggedOn
}

Can't append <script> element

This works:

$('body').append($("<script>alert('Hi!');<\/script>")[0]);

It seems like jQuery is doing something clever with scripts so you need to append the html element rather than jQuery object.

Entity Framework Migrations renaming tables and columns

In EF Core, I use the following statements to rename tables and columns:

As for renaming tables:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameTable(name: "OldTableName", schema: "dbo", newName: "NewTableName", newSchema: "dbo");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameTable(name: "NewTableName", schema: "dbo", newName: "OldTableName", newSchema: "dbo");
    }

As for renaming columns:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameColumn(name: "OldColumnName", table: "TableName", newName: "NewColumnName", schema: "dbo");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameColumn(name: "NewColumnName", table: "TableName", newName: "OldColumnName", schema: "dbo");
    }

How to check if a query string value is present via JavaScript?

one more variant, but almost the same as Gumbos solution:

var isDebug = function(){
    return window.location.href.search("[?&]debug=") != -1;
};

How to check whether a str(variable) is empty or not?

The "Pythonic" way to check if a string is empty is:

import random
variable = random.choice(l)
if variable:
    # got a non-empty string
else:
    # got an empty string

How to get english language word database?

You didn't say what you needed this list for. If something used as a blacklist for password checks is enough cracklib might be good for you. It contains over 1.5M words.

Adding ID's to google map markers

JavaScript is a dynamic language. You could just add it to the object itself.

var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};

Also, because all v3 objects extend MVCObject(). You can use:

marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

How to create a DB for MongoDB container on start up?

The official mongo image has merged a PR to include the functionality to databases and admin users at startup.

The database initialisation will run scripts in /docker-entrypoint-initdb.d/ when there is nothing populated in the /data/db directory.

Database Initialisation

The mongo container image provides the /docker-entrypoint-initdb.d/ path to deploy custom .js or .sh setup scripts that will be run once on database initialisation. .js scripts will be run against test by default or MONGO_INITDB_DATABASE if defined in the environment.

COPY mysetup.sh /docker-entrypoint-initdb.d/

or

COPY mysetup.js /docker-entrypoint-initdb.d/

A simple initialisation mongo shell javascript file that demonstrates setting up the container collection with data, logging and how to exit with an error (for result checking).

let error = true

let res = [
  db.container.drop(),
  db.container.createIndex({ myfield: 1 }, { unique: true }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.insert({ myfield: 'hello', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello2', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' })
]

printjson(res)

if (error) {
  print('Error, exiting')
  quit(1)
}

Admin User Setup

The environment variables to control "root" user setup are

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

Example

docker run -d \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password \
  mongod

or Dockerfile

FROM docker.io/mongo
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD password

You don't need to use --auth on the command line as the docker entrypoint.sh script adds this in when it detects the environment variables exist.

JSON encode MySQL results

$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here

NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:

0
1
2
3
4

You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:

5
4
3
2
1

Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

What is the difference between SQL, PL-SQL and T-SQL?

1. SQL or Structured Query Language was developed by IBM for their product "System R".

Later ANSI made it as a Standard on which all Query Languages are based upon and have extended this to create their own DataBase Query Language suits. The first standard was SQL-86 and latest being SQL:2016

2. T-SQL or Transact-SQL was developed by Sybase and later co-owned by Microsoft SQL Server.

3. PL/SQL or Procedural Language/SQL was Oracle Database, known as "Relation Software" that time.

I've documented this in my blog post.

Tool to monitor HTTP, TCP, etc. Web Service traffic

JMeter's built-in proxy may be used to record all HTTP request/response information.

Firefox "Live HTTP headers" plugin may be used to see what is happening on the browser side when sending/receiving request.

Firefox "Tamper data" plugin may be useful when you need to intercept and modify request.

How does Access-Control-Allow-Origin header work?

In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.

Installing:

$ pip install -U flask-cors

Simple example that allows CORS for all domains on all routes:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.

How does BitLocker affect performance?

I used to use the PGP disk encryption product on a laptop (and ran NTFS compressed on top of that!). It didn't seem to have much effect if the amount of disk to be read was small; and most software sources aren't huge by disk standards.

You have lots of RAM and pretty fast processors. I spent most of my time thinking, typing or debugging.

I wouldn't worry very much about it.

How to import JsonConvert in C# application?

JsonConvert is from the namespace Newtonsoft.Json, not System.ServiceModel.Web

Use NuGet to download the package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

How to use UIScrollView in Storyboard

The key is the contentSize.

This is often missing and not indicated when adding a UIScrollView.

Select the UIScrollView and select the Identity Inspector.

Add a contentSize keyPath as a size to the scrollView in the Identity Inspector and setting it to (320, 1000).

Scroll away.

CSS: How to align vertically a "label" and "input" inside a "div"?

_x000D_
_x000D_
div {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    height: 50px;_x000D_
    border: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <label for='name'>Name:</label>_x000D_
    <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

The advantages of this method is that you can change the height of the div, change the height of the text field and change the font size and everything will always stay in the middle.

http://jsfiddle.net/53ALd/6/

Redirect to a page/URL after alert button is pressed

<head>
<script>
    function myFunction() {
        var x;
        var r = confirm("Do you want to clear data?");
        if (r == true) {
            x = "Your Data is Cleared";
            window.location.href = "firstpage.php";
        }
        else {
            x = "You pressed Cancel!";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>

<p id="demo"></p>
</body>
</html>

This will redirect to new php page.

How to verify static void method has been called with power mockito

If you are mocking the behavior (with something like doNothing()) there should really be no need to call to verify*(). That said, here's my stab at re-writing your test method:

@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
   public void testProcessOrder() {
        //Variables
        InternalService is = new InternalService();
        Order order = mock(Order.class);

        //Mock Behavior
        when(order.isSuccessful()).thenReturn(true);
        mockStatic(Internalutils.class);
        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

        //Execute
        is.processOrder(order);            

        //Verify
        verifyStatic(InternalUtils.class); //Similar to how you mock static methods
                                           //this is how you verify them.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
   }
}

I grouped into four sections to better highlight what is going on:

1. Variables

I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.

2. Mock Behavior

This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.

3. Execute

Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.

4. Verify

This is when you call any method starting with verify or assert. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.

Additional Notes

This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.

I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

Regexp Java for password validation

easy one

("^ (?=.* [0-9]) (?=.* [a-z]) (?=.* [A-Z]) (?=.* [\\W_])[\\S]{8,10}$")

  1. (?= anything ) ->means positive looks forward in all input string and make sure for this condition is written .sample(?=.*[0-9])-> means ensure one digit number is written in the all string.if not written return false .

  2. (?! anything ) ->(vise versa) means negative looks forward if condition is written return false.

    close meaning ^(condition)(condition)(condition)(condition)[\S]{8,10}$

What does "make oldconfig" do exactly in the Linux kernel makefile?

From this page:

Make oldconfig takes the .config and runs it through the rules of the Kconfig files and produces a .config which is consistant with the Kconfig rules. If there are CONFIG values which are missing, the make oldconfig will ask for them.

If the .config is already consistant with the rules found in Kconfig, then make oldconfig is essentially a no-op.

If you were to run make oldconfig, and then run make oldconfig a second time, the second time won't cause any additional changes to be made.

R: Print list to a text file

depending on your tastes, an alternative to nico's answer:

d<-lapply(mylist, write, file=" ... ", append=T);

Confirm Password with jQuery Validate

It works if id value and name value are different:

<input type="password" class="form-control"name="password" id="mainpassword">
password: {     required: true,     } , 
cpassword: {required: true, equalTo: '#mainpassword' },

How to make --no-ri --no-rdoc the default for gem install?

# /home/{user}/.gemrc

---
:update_sources: true
:sources:
- http://gems.rubyforge.org/
- http://gems.github.com
:benchmark: false
:bulk_threshold: 1000
:backtrace: false
:verbose: true
gem: --no-ri --no-rdoc

http://webonrails.com/2008/12/03/skiping-installation-of-ri-and-rdoc-documentation-while-installing-gems/

generate a random number between 1 and 10 in c

srand(time(NULL));

int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);

How to use moment.js library in angular 2 typescript app?

for angular2 RC5 this worked for me...

first install moment via npm

npm install moment --save

Then import moment in the component that you want to use it

import * as moment from 'moment';

lastly configure moment in systemjs.config.js "map" and "packages"

// map tells the System loader where to look for things
  var map = {
  ....
  'moment':                     'node_modules/moment'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    ...
    'moment':                       { main:'moment', defaultExtension: 'js'}
  };

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

Make sure that all these libs are in your class path:

compile(group: 'com.sun.jersey', name: 'jersey-core',        version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-server',      version: '1.19.4') 
compile(group: 'com.sun.jersey', name: 'jersey-servlet',     version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-json',        version: '1.19.4')
compile(group: 'com.sun.jersey', name: 'jersey-client',      version: '1.19.4')
compile(group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-core-asl',   version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-jaxrs',      version: '1.9.2')
compile(group: 'org.codehaus.jackson', name: 'jackson-xc',         version: '1.9.2')

Add "Pojo Mapping" and "Jackson Provider" to the jersey client config:

ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
clientConfig.getClasses().add(JacksonJsonProvider.class);

This solve to me!

ClientResponse response = null;

response = webResource
        .type(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON)
        .get(ClientResponse.class);


if (response.getStatus() == Response.Status.OK.getStatusCode()) {

    MyClass myclass = response.getEntity(MyClass.class);
    System.out.println(myclass);
}

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

According to this: https://www.simplified.guide/phpmyadmin/enable-login-without-password

This $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; should be added twice in /etc/phpmyadmin/config.inc.php

if (!empty($dbname)) {
    // other configuration options
    $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
    // it should be placed before the following line
    $i++;
}

// other configuration options
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

How to read xml file contents in jQuery and display in html elements?

_x000D_
_x000D_
 $.get("/folder_name/filename.xml", function (xml) {_x000D_
 var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
 });
_x000D_
_x000D_
_x000D_

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

How to stop an unstoppable zombie job on Jenkins without restarting the server?

You can just copy the job and delete the old one. If it doesn't matter that you lost the old build logs.

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

How to window.scrollTo() with a smooth effect

$('html, body').animate({scrollTop:1200},'50');

You can do this!

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

Convert JSON to Map

I like google gson library.
When you don't know structure of json. You can use

JsonElement root = new JsonParser().parse(jsonString);

and then you can work with json. e.g. how to get "value1" from your gson:

String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();

Compiler error: "initializer element is not a compile-time constant"

The reason is that your are defining your imageSegment outside of a function in your source code (static variable).

In such cases, the initialization cannot include execution of code, like calling a function or allocation a class. Initializer must be a constant whose value is known at compile time.

You can then initialize your static variable inside of your init method (if you postpone its declaration to init).

Java using scanner enter key pressed

Scanner scan = new Scanner(System.in);
        int i = scan.nextInt();
        Double d = scan.nextDouble();


        String newStr = "";
        Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
        while( charScanner.hasNext() ) { 
            String  c = charScanner.next();

            if (c.equalsIgnoreCase("\r")) {
                break;
            }
            else {
                newStr += c;    
            }
        }

        System.out.println("String: " + newStr);
        System.out.println("Int: " + i);
        System.out.println("Double: " + d);

This code works fine

ReferenceError: Invalid left-hand side in assignment

Common reasons for the error:

  • use of assignment (=) instead of equality (==/===)
  • assigning to result of function foo() = 42 instead of passing arguments (foo(42))
  • simply missing member names (i.e. assuming some default selection) : getFoo() = 42 instead of getFoo().theAnswer = 42 or array indexing getArray() = 42 instead of getArray()[0]= 42

In this particular case you want to use == (or better === - What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock"), but it the actual reason you are getting the error is trickier.

The reason for the error is Operator precedence. In particular we are looking for && (precedence 6) and = (precedence 3).

Let's put braces in the expression according to priority - && is higher than = so it is executed first similar how one would do 3+4*5+6 as 3+(4*5)+6:

 if(one= ("rock" && two) = "rock"){...

Now we have expression similar to multiple assignments like a = b = 42 which due to right-to-left associativity executed as a = (b = 42). So adding more braces:

 if(one= (  ("rock" && two) = "rock" )  ){...

Finally we arrived to actual problem: ("rock" && two) can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two as truthy).

Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do && on two strings "rock" && "rock" resulting in "rock" (which in turn is truthy) all the time due to behavior of logial &&:

if((one = "rock") && (two = "rock"))
{
   // always executed, both one and two are set to "rock"
   ...
}

For even more details on the error and other cases when it can happen - see specification:

Assignment

LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true

Left-Hand-Side Expressions

and The Reference Specification Type explaining IsStrictReference:

... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...

simple way to display data in a .txt file on a webpage?

You can add it as script file. save the txt file with js suffix

in the head section add

_x000D_
_x000D_
<script src="fileName.js"></script>
_x000D_
_x000D_
_x000D_

Run git pull over all subdirectories

This should happen automatically, so long as cms, admin and chart are all parts of the repository.

A likely issue is that each of these plugins is a git submodule.

Run git help submodule for more information.

EDIT

For doing this in bash:

cd plugins
for f in cms admin chart
do 
  cd $f && git pull origin master && cd ..
done

Save results to csv file with Python

You can close files not csv.writer object, it should be:

f = open(fileName, "wb")
writer = csv.writer(f)
String[] entries = "first*second*third".split("*");
writer.writerows(entries)
f.close()

Getting the array length of a 2D array in Java

Try this following program for 2d array in java:

public class ArrayTwo2 {
    public static void main(String[] args) throws  IOException,NumberFormatException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[][] a;
        int sum=0;
        a=new int[3][2];
        System.out.println("Enter array with 5 elements");
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            a[i][j]=Integer.parseInt(br.readLine());
            }
        }
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[0].length;j++)
            {
            System.out.print(a[i][j]+"  ");
            sum=sum+a[i][j];
            }
        System.out.println();   
        //System.out.println("Array Sum: "+sum);
        sum=0;
        }
    }
}

How to create an array of object literals in a loop?

var myColumnDefs = new Array();

for (var i = 0; i < oFullResponse.results.length; i++) {
    myColumnDefs.push({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}

Converting HTML to plain text in PHP for e-mail

You can test this function

function html2text($Document) {
    $Rules = array ('@<script[^>]*?>.*?</script>@si',
                    '@<[\/\!]*?[^<>]*?>@si',
                    '@([\r\n])[\s]+@',
                    '@&(quot|#34);@i',
                    '@&(amp|#38);@i',
                    '@&(lt|#60);@i',
                    '@&(gt|#62);@i',
                    '@&(nbsp|#160);@i',
                    '@&(iexcl|#161);@i',
                    '@&(cent|#162);@i',
                    '@&(pound|#163);@i',
                    '@&(copy|#169);@i',
                    '@&(reg|#174);@i',
                    '@&#(d+);@e'
             );
    $Replace = array ('',
                      '',
                      '',
                      '',
                      '&',
                      '<',
                      '>',
                      ' ',
                      chr(161),
                      chr(162),
                      chr(163),
                      chr(169),
                      chr(174),
                      'chr()'
                );
  return preg_replace($Rules, $Replace, $Document);
}

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

I would use this in HTML 5... Just sayin

#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #f5f5f5;
}

Adding backslashes without escaping [Python]

Python treats \ in literal string in a special way.
This is so you can type '\n' to mean newline or '\t' to mean tab
Since '\&' doesn't mean anything special to Python, instead of causing an error, the Python lexical analyser implicitly adds the extra \ for you.

Really it is better to use \\& or r'\&' instead of '\&'

The r here means raw string and means that \ isn't treated specially unless it is right before the quote character at the start of the string.

In the interactive console, Python uses repr to display the result, so that is why you see the double '\'. If you print your string or use len(string) you will see that it is really only the 2 characters

Some examples

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

To Clarify the point Peter makes in his comment see this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as “(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

How to show code but hide output in RMarkdown?

To hide warnings, you can also do {r, warning=FALSE}

How to find index of list item in Swift?

You can filter an array with a closure:

var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 }  // <= returns [3]

And you can count an array:

filtered.count // <= returns 1

So you can determine if an array includes your element by combining these:

myList.filter { $0 == 3 }.count > 0  // <= returns true if the array includes 3

If you want to find the position, I don't see fancy way, but you can certainly do it like this:

var found: Int?  // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
    if x[i] == 3 {
        found = i
    }
}

EDIT

While we're at it, for a fun exercise let's extend Array to have a find method:

extension Array {
    func find(includedElement: T -> Bool) -> Int? {
        for (idx, element) in enumerate(self) {
            if includedElement(element) {
                return idx
            }
        }
        return nil
    }
}

Now we can do this:

myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found

IntelliJ - Convert a Java project/module into a Maven project/module

I want to add the important hint that converting a project like this can have side effects which are noticeable when you have a larger project. This is due the fact that Intellij Idea (2017) takes some important settings only from the pom.xml then which can lead to some confusion, following sections are affected at least:

  1. Annotation settings are changed for the modules
  2. Compiler output path is changed for the modules
  3. Resources settings are ignored totally and only taken from pom.xml
  4. Module dependencies are messed up and have to checked
  5. Language/Encoding settings are changed for the modules

All these points need review and adjusting but after this it works like charm.

Further more unfortunately there is no sufficient pom.xml template created, I have added an example which might help to solve most problems.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Name</groupId>
<artifactId>Artifact</artifactId>
<version>4.0</version>
<properties>
    <!-- Generic properties -->
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
    <!--All dependencies to put here, including module dependencies-->
</dependencies>
<build>
    <directory>${project.basedir}/target</directory>
    <outputDirectory>${project.build.directory}/classes</outputDirectory>
    <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <testSourceDirectory> ${project.basedir}/src/test/java</testSourceDirectory>

    <resources>
        <resource>
            <directory>${project.basedir}/src/main/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <annotationProcessors/>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Edit 2019:

  • Added recursive resource scan
  • Added directory specification which might be important to avoid confusion of IDEA recarding the content root structure

This application has no explicit mapping for /error

Try adding the dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Creating a very simple 1 username/password login in php

Your code could look more like:

<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
  $username = $_POST['username']; $password = $_POST['password'];
  if($username === 'admin' && $password === 'password'){
    $_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
  }
  if($username !== 'admin')$userError = 'Invalid Username';
  if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <style type='text.css'>
       @import common.css;
     </style>
   </head>
<body>
  <form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
    <label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
    <div class='error'><?php echo $userError;?></div>
    <label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
    <div class='error'><?php echo $passError;?></div>
    <input type='submit' value='Home' name='sub' />
  </form>
  <script type='text/javascript' src='common.js'></script>
</body>
</html>

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

Console output in a Qt GUI app?

Make sure Qt5Core.dll is in the same directory with your application executable.

I had a similar issue in Qt5 with a console application: if I start the application from Qt Creator, the output text is visible, if I open cmd.exe and start the same application there, no output is visible. Very strange!

I solved it by copying Qt5Core.dll to the directory with the application executable.

Here is my tiny console application:

#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    int x=343;
    QString str("Hello World");
    qDebug()<< str << x<<"lalalaa";

    QTextStream out(stdout);
    out << "aldfjals alsdfajs...";
}

Insert results of a stored procedure into a temporary table

If the OPENROWSET is causing you issues, there is another way from 2012 onwards; make use of sys.dm_exec_describe_first_result_set_for_object, as mentioned here: Retrieve column names and types of a stored procedure?

First, create this stored procedure to generate the SQL for the temporary table:

CREATE PROCEDURE dbo.usp_GetStoredProcTableDefinition(
    @ProcedureName  nvarchar(128),
    @TableName      nvarchar(128),
    @SQL            nvarchar(max) OUTPUT
)
AS
SET @SQL = 'CREATE TABLE ' + @tableName + ' ('

SELECT @SQL = @SQL + '['+name +'] '+ system_type_name +''  + ','
        FROM sys.dm_exec_describe_first_result_set_for_object
        (
          OBJECT_ID(@ProcedureName), 
          NULL
        );

--Remove trailing comma
SET @SQL = SUBSTRING(@SQL,0,LEN(@SQL))    
SET @SQL =  @SQL +')'

To use the procedure, call it in the following way:

DECLARE     @SQL    NVARCHAR(MAX)

exec dbo.usp_GetStoredProcTableDefinition
    @ProcedureName='dbo.usp_YourProcedure',
    @TableName='##YourGlobalTempTable',@SQL = @SQL OUTPUT

INSERT INTO ##YourGlobalTempTable
EXEC    [dbo].usp_YourProcedure

select * from ##YourGlobalTempTable

Note that I'm using a global temporary table. That's because using EXEC to run the dynamic SQL creates its own session, so an ordinary temporary table would be out of scope to any subsequent code. If a global temporary table is a problem, you can use an ordinary temporary table, but any subsequent SQL would need to be dynamic, that is, also executed by the EXEC statement.

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

In using toolbar you should extends AppCompatActivity and

import android.support.v7.widget.Toolbar 

How to run PowerShell in CMD

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

How to convert string to binary?

Something like this?

>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'

OR operator in switch-case?

You cannot use || operators in between 2 case. But you can use multiple case values without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a "break". As a result these cases will share the same code.

switch(value) 
{ 
    case 0: 
    case 1: 
        // do stuff for if case 0 || case 1 
        break; 
    // other cases 
    default: 
        break; 
}

Running multiple commands with xargs

Another possible solution that works for me is something like -

cat a.txt | xargs bash -c 'command1 $@; command2 $@' bash

Note the 'bash' at the end - I assume it is passed as argv[0] to bash. Without it in this syntax the first parameter to each command is lost. It may be any word.

Example:

cat a.txt | xargs -n 5 bash -c 'echo -n `date +%Y%m%d-%H%M%S:` ; echo " data: " $@; echo "data again: " $@' bash

How to store Java Date to Mysql datetime with JPA

Annotate your field (or getter) with @Temporal(TemporalType.TIMESTAMP), like this:

public class MyEntity {
    ...
    @Temporal(TemporalType.TIMESTAMP)
    private java.util.Date myDate;
    ...
}

That should do the trick.

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

Entity Framework Query for inner join

In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:

db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);

If you don't, unless there's some Join() override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):

db.Services.Join(db.ServiceAssignments, 
     s => s.Id,
     sa => sa.ServiceId, 
     (s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);

Can You Get A Users Local LAN IP Address Via JavaScript?

You can find more info about what limitations browsers will likely add to mitigate this and what IETF is doing about it as well as why this is needed at IETF SPEC on IP handling

Add padding to HTML text input field

<input class="form-control search-query input_style" placeholder="Search…"  name="" title="Search for:" type="text">


.input_style
{
    padding-left:20px;
}

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

When trying to generate a random password you are trying to :

  • First generate a cryptographically secure set of random bytes

  • Second is turning those random bytes into a printable string

Now, there are multiple way to generate random bytes in php like :

$length = 32;

//PHP 7+
$bytes= random_bytes($length);

//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);

Then you want to turn these random bytes into a printable string :

You can use bin2hex :

$string = bin2hex($bytes);

or base64_encode :

$string = base64_encode($bytes);

However, note that you do not control the length of the string if you use base64. You can use bin2hex to do that, using 32 bytes will turn into a 64 char string. But it will only work like so in an EVEN string.

So basically you can just do :

$length = 32;

if(PHP_VERSION>=7){
    $bytes= random_bytes($length);
}else{
    $bytes= openssl_random_pseudo_bytes($length);
} 

$string = bin2hex($bytes);

Using success/error/finally/catch with Promises in AngularJS

What type of granularity are you looking for? You can typically get by with:

$http.get(url).then(
  //success function
  function(results) {
    //do something w/results.data
  },
  //error function
  function(err) {
    //handle error
  }
);

I've found that "finally" and "catch" are better off when chaining multiple promises.

How to get Locale from its String representation in Java?

Option 1 :

org.apache.commons.lang3.LocaleUtils.toLocale("en_US")

Option 2 :

Locale.forLanguageTag("en-US")

Please note Option 1 is "underscore" between language and country , and Option 2 is "dash".

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

How to find out what this MySQL Error is trying to say:

#1064 - You have an error in your SQL syntax;

This error has no clues in it. You have to double check all of these items to see where your mistake is:

  1. You have omitted, or included an unnecessary symbol: !@#$%^&*()-_=+[]{}\|;:'",<>/?
  2. A misplaced, missing or unnecessary keyword: select, into, or countless others.
  3. You have unicode characters that look like ascii characters in your query but are not recognized.
  4. Misplaced, missing or unnecessary whitespace or newlines between keywords.
  5. Unmatched single quotes, double quotes, parenthesis or braces.

Take away as much as you can from the broken query until it starts working. And then use PostgreSQL next time that has a sane syntax reporting system.

SQL JOIN, GROUP BY on three tables to get totals

I am not sure I got you but this might be what you are looking for:

SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid

This would get you the amounts sums in case there are multiple payment rows for each invoice

Connection string with relative path to the database file

   <?xml version="1.0"?>  
<configuration>  
  <appSettings>  
    <!--FailIfMissing=false -->  
    <add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>  
  </appSettings>  
</configuration>  

Simultaneously merge multiple data.frames in a list

You can do it using merge_all in the reshape package. You can pass parameters to merge using the ... argument

reshape::merge_all(list_of_dataframes, ...)

Here is an excellent resource on different methods to merge data frames.

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Converting EditText to int? (Android)

Try the line below to convert editText to integer.

int intVal = Integer.parseInt(mEtValue.getText().toString());

MySQL Where DateTime is greater than today

I guess you looking for CURDATE() or NOW() .

  SELECT name, datum 
  FROM tasks 
  WHERE datum >= CURDATE()

LooK the rsult of NOW and CURDATE

   NOW()                    CURDATE()        
   2008-11-11 12:45:34      2008-11-11       

How do I turn off the mysql password validation?

For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html

Then you should edit your mysqld.cnf file, for instance :

vim /etc/mysql/mysql.conf.d/mysqld.cnf

Then, add in the [mysqld] part, the following :

plugin-load-add=validate_password.so
validate_password_policy=LOW

Basically, if you edit your default, it will looks like :

[mysqld]
#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW

Then, you can restart:

systemctl restart mysql

If you forget the plugin-load-add=validate_password.so part, you will it an error at restart.

Enjoy !

Found 'OR 1=1/* sql injection in my newsletter database

'OR 1=1 is an attempt to make a query succeed no matter what
The /* is an attempt to start a multiline comment so the rest of the query is ignored.

An example would be

SELECT userid 
FROM users 
WHERE username = ''OR 1=1/*' 
    AND password = ''
    AND domain = ''

As you can see if you were to populate the username field without escaping the ' no matter what credentials the user passes in the query would return all userids in the system likely granting access to the attacker (possibly admin access if admin is your first user). You will also notice the remainder of the query would be commented out because of the /* including the real '.

The fact that you can see the value in your database means that it was escaped and that particular attack did not succeed. However, you should investigate if any other attempts were made.

How do I get the color from a hexadecimal color code using .NET?

Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:

System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");

If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:

Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or      = (Color) ColorConverter.ConvertFromString("#FFCC66") ;

Git asks for username every time I push

Quick method

get url of your git when inside working dir :

git config remote.origin.url

then :

git config credential.helper store

git push "url of your git"

will ask username and password last one time

done.

How do I compile with -Xlint:unchecked?

Specify it on the command line for javac:

javac -Xlint:unchecked

Or if you are using Ant modify your javac target

  <javac ...>
    <compilerarg value="-Xlint"/>
  </javac> 

If you are using Maven, configure this in the maven-compiler-plugin

<compilerArgument>-Xlint:unchecked</compilerArgument>

Combine two columns and add into one new column

Generally, I agree with @kgrittn's advice. Go for it.

But to address your basic question about concat(): The new function concat() is useful if you need to deal with null values - and null has neither been ruled out in your question nor in the one you refer to.

If you can rule out null values, the good old (SQL standard) concatenation operator || is still the best choice, and @luis' answer is just fine:

SELECT col_a || col_b;

If either of your columns can be null, the result would be null in that case. You could defend with COALESCE:

SELECT COALESCE(col_a, '') || COALESCE(col_b, '');

But that get tedious quickly with more arguments. That's where concat() comes in, which never returns null, not even if all arguments are null. Per documentation:

NULL arguments are ignored.

SELECT concat(col_a, col_b);

The remaining corner case for both alternatives is where all input columns are null in which case we still get an empty string '', but one might want null instead (at least I would). One possible way:

SELECT CASE
          WHEN col_a IS NULL THEN col_b
          WHEN col_b IS NULL THEN col_a
          ELSE col_a || col_b
       END;

This gets more complex with more columns quickly. Again, use concat() but add a check for the special condition:

SELECT CASE WHEN (col_a, col_b) IS NULL THEN NULL
            ELSE concat(col_a, col_b) END;

How does this work?
(col_a, col_b) is shorthand notation for a row type expression ROW (col_a, col_b). And a row type is only null if all columns are null. Detailed explanation:

Also, use concat_ws() to add separators between elements (ws for "with separator").


An expression like the one in Kevin's answer:

SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;

is tedious to prepare for null values in PostgreSQL 8.3 (without concat()). One way (of many):

SELECT COALESCE(
         CASE
            WHEN $1.zipcode IS NULL THEN $1.city
            WHEN $1.city    IS NULL THEN $1.zipcode
            ELSE $1.zipcode || ' - ' || $1.city
         END, '')
       || COALESCE(', ' || $1.state, '');

Function volatility is only STABLE

concat() and concat_ws() are STABLE functions, not IMMUTABLE because they can invoke datatype output functions (like timestamptz_out) that depend on locale settings.
Explanation by Tom Lane.

This prohibits their direct use in index expressions. If you know that the result is actually immutable in your case, you can work around this with an IMMUTABLE function wrapper. Example here:

How to make padding:auto work in CSS?

if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:

* {
  padding: initial;
}

if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.

MySQL INNER JOIN select only one row from second table

SELECT u.*, p.*, max(p.date)
FROM payments p
JOIN users u ON u.id=p.user_id AND u.package = 1
GROUP BY u.id
ORDER BY p.date DESC

Check out this sqlfiddle

How can I get the image url in a Wordpress theme?

get_template_directory_uri();

This function will help you retrieve theme directory URI, and can be used with your images, your example below:

<img src="<?php echo get_template_directory_uri(); ?>/images/mindset.jpg" />

Using iFrames In ASP.NET

You can think of an iframe as an embedded browser window that you can put on an HTML page to show another URL inside it. This URL can be totally distinct from your web site/app.

You can put an iframe in any HTML page, so you could put one inside a contentplaceholder in a webform that has a Masterpage and it will appear with whatever URL you load into it (via Javascript, or C# if you turn your iframe into a server-side control (runat='server') on the final HTML page that your webform produces when requested.

And you can load a URL into your iframe that is a .aspx page.

But - iframes have nothing to do with the ASP.net mechanism. They are HTML elements that can be made to run server-side, but they are essentially 'dumb' and unmanaged/unconnected to the ASP.Net mechanisms - don't confuse a Contentplaceholder with an iframe.

Incidentally, the use of iframes is still contentious - do you really need to use one? Can you afford the negative trade-offs associated with them e.g. lack of navigation history ...?

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

How to get Javascript Select box's selected text

I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()

Sql connection-string for localhost server

Using the default instance (i.e., MSSQLSERVER, use the DOT (.))

<add name="CONNECTION_STRING_NAME" connectionString="Data Source=.;Initial Catalog=DATABASE_NAME;Integrated Security=True;" />

Mockito How to mock only the call of a method of the superclass

The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.

public class BaseService{
  public boolean foo(){
    return true;
  }
}

public ChildService extends BaseService{
}

@Test
@Mock ChildService childService;
public void testSave() {
  Mockito.when(childService.foo()).thenReturn(false);

  // When
  assertFalse(childService.foo());
}

Compare given date with today

Some given answers don't have in consideration the current day!

Here it is my proposal.

$var = "2010-01-21 00:00:00.0"
$given_date = new \DateTime($var);

if ($given_date == new \DateTime('today')) {
  //today
}

if ($given_date < new \DateTime('today')) {
  //past
}

if ($given_date > new \DateTime('today')) {
  //future
}

Error sending json in POST to web API service

  1. You have to must add header property Content-Type:application/json
  2. When you define any POST request method input parameter that should be annotated as [FromBody], e.g.:

    [HttpPost]
    public HttpResponseMessage Post([FromBody]ActivityResult ar)
    {
      return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
  3. Any JSON input data must be raw data.

How might I force a floating DIV to match the height of another floating DIV?

You can always use a background image to do it too. I tend to vote for this option 100% of the time as the only other perfect solution is the Jquery option.

As with using the outer div with a background color you'll end up having to have the content in both divs reaching the same height.

Mockito: List Matchers with generics

For Java 8 and above, it's easy:

when(mock.process(Matchers.anyList()));

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz):

when(mock.process(Matchers.anyListOf(Bar.class)));

How do I get a file's directory using the File object?

You can use this

 File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

Run Command Prompt Commands

Yes, there is (see link in Matt Hamilton's comment), but it would be easier and better to use .NET's IO classes. You can use File.ReadAllBytes to read the files and then File.WriteAllBytes to write the "embedded" version.

The remote host closed the connection. The error code is 0x800704CD

I was getting this on an asp.net 2.0 iis7 Windows2008 site. Same code on iis6 worked fine. It was causing an issue for me because it was messing up the login process. User would login and get a 302 to default.asxp, which would get through page_load, but not as far as pre-render before iis7 would send a 302 back to login.aspx without the auth cookie. I started playing with app pool settings, and for some reason 'enable 32 bit applications' seems to have fixed it. No idea why, since this site isn't doing anything special that should require any 32 bit drivers. We have some sites that still use Access that require 32bit, but not our straight SQL sites like this one.

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

Getting Access Denied when calling the PutObject operation with bucket-level permission

If you have set public access for bucket and if it is still not working, edit bucker policy and paste following:

    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:GetObject",
                "s3:GetObjectAcl",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::yourbucketnamehere",
                "arn:aws:s3:::yourbucketnamehere/*"
            ],
            "Effect": "Allow",
            "Principal": "*"
        }
    ]
}

Clicking HTML 5 Video element to play, pause video, breaks play button

I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.

    var v = document.getElementById('videoID');
    v.addEventListener(
       'play', 
          function() { 
             v.play();
          }, 
        false);

    v.onclick = function() {
      if (v.paused) {
        v.play();
        v.controls=null;
      } else {
        v.pause();
        v.controls="controls";
      }
    };

Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.

Anyone have a solution to that?

Struct with template variables in C++

You can template a struct as well as a class. However you can't template a typedef. So template<typename T> struct array {...}; works, but template<typename T> typedef struct {...} array; does not. Note that there is no need for the typedef trick in C++ (you can use structs without the struct modifier just fine in C++).

CALL command vs. START with /WAIT option

For exe files, I suppose the differences are nearly unimportant.
But to start an exe you don't even need CALL.

When starting another batch it's a big difference,
as CALL will start it in the same window and the called batch has access to the same variable context.
So it can also change variables which affects the caller.

START will create a new cmd.exe for the called batch and without /b it will open a new window.
As it's a new context, variables can't be shared.

Differences

Using start /wait <prog>
- Changes of environment variables are lost when the <prog> ends
- The caller waits until the <prog> is finished

Using call <prog>
- For exe it can be ommited, because it's equal to just starting <prog>
- For an exe-prog the caller batch waits or starts the exe asynchronous, but the behaviour depends on the exe itself.
- For batch files, the caller batch continues, when the called <batch-file> finishes, WITHOUT call the control will not return to the caller batch

Addendum:

Using CALL can change the parameters (for batch and exe files), but only when they contain carets or percent signs.

call myProg param1 param^^2 "param^3" %%path%%

Will be expanded to (from within an batch file)

myProg param1 param2 param^^3 <content of path>

Build tree array from flat array in javascript

Here's a simple helper function that I created modeled after the above answers, tailored to a Babel environment:

import { isEmpty } from 'lodash'

export default function unflattenEntities(entities, parent = {id: null}, tree = []) {

  let children = entities.filter( entity => entity.parent_id == parent.id)

  if (!isEmpty( children )) {
    if ( parent.id == null ) {
      tree = children
    } else {
      parent['children'] = children
    }
    children.map( child => unflattenEntities( entities, child ) )
  }

  return tree

}

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

If there is an on-screen keyboard, focusing a text field that is near the bottom of the viewport will cause Safari to scroll the text field into view. There might be some way to exploit this phenomenon to detect the presence of the keyboard (having a tiny text field at the bottom of the page which gains focus momentarily, or something like that).

Django: Model Form "object has no attribute 'cleaned_data'"

I would write the code like this:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

Pretty much like the documentation.

How to get the number of columns from a JDBC ResultSet?

Number of a columns in the result set you can get with code (as DB is used PostgreSQL):

//load the driver for PostgreSQL
Class.forName("org.postgresql.Driver");

String url = "jdbc:postgresql://localhost/test";
Properties props = new Properties();
props.setProperty("user","mydbuser");
props.setProperty("password","mydbpass");
Connection conn = DriverManager.getConnection(url, props);

//create statement
Statement stat = conn.createStatement();

//obtain a result set
ResultSet rs = stat.executeQuery("SELECT c1, c2, c3, c4, c5 FROM MY_TABLE");

//from result set give metadata
ResultSetMetaData rsmd = rs.getMetaData();

//columns count from metadata object
int numOfCols = rsmd.getColumnCount();

But you can get more meta-informations about columns:

for(int i = 1; i <= numOfCols; i++)
{
    System.out.println(rsmd.getColumnName(i));
}

And at least but not least, you can get some info not just about table but about DB too, how to do it you can find here and here.

What's the @ in front of a string in C#?

Putting a @ in front of a string enables you to use special characters such as a backslash or double-quotes without having to use special codes or escape characters.

So you can write:

string path = @"C:\My path\";

instead of:

string path = "C:\\My path\\";

How can I show an image using the ImageView component in javafx and fxml?

@FXML
ImageView image;

@Override
public void initialize(URL url, ResourceBundle rb) {
  image.setImage(new Image ("/about.jpg"));
}

Bi-directional Map in Java?

Creating a Guava BiMap and getting its inverted value is not so trivial.

A simple example:

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class BiMapTest {

  public static void main(String[] args) {

    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("k1", "v1");
    biMap.put("k2", "v2");

    System.out.println("k1 = " + biMap.get("k1"));
    System.out.println("v2 = " + biMap.inverse().get("v2"));
  }
}

Undo a particular commit in Git that's been pushed to remote repos

If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1 or -m 2 option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.

  • git revert <commit> -m 1
  • git revert <commit> -m 2

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

Usually what you choose will depend on which methods you need access to. In general - IEnumerable<> (MSDN: http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx) for a list of objects that only needs to be iterated through, ICollection<> (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx).

From a more specific standpoint, lazy loading comes in to play with choosing the type. By default, navigation properties in Entity Framework come with change tracking and are proxies. In order for the dynamic proxy to be created as a navigation property, the virtual type must implement ICollection.

A navigation property that represents the "many" end of a relationship must return a type that implements ICollection, where T is the type of the object at the other end of the relationship. -Requirements for Creating POCO ProxiesMSDN

More information on Defining and Managing RelationshipsMSDN

Arrays vs Vectors: Introductory Similarities and Differences

I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).

Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.

rsync copy over only certain types of files using include option

The answer by @chepner will copy all the sub-directories irrespective of the fact if it contains the file or not. If you need to exclude the sub-directories that dont contain the file and still retain the directory structure, use

rsync -zarv  --prune-empty-dirs --include "*/"  --include="*.sh" --exclude="*" "$from" "$to"

Two arrays in foreach loop

foreach( $codes as $code and $names as $name ) { }

That is not valid.

You probably want something like this...

foreach( $codes as $index => $code ) {
   echo '<option value="' . $code . '">' . $names[$index] . '</option>';
}

Alternatively, it'd be much easier to make the codes the key of your $names array...

$names = array(
   'tn' => 'Tunisia',
   'us' => 'United States',
   ...
);

Linux command for extracting war file?

You can use the unzip command.

MySQL: selecting rows where a column is null

SQL NULL's special, and you have to do WHERE field IS NULL, as NULL cannot be equal to anything,

including itself (ie: NULL = NULL is always false).

See Rule 3 https://en.wikipedia.org/wiki/Codd%27s_12_rules

How to set environment variables in Python?

You should assign string value to environment variable.

os.environ["DEBUSSY"] = "1"

If you want to read or print the environment variable just use

print os.environ["DEBUSSY"]

This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.

enter image description here

How to set custom header in Volley Request

That is my code, dont forget = object: if don't put don't works

val queue = Volley.newRequestQueue(this)
        val url = "http://35.237.133.137:8080/lamarrullaWS/rest/lamarrullaAPI"
        // Request a string response from the provided URL.
        val jsonObjectRequest = object: JsonObjectRequest(Request.Method.GET, url, null,
                Response.Listener { response ->
                    txtPrueba.text = "Response: %s".format(response.toString())
                },
                Response.ErrorListener { txtPrueba.text = "That didn't work!" }
        )
        {
            @Throws(AuthFailureError::class)
            override fun getHeaders(): Map<String, String> {
                val headers = HashMap<String, String>()
                headers.put("Content-Type", "application/json")
                return headers
            }
        }
        queue.add(jsonObjectRequest)

How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

function savedata1() { 

var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
    td_1: $row.find(':nth-child(1)').text(),
    td_2: $row.find(':nth-child(2)').text(),
    td_3: $row.find(':nth-child(3)').text()
   };
}).get();

logout and redirecting session in php

<?php
session_start();
session_destroy();
header("Location: home.php");
?>

Tool for sending multipart/form-data request

UPDATE: I have created a video on sending multipart/form-data requests to explain this better.


Actually, Postman can do this. Here is a screenshot

Newer version : Screenshot captured from postman chrome extension enter image description here

Another version

enter image description here

Older version

enter image description here

Make sure you check the comment from @maxkoryukov

Be careful with explicit Content-Type header. Better - do not set it's value, the Postman is smart enough to fill this header for you. BUT, if you want to set the Content-Type: multipart/form-data - do not forget about boundary field.

How to create Android Facebook Key Hash?

Here is what you need to do -

Download openSSl from Code Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.

detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.

detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-

$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64

it will ask for password, put android that's all. u will get a key-hash

Counter inside xsl:for-each loop

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <newBooks>
                <xsl:for-each select="books/book">
                        <newBook>
                                <countNo><xsl:value-of select="position()"/></countNo>
                                <title>
                                        <xsl:value-of select="title"/>
                                </title>
                        </newBook>
                </xsl:for-each>
        </newBooks>
    </xsl:template>
</xsl:stylesheet>

Angular - Use pipes in services and components

As usual in Angular, you can rely on dependency injection:

import { DatePipe } from '@angular/common';

class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

providers: [DatePipe,...]

Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate function directly.

import { formatDate } from '@angular/common';

class MyService {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}

Before Angular 5: Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

Redirect pages in JSP?

Just define the target page in the action attribute of the <form> containing the submit button.

So, in page1.jsp:

<form action="page2.jsp">
    <input type="submit">
</form>

Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.

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

None of these suggestions above worked for me as-is. I had to use the following to center a checkbox with the label text displayed to the right of the box:

<style>
.checkboxes {
  display: flex;
  justify-content: center;
  align-items: center;
  vertical-align: middle;
  word-wrap: break-word;
}
</style>

<label for="checkbox1" class="checkboxes"><input type="checkbox" id="checkbox1" name="checked" value="yes" class="checkboxes"/>
Check the box.</label>

how can I display tooltip or item information on mouse over?

The simplest way to get tooltips in most browsers is to set some text in the title attribute.

eg.

<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />

produces (hover your mouse over the image):

a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg

Title attributes can be applied to most HTML elements.

Toad for Oracle..How to execute multiple statements?

  1. Just finsih all of your queries with ;
  2. Select all queries you need (inserts, selects, ...).
  3. Push or F5 or F9 both Works.

Not necessary to execute as script

PHP convert string to hex and hex to string

For people that end up here and are just looking for the hex representation of a (binary) string.

bin2hex("that's all you need");
# 74686174277320616c6c20796f75206e656564

hex2bin('74686174277320616c6c20796f75206e656564');
# that's all you need

Doc: bin2hex, hex2bin.

JavaScript: How to get parent element by selector?

Finds the closest parent (or the element itself) that matches the given selector. Also included is a selector to stop searching, in case you know a common ancestor that you should stop searching at.

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.matches(selector)) {
      retval = el;
      break
    } else if (stopSelector && el.matches(stopSelector)) {
      break
    }
    el = el.parentElement;
  }
  return retval;
}

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

if You use spring boot , you should add origin link in the @CrossOrigin annotation

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/yourPath")

You can find detailed instruction in the https://spring.io/guides/gs/rest-service-cors/

Display PDF within web browser

We render the PDF file pages as PNG files on the server using JPedal (a java library). That, combined with some javascript, gives us high control over visualization and navigation.

Parsing JSON from XmlHttpRequest.responseJSON

I think you have to include jQuery to use responseJSON.

Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");

UPDATE:Please read the comment regarding eval, you can test with eval, but don't use it in working extension.

OR

use json_parse : it does not use eval

How to do jquery code AFTER page loading?

write the code that you want to be executed inside this. When your document is ready, this will be executed.

$(document).ready(function() { 

});

PowerShell Connect to FTP server and get files

Invoke-WebRequest can download HTTP, HTTPS, and FTP links.

$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password

# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing

Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.

How to use function srand() with time.h?

You need to call srand() once, to randomize the seed, and then call rand() in your loop:

#include <stdlib.h>
#include <time.h>

#define size 10

srand(time(NULL)); // randomize seed

for(i=0;i<size;i++)
    Arr[i] = rand()%size;

Which is better, return value or out parameter?

Using the out keyword with a return type of bool, can sometimes reduce code bloat and increase readability. (Primarily when the extra info in the out param is often ignored.) For instance:

var result = DoThing();
if (result.Success)
{
    result = DoOtherThing()
    if (result.Success)
    {
        result = DoFinalThing()
        if (result.Success)
        {
            success = true;
        }
    }
}

vs:

var result;
if (DoThing(out result))
{
    if (DoOtherThing(out result))
    {
        if (DoFinalThing(out result))
        {
            success = true;
        }
    }
}

Access Tomcat Manager App from different host

Following two configuration is working for me.

1 .tomcat-users.xml details
--------------------------------
  <role rolename="manager-gui"/>
  <role rolename="manager-script"/>
  <role rolename="manager-jmx"/>
  <role rolename="manager-status"/>
  <role rolename="admin-gui"/>
  <role rolename="admin-script"/>
  <role rolename="tomcat"/>


  <user  username="tomcat"  password="tomcat" roles="tomcat"/>

  <user  username="admin"  password="admin" roles="admin-gui"/>

  <user  username="adminscript"  password="adminscrip" roles="admin-script"/>

  <user  username="tomcat"  password="s3cret" roles="manager-gui"/>
  <user  username="status"  password="status" roles="manager-status"/>

  <user  username="both"    password="both"   roles="manager-gui,manager-status"/>

  <user  username="script"  password="script" roles="manager-script"/>
  <user  username="jmx"     password="jmx"    roles="manager-jmx"/>

2. context.xml  of <tomcat>/webapps/manager/META-INF/context.xml and 
<tomcat>/webapps/host-manager/META-INF/context.xml
------------------------------------------------------------------------
<Context antiResourceLocking="false" privileged="true" >

  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>

How to change HTML Object element data attribute value in javascript

document.getElementById("PdfContentArea").setAttribute('data', path);

OR

var objectEl = document.getElementById("PdfContentArea")

objectEl.outerHTML = objectEl.outerHTML.replace(/data="(.+?)"/, 'data="' + path + '"');

How do you remove the title text from the Android ActionBar?

getSupportActionBar().setDisplayShowTitleEnabled(false);
    getSupportActionBar().hide();

hope this will help

PHP error: Notice: Undefined index:

apparently, the GET and/or the POST variable(s) do(es) not exist. simply test if "isset". (pseudocode):

if(isset($_GET['action'];)) {$action = $_GET['action'];} else { RECOVER FROM ERROR CODE }

Is there a difference between `continue` and `pass` in a for loop in python?

Yes, there is a difference. Continue actually skips the rest of the current iteration of the loop (returning to the beginning). Pass is a blank statement that does nothing.

See the python docs

Spring Boot Multiple Datasource

Using two datasources you need their own transaction managers.

@Configuration
public class MySqlDBConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.test.mysql")
    public DataSource mysqlDataSource(){
         return DataSourceBuilder
                 .create()
                 .build();
    }

    @Bean("mysqlTx")
    public DataSourceTransactionManager mysqlTx() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    // same for another DS
}

And then use it accordingly within @Transaction

@Transactional("mysqlTx")
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
    public UserMysql findByName(String name);
}

How to read input from console in a batch file?

In addition to the existing answer it is possible to set a default option as follows:

echo off
ECHO A current build of Test Harness exists.
set delBuild=n
set /p delBuild=Delete preexisting build [y/n] (default - %delBuild%)?:

This allows users to simply hit "Enter" if they want to enter the default.

How do I convert an Array to a List<object> in C#?

You can also initialize the list with an array directly:

List<int> mylist= new List<int>(new int[]{6, 1, -5, 4, -2, -3, 9});

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

How to call a function after a div is ready?

Through jQuery.ready function you can specify function that's executed when DOM is loaded. Whole DOM, not any div you want.

So, you should use ready in a bit different way

$.ready(function() {
    createGrid();
});

This is in case when you dont use AJAX to load your div