Programs & Examples On #Frame

Frame refers to a property of a UIView or an NSView in Objective-C. It is a 4-floating-point representation of the View's location in the parent view or window. ... Use the [frames] tag for HTML frames (not iframes).

Adjust UILabel height to text

Following on @Anorak answer, i added this extension to String and sent an inset as a parameter, because a lot of times you will need a padding to your text. Anyway, maybe some you will find this usefull.

extension String {

    func heightForWithFont(font: UIFont, width: CGFloat, insets: UIEdgeInsets) -> CGFloat {

        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width + insets.left + insets.right, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = self

        label.sizeToFit()
        return label.frame.height + insets.top + insets.bottom
    }
}

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Switch between two frames in tkinter

Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.

One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame.

I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.

# Multi-frame tkinter application v2.3
import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Open page one",
                  command=lambda: master.switch_frame(PageOne)).pack()
        tk.Button(self, text="Open page two",
                  command=lambda: master.switch_frame(PageTwo)).pack()

class PageOne(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

class PageTwo(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
        tk.Button(self, text="Return to start page",
                  command=lambda: master.switch_frame(StartPage)).pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

Start page Page one Page two

Explanation

switch_frame() works by accepting any Class object that implements Frame. The function then creates a new frame to replace the old one.

  • Deletes old _frame if it exists, then replaces it with the new frame.
  • Other frames added with .pack(), such as menubars, will be unaffected.
  • Can be used with any class that implements tkinter.Frame.
  • Window automatically resizes to fit new content

Version History

v2.3

- Pack buttons and labels as they are initialized

v2.2

- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.

v2.1.1

- Remove type-hinting for backwards compatibility with Python 3.4.

v2.1

- Add type-hinting for `frame_class`.

v2.0

- Remove extraneous `container` frame.
    - Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
    - Frame switching is now done with `master.switch_frame()`.

v1.6

- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.

v1.5

  - Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
      - Initializing the frame before calling `.destroy()` results
        in a smoother visual transition.

v1.4

- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
    - Remove `new_frame` variable.

v1.3

- Rename `parent` to `master` for consistency with base `Frame` class.

v1.2

- Remove `main()` function.

v1.1

- Rename `frame` to `_frame`.
    - Naming implies variable should be private.
- Create new frame before destroying old frame.

v1.0

- Initial version.

UIView frame, bounds and center

Since the question I asked has been seen many times I will provide a detailed answer of it. Feel free to modify it if you want to add more correct content.

First a recap on the question: frame, bounds and center and theirs relationships.

Frame A view's frame (CGRect) is the position of its rectangle in the superview's coordinate system. By default it starts at the top left.

Bounds A view's bounds (CGRect) expresses a view rectangle in its own coordinate system.

Center A center is a CGPoint expressed in terms of the superview's coordinate system and it determines the position of the exact center point of the view.

Taken from UIView + position these are the relationships (they don't work in code since they are informal equations) among the previous properties:

  • frame.origin = center - (bounds.size / 2.0)

  • center = frame.origin + (bounds.size / 2.0)

  • frame.size = bounds.size

NOTE: These relationships do not apply if views are rotated. For further info, I will suggest you take a look at the following image taken from The Kitchen Drawer based on Stanford CS193p course. Credits goes to @Rhubarb.

Frame, bounds and center

Using the frame allows you to reposition and/or resize a view within its superview. Usually can be used from a superview, for example, when you create a specific subview. For example:

// view1 will be positioned at x = 30, y = 20 starting the top left corner of [self view]
// [self view] could be the view managed by a UIViewController
UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 400.0f, 400.0f)];    
view1.backgroundColor = [UIColor redColor];

[[self view] addSubview:view1];

When you need the coordinates to drawing inside a view you usually refer to bounds. A typical example could be to draw within a view a subview as an inset of the first. Drawing the subview requires to know the bounds of the superview. For example:

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 400.0f, 400.0f)];    
view1.backgroundColor = [UIColor redColor];

UIView* view2 = [[UIView alloc] initWithFrame:CGRectInset(view1.bounds, 20.0f, 20.0f)];    
view2.backgroundColor = [UIColor yellowColor];

[view1 addSubview:view2];

Different behaviours happen when you change the bounds of a view. For example, if you change the bounds size, the frame changes (and vice versa). The change happens around the center of the view. Use the code below and see what happens:

NSLog(@"Old Frame %@", NSStringFromCGRect(view2.frame));
NSLog(@"Old Center %@", NSStringFromCGPoint(view2.center));    

CGRect frame = view2.bounds;
frame.size.height += 20.0f;
frame.size.width += 20.0f;
view2.bounds = frame;

NSLog(@"New Frame %@", NSStringFromCGRect(view2.frame));
NSLog(@"New Center %@", NSStringFromCGPoint(view2.center));

Furthermore, if you change bounds origin you change the origin of its internal coordinate system. By default the origin is at (0.0, 0.0) (top left corner). For example, if you change the origin for view1 you can see (comment the previous code if you want) that now the top left corner for view2 touches the view1 one. The motivation is quite simple. You say to view1 that its top left corner now is at the position (20.0, 20.0) but since view2's frame origin starts from (20.0, 20.0), they will coincide.

CGRect frame = view1.bounds;
frame.origin.x += 20.0f;
frame.origin.y += 20.0f;
view1.bounds = frame; 

The origin represents the view's position within its superview but describes the position of the bounds center.

Finally, bounds and origin are not related concepts. Both allow to derive the frame of a view (See previous equations).

View1's case study

Here is what happens when using the following snippet.

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 400.0f, 400.0f)];
view1.backgroundColor = [UIColor redColor];

[[self view] addSubview:view1];

NSLog(@"view1's frame is: %@", NSStringFromCGRect([view1 frame]));
NSLog(@"view1's bounds is: %@", NSStringFromCGRect([view1 bounds]));
NSLog(@"view1's center is: %@", NSStringFromCGPoint([view1 center]));

The relative image.

enter image description here

This instead what happens if I change [self view] bounds like the following.

// previous code here...
CGRect rect = [[self view] bounds];
rect.origin.x += 30.0f;
rect.origin.y += 20.0f;
[[self view] setBounds:rect];

The relative image.

enter image description here

Here you say to [self view] that its top left corner now is at the position (30.0, 20.0) but since view1's frame origin starts from (30.0, 20.0), they will coincide.

Additional references (to update with other references if you want)

About clipsToBounds (source Apple doc)

Setting this value to YES causes subviews to be clipped to the bounds of the receiver. If set to NO, subviews whose frames extend beyond the visible bounds of the receiver are not clipped. The default value is NO.

In other words, if a view's frame is (0, 0, 100, 100) and its subview is (90, 90, 30, 30), you will see only a part of that subview. The latter won't exceed the bounds of the parent view.

masksToBounds is equivalent to clipsToBounds. Instead to a UIView, this property is applied to a CALayer. Under the hood, clipsToBounds calls masksToBounds. For further references take a look to How is the relation between UIView's clipsToBounds and CALayer's masksToBounds?.

Tkinter scrollbar for frame

"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"

Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.

"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"

You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.

"What so special about using anchor='nw' when creating window on canvas?"

The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.

Simple way to change the position of UIView?

I found a similar approach (it uses a category as well) with gcamp's answer that helped me greatly here. In your case is as simple as this:

aView.topLeft = CGPointMake(100, 200);

but if you want for example to centre horizontal and to the left with another view you can simply:

aView.topLeft = anotherView.middleLeft;

What's the difference between IFrame and Frame?

The only reasons I can think of are actually in the wiki article you referenced to mention a couple...

"The "Verified by Visa" system has drawn some criticism, since it is hard for users to differentiate between the legitimate Verified by Visa pop-up window or inline frame, and a fraudulent phishing site."

"as of 2008, most web browsers do not provide a simple way to check the security certificate for the contents of an iframe"

If you read the Criticism section in the article it details all the potential security flaws.

Otherwise the only difference is the fact that an IFrame is an inline frame and a Frame is part of a Frameset. Which means more layout problems than anything else!

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

Html code as IFRAME source rather than a URL

I have a page it loads an HTML body from MYSQL I want to present that code in a frame so it renders it self independent of the rest of the page and in the confines of that specific bordering.

An object with a unencoded dataUri might have also fit your need if it was only to load a portion of data text:

The HTML <object> element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.

_x000D_
_x000D_
body {display:flex;min-height:25em;}
p {margin:auto;}
object {margin:0 auto;background:lightgray;}
_x000D_
<p>here My uploaded content: </p>
<object data='data:text/html,
  <style>

.table {
  display: table;
  text-align:center;
  width:100%;
  height:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>


<div class="table">
  <header>
    <h1>Title</h1>
    <p>subTitle</p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>'>

</object>
_x000D_
_x000D_
_x000D_

But keeping your Iframe idea, You could also load your HTML inside your iframe tag and set it as the srcdoc value.You should not have to mind about quotes nor turning it into a dataUri but only mind to fire onload once.

The HTML Inline Frame element (<iframe>) represents a nested browsing context, embedding another HTML page into the current one.

Both iframe below will render the same, one require extra javascript.

example loading a full document :

_x000D_
_x000D_
body {
  display: flex;
  min-height: 25em;
}

p {
  margin: auto;
}

iframe {
  margin: 0 auto;
  min-height: 100%;
  background:lightgray;
}
_x000D_
<p>here my uploaded contents =>:</p>
  <iframe srcdoc='<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <style>
html, body {
  height: 100%;
  margin:0;
}

body.table {
  display: table;
  text-align:center;
  width:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>
</head>

<body class="table">
  <header>
    <h1>title</h1>
    <p>injected via <code>srcdoc</code></p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>
</body>
</html>'>

</iframe>

  <iframe onload="this.setAttribute('srcdoc', this.innerHTML);this.setAttribute('onload','')">
    <!-- below html loaded -->
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
      <title>Test</title>
      <style>
        html,
        body {
          height: 100%;
          margin: 0;
          overflow:auto;
        }
        
        body.table {
          display: table;
          text-align: center;
          width: 100%;
        }
        
        .table>* {
          display: table-row;
        }
        
        .table>main {
          display: table-cell;
          height: 100%;
          vertical-align: middle;
        }
      </style>
    </head>

    <body class="table">
      <header>
        <h1>Title</h1>
        <p>Injected from <code>innerHTML</code></p>
      </header>

      <main>
        <p>Collection</p>
        <p>Version</p>
        <p>Id</p>
      </main>

      <footer>
        <p>Edition</p>
      </footer>
    </body>

    </html>
    </iframe>
_x000D_
_x000D_
_x000D_

Python Tkinter clearing a frame

For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.

import tkinter as tk
from tkinter import *
root = tk.Tk()

frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")

lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)

def clearFrame():
    # destroy all widgets from frame
    for widget in frame.winfo_children():
       widget.destroy()
    
    # this will clear frame and frame will be empty
    # if you want to hide the empty panel then
    frame.pack_forget()

frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)

# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()

Invalid length parameter passed to the LEFT or SUBSTRING function

That would only happen if PostCode is missing a space. You could add conditionality such that all of PostCode is retrieved should a space not be found as follows

select SUBSTRING(PostCode, 1 ,
case when  CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode) 
else CHARINDEX(' ', PostCode) -1 end)

Listen to changes within a DIV and act accordingly

Try this

$('#D25,#E37,#E31,#F37,#E16,#E40,#F16,#F40,#E41,#F41').bind('DOMNodeInserted DOMNodeRemoved',function(){
          // your code;
       });

Do not use this. This may crash the page.

$('mydiv').bind("DOMSubtreeModified",function(){
  alert('changed');
});

bad operand types for binary operator "&" java

Because & has a lesser priority than ==.

Your code is equivalent to a[0] & (1 == 0), and unless a[0] is a boolean this won't compile...

You need to:

(a[0] & 1) == 0

etc etc.

(yes, Java does hava a boolean & operator -- a non shortcut logical and)

Why is a primary-foreign key relation required when we can join without it?

I know its late to post, but I use the site for my own reference and so I wanted to put an answer here for myself to reference in the future too. I hope you (and others) find it helpful.

Lets pretend a bunch of super Einstein experts designed our database. Our super perfect database has 3 tables, and the following relationships defined between them:

TblA 1:M TblB
TblB 1:M TblC

Notice there is no relationship between TblA and TblC

In most scenarios such a simple database is easy to navigate but in commercial databases it is usually impossible to be able to tell at the design stage all the possible uses and combination of uses for data, tables, and even whole databases, especially as systems get built upon and other systems get integrated or switched around or out. This simple fact has spawned a whole industry built on top of databases called Business Intelligence. But I digress...

In the above case, the structure is so simple to understand that its easy to see you can join from TblA, through to B, and through to C and vice versa to get at what you need. It also very vaguely highlights some of the problems with doing it. Now expand this simple chain to 10 or 20 or 50 relationships long. Now all of a sudden you start to envision a need for exactly your scenario. In simple terms, a join from A to C or vice versa or A to F or B to Z or whatever as our system grows.

There are many ways this can indeed be done. The one mentioned above being the most popular, that is driving through all the links. The major problem is that its very slow. And gets progressively slower the more tables you add to the chain, the more those tables grow, and the further you want to go through it.

Solution 1: Look for a common link. It must be there if you taught of a reason to join A to C. If it is not obvious, create a relationship and then join on it. i.e. To join A through B through C there must be some commonality or your join would either produce zero results or a massive number or results (Cartesian product). If you know this commonality, simply add the needed columns to A and C and link them directly.

The rule for relationships is that they simply must have a reason to exist. Nothing more. If you can find a good reason to link from A to C then do it. But you must ensure your reason is not redundant (i.e. its already handled in some other way).

Now a word of warning. There are some pitfalls. But I don't do a good job of explaining them so I will refer you to my source instead of talking about it here. But remember, this is getting into some heavy stuff, so this video about fan and chasm traps is really only a starting point. You can join without relationships. But I advise watching this video first as this goes beyond what most people learn in college and well into the territory of the BI and SAP guys. These guys, while they can program, their day job is to specialise in exactly this kind of thing. How to get massive amounts of data to talk to each other and make sense.

This video is one of the better videos I have come across on the subject. And it's worth looking over some of his other videos. I learned a lot from him.

Shift column in pandas dataframe up by one?

First shift the column:

df['gdp'] = df['gdp'].shift(-1)

Second remove the last row which contains an NaN Cell:

df = df[:-1]

Third reset the index:

df = df.reset_index(drop=True)

Failed to load ApplicationContext for JUnit test of Spring controller

There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class) at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.

An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than @WebMvcTest

Can scripts be inserted with innerHTML?

Yes you can, but you have to do it outside of the DOM and the order has to be right.

var scr = '<scr'+'ipt>alert("foo")</scr'+'ipt>';
window.onload = function(){
    var n = document.createElement("div");
    n.innerHTML = scr;
    document.body.appendChild(n);
}

...will alert 'foo'. This won't work:

document.getElementById("myDiv").innerHTML = scr;

And even this won't work, because the node is inserted first:

var scr = '<scr'+'ipt>alert("foo")</scr'+'ipt>';
window.onload = function(){
    var n = document.createElement("div");
    document.body.appendChild(n);
    n.innerHTML = scr;  
}

Available text color classes in Bootstrap

The text at the navigation bar is normally colored by using one of the two following css classes in the bootstrap.css file.

Firstly, in case of using a default navigation bar (the gray one), the .navbar-default class will be used and the text is colored as dark gray.

.navbar-default .navbar-text {
  color: #777;
}

The other is in case of using an inverse navigation bar (the black one), the text is colored as gray60.

.navbar-inverse .navbar-text {
  color: #999;
}

So, you can change its color as you wish. However, I would recommend you to use a separate css file to change it.

NOTE: you could also use the customizer provided by Twitter Bootstrap, in the Navbar section.

Time complexity of nested for-loop

Yes, nested loops are one way to quickly get a big O notation.

Typically (but not always) one loop nested in another will cause O(n²).

Think about it, the inner loop is executed i times, for each value of i. The outer loop is executed n times.

thus you see a pattern of execution like this: 1 + 2 + 3 + 4 + ... + n times

Therefore, we can bound the number of code executions by saying it obviously executes more than n times (lower bound), but in terms of n how many times are we executing the code?

Well, mathematically we can say that it will execute no more than n² times, giving us a worst case scenario and therefore our Big-Oh bound of O(n²). (For more information on how we can mathematically say this look at the Power Series)

Big-Oh doesn't always measure exactly how much work is being done, but usually gives a reliable approximation of worst case scenario.


4 yrs later Edit: Because this post seems to get a fair amount of traffic. I want to more fully explain how we bound the execution to O(n²) using the power series

From the website: 1+2+3+4...+n = (n² + n)/2 = n²/2 + n/2. How, then are we turning this into O(n²)? What we're (basically) saying is that n² >= n²/2 + n/2. Is this true? Let's do some simple algebra.

  • Multiply both sides by 2 to get: 2n² >= n² + n?
  • Expand 2n² to get:n² + n² >= n² + n?
  • Subtract n² from both sides to get: n² >= n?

It should be clear that n² >= n (not strictly greater than, because of the case where n=0 or 1), assuming that n is always an integer.

Actual Big O complexity is slightly different than what I just said, but this is the gist of it. In actuality, Big O complexity asks if there is a constant we can apply to one function such that it's larger than the other, for sufficiently large input (See the wikipedia page)

error_log per Virtual Host?

To set the Apache (not the PHP) log, the easiest way to do this would be to do:

<VirtualHost IP:Port>
   # Stuff,
   # More Stuff,
   ErrorLog /path/where/you/want/the/error.log
</VirtualHost>

If there is no leading "/" it is assumed to be relative.

Apache Error Log Page

How do I assign ls to an array in Linux Bash?

This would print the files in those directories line by line.

array=(ww/* ee/* qq/*)
printf "%s\n" "${array[@]}"

momentJS date string add 5 days

The function add() returns the old date, but changes the original date :)

startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);

How can we generate getters and setters in Visual Studio?

I use Visual Studio 2013 Professional.

  • Place your cursor at the line of an instance variable.

    Enter image description here

  • Press combine keys Ctrl + R, Ctrl + E, or click the right mouse button. Choose context menu RefactorEncapsulate Field..., and then press OK.

    Enter image description here

  • In Preview Reference Changes - Encapsulate Field dialog, press button Apply.

    Enter image description here

  • This is result:

    Enter image description here



You also place the cursor for choosing a property. Use menu EditRefactorEncapsulate Field...

  • Other information:

    Since C# 3.0 (November 19th 2007), we can use auto-implemented properties (this is merely syntactic sugar).

    And

    private int productID;
    
    public int ProductID
    {
        get { return productID; }
        set { productID = value; }
    }
    

    becomes

    public int ProductID { get; set; }
    

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Relative paths in Python

Instead of using

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

as in the accepted answer, it would be more robust to use:

import inspect
import os
dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

because using __file__ will return the file from which the module was loaded, if it was loaded from a file, so if the file with the script is called from elsewhere, the directory returned will not be correct.

These answers give more detail: https://stackoverflow.com/a/31867043/5542253 and https://stackoverflow.com/a/50502/5542253

How to export library to Jar in Android Studio?

It is not possible to export an Android library as a jar file. It is possible, however, to export it as aar file. Aar files being the new binary format for Android libraries. There's info about them in Google I/O, the New Build System video.

First, build the library in Android Studio or from command line issuing gradle build from your library's root directory.

This will result in <yourlibroot>/libs/build/yourlib.aar file.

This aar file is a binary representation of your library and can be added to your project instead of the library as a dependency project.

To add aar file as a dependency you have to publish it to the maven central or to your local maven repository, and then refer the aar file in your project's gradle.build file.

However, this step is a bit convoluted. I've found a good explanation how to do so here:

http://www.flexlabs.org/2013/06/using-local-aar-android-library-packages-in-gradle-builds

return in for loop or outside loop

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.

The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.

It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally blocks).

How to set caret(cursor) position in contenteditable element (div)?

In most browsers, you need the Range and Selection objects. You specify each of the selection boundaries as a node and an offset within that node. For example, to set the caret to the fifth character of the second line of text, you'd do the following:

_x000D_
_x000D_
function setCaret() {
    var el = document.getElementById("editable")
    var range = document.createRange()
    var sel = window.getSelection()
    
    range.setStart(el.childNodes[2], 5)
    range.collapse(true)
    
    sel.removeAllRanges()
    sel.addRange(range)
}
_x000D_
<div id="editable" contenteditable="true">
  text text text<br>text text text<br>text text text<br>
</div>

<button id="button" onclick="setCaret()">focus</button>
_x000D_
_x000D_
_x000D_

IE < 9 works completely differently. If you need to support these browsers, you'll need different code.

jsFiddle example: http://jsfiddle.net/timdown/vXnCM/

Get Locale Short Date Format using javascript

There is no easy way. If you want a reliable, cross-browser solution, you'd have to build a lookup table of date, and time format strings, by culture. To format a date, parse the corresponding format string, extract the relevant parts from the date, i.e. day, month, year, and append them together.

This is essentially what Microsoft does with their AJAX library, as shown in @no's answer.

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

After testing on Juno, Kepler and Luna, I found JD only works for *.class files on build path.

  1. Adding the jar as a lib of an existing project
  2. Go to Preferences->General->Editors->File Associations, set *.class without source to Class File Editor with a cup icon

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

IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyType')
    --stuff

sys.types... they aren't schema-scoped objects so won't be in sys.objects

Update, Mar 2013

You can use TYPE_ID too

#1214 - The used table type doesn't support FULLTEXT indexes

Before MySQL 5.6 Full-Text Search is supported only with MyISAM Engine.

Therefore either change the engine for your table to MyISAM

CREATE TABLE gamemech_chat (
  id bigint(20) unsigned NOT NULL auto_increment,
  from_userid varchar(50) NOT NULL default '0',
  to_userid varchar(50) NOT NULL default '0',
  text text NOT NULL,
  systemtext text NOT NULL,
  timestamp datetime NOT NULL default '0000-00-00 00:00:00',
  chatroom bigint(20) NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY from_userid (from_userid),
  FULLTEXT KEY from_userid_2 (from_userid),
  KEY chatroom (chatroom),
  KEY timestamp (timestamp)
) ENGINE=MyISAM;

Here is SQLFiddle demo

or upgrade to 5.6 and use InnoDB Full-Text Search.

Issue with Task Scheduler launching a task

My task also failed to start.

I solved it by specifying not only the path to the executable, but also the path to the folder of the executable (Tab "Actions" | Edit | TextBox "Start in").

Read text file into string. C++ ifstream

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
 std::string temp;
 std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
 std::string temp;
 while(std::getline(file, temp)) {
      //Do with temp
 }

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

WAMP server, localhost is not working

The best solution is:

  1. Right click on Computer -> Properties -> Device manager.
  2. View -> Show hidden devices.
  3. Choose Non-plug and plug drivers -> HTTP -> Disable.
  4. Restart your computer.

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

numpy max vs amax vs maximum

You've already stated why np.maximum is different - it returns an array that is the element-wise maximum between two arrays.

As for np.amax and np.max: they both call the same function - np.max is just an alias for np.amax, and they compute the maximum of all elements in an array, or along an axis of an array.

In [1]: import numpy as np

In [2]: np.amax
Out[2]: <function numpy.core.fromnumeric.amax>

In [3]: np.max
Out[3]: <function numpy.core.fromnumeric.amax>

How do I read the file content from the Internal storage - Android App

I prefer to use java.util.Scanner:

try {
    Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
    StringBuilder sb = new StringBuilder();

    while (scanner.hasNext()) {
        sb.append(scanner.next());
    }

    scanner.close();

    String result = sb.toString();

} catch (IOException e) {}

PHP: Read Specific Line From File

If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:

$text = shell_exec("sed -n '74,159p' path/to/file.log");

This solution is good if your file is large.

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

How do I join two lines in vi?

This should do it:

J

Get the item doubleclick event of listview

In the ListBox DoubleClick event get the selecteditem(s) member of the listbox, and there you are.

void ListBox1DoubleClick(object sender, EventArgs e)
    {
        MessageBox.Show(string.Format("SelectedItem:\n{0}",listBox1.SelectedItem.ToString()));
    }

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:

Dim cell As Range
Dim cellAddress As String
Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1)
cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False)

EDIT:

Modify last line to :

cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False) 

if you want it to work even if there are spaces or other funny characters in the sheet name.

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

How to include clean target in Makefile?

In makefile language $@ means "name of the target", so rm -f $@ translates to rm -f clean.

You need to specify to rm what exactly you want to delete, like rm -f *.o code1 code2

How can I know if a process is running?

This is the simplest way I found after using reflector. I created an extension method for that:

public static class ProcessExtensions
{
    public static bool IsRunning(this Process process)
    {
        if (process == null) 
            throw new ArgumentNullException("process");

        try
        {
            Process.GetProcessById(process.Id);
        }
        catch (ArgumentException)
        {
            return false;
        }
        return true;
    }
}

The Process.GetProcessById(processId) method calls the ProcessManager.IsProcessRunning(processId) method and throws ArgumentException in case the process does not exist. For some reason the ProcessManager class is internal...

What is the difference between an int and an Integer in Java and C#?

In Java, the int type is a primitive data type, where as the Integer type is an object.

In C#, the int type is also a data type same as System.Int32. An integer (just like any other value types) can be boxed ("wrapped") into an object.

Check if number is decimal

This is a more tolerate way to handle this with user input. This regex will match both "100" or "100.1" but doesn't allow for negative numbers.

/^(\d+)(\.\d+)?$/

Query to convert from datetime to date mysql

I see the many types of uses, but I find this layout more useful as a reference tool:

SELECT DATE_FORMAT('2004-01-20' ,'%Y-%m-01');

enter image description here

Combine hover and click functions (jQuery)?

You could also use bind:

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});

Bridged networking not working in Virtualbox under Windows 10

i had same problem. i updated to new version of VirtualBox 5.2.26 and checked to make sure Bridge Adapter was enabled in the installation process now is working

Android Starting Service at Boot Time , How to restart service class after device Reboot?

Most the solutions posted here are missing an important piece: doing it without a wake lock runs the risk of your Service getting killed before it is finished processing. Saw this solution in another thread, answering here as well.

Since WakefulBroadcastReceiver is deprecated in api 26 it is recommended for API Levels below 26

You need to obtain a wake lock . Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission and register your receiver in the manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

...

<service android:name=".SimpleWakefulReceiver">
    <intent-filter>
        <action android:name="com.example.SimpleWakefulReceiver"/>
    </intent-filter>
</service>

Getting View's coordinates relative to the root layout

Please use view.getLocationOnScreen(int[] location); (see Javadocs). The answer is in the integer array (x = location[0] and y = location[1]).

How to include js file in another js file?

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)

  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.

  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

How to generate keyboard events?

Windows only: You can either use Ironpython or a library that allows cPython to access the .NET frameworks on Windows. Then use the sendkeys class of .NET or the more general send to simulate a keystroke.

OS X only: Use PyObjC then use use CGEventCreateKeyboardEvent call.

Full disclosure: I have only done this on OS X with Python, but I have used .NET sendkeys (with C#) and that works great.

How to get data from Magento System Configuration

Magento 1.x

(magento 2 example provided below)

sectionName, groupName and fieldName are present in etc/system.xml file of the module.

PHP Syntax:

Mage::getStoreConfig('sectionName/groupName/fieldName');

From within an editor in the admin, such as the content of a CMS Page or Static Block; the description/short description of a Catalog Category, Catalog Product, etc.

{{config path="sectionName/groupName/fieldName"}}

For the "Within an editor" approach to work, the field value must be passed through a filter for the {{ ... }} contents to be parsed out. Out of the box, Magento will do this for Category and Product descriptions, as well as CMS Pages and Static Blocks. However, if you are outputting the content within your own custom view script and want these variables to be parsed out, you can do so like this:

<?php
    $example = Mage::getModel('identifier/name')->load(1);
    $filter  = Mage::getModel('cms/template_filter');
    echo $filter->filter($example->getData('field'));
?>

Replacing identifier/name with the a appropriate values for the model you are loading, and field with the name of the attribute you want to output, which may contain {{ ... }} occurrences that need to be parsed out.

Magento 2.x

From any Block class that extends \Magento\Framework\View\Element\AbstractBlock

$this->_scopeConfig->getValue('sectionName/groupName/fieldName');

Any other PHP class:

If the class (and none of it's parent's) does not inject \Magento\Framework\App\Config\ScopeConfigInterface via the constructor, you'll have to add it to your class.

// ... Remaining class definition above...

/**
 * @var \Magento\Framework\App\Config\ScopeConfigInterface
 */
protected $_scopeConfig;

/**
 * Constructor
 */
public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    // ...any other injected classes the class depends on...
) {
  $this->_scopeConfig = $scopeConfig;
  // Remaining constructor logic...
}

// ...remaining class definition below...

Once you have injected it into your class, you can now fetch store configuration values with the same syntax example given above for block classes.

Note that after modifying any class's __construct() parameter list, you may have to clear your generated classes as well as dependency injection directory: var/generation & var/di

Python Tkinter clearing a frame

For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.

import tkinter as tk
from tkinter import *
root = tk.Tk()

frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")

lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)

def clearFrame():
    # destroy all widgets from frame
    for widget in frame.winfo_children():
       widget.destroy()
    
    # this will clear frame and frame will be empty
    # if you want to hide the empty panel then
    frame.pack_forget()

frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)

# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

View is the superclass for all widgets and the OnClickListener interface belongs to this class. All widgets inherit this. View.OnClickListener is the same as OnClickListener. You would have to override the onClick(View view) method from this listener to achieve the action that you want for your button.

To tell Android to listen to click events for a widget, you need to do:

widget.setOnClickListener(this); // If the containing class implements the interface
// Or you can do the following to set it for each widget individually
widget.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Do something here
    }
});

The 'View' parameter passed in the onClick() method simply lets Android know that a view has been clicked. It can be a Button or a TextView or something else. It is up to you to set an OnClickListener for every widget or to simply make the class containing all these widgets implement the interface. In this case you will have a common onClick() method for all the widgets and all you have to do is to check the id of the view that is passed into the method and then match that against the id for each element that you want and take action for that element.

Cron job every three days

If you want it to run on specific days of the month, like the 1st, 4th, 7th, etc... then you can just have a conditional in your script that checks for the current day of the month.

I thought all you needed for this was instead of */3 which means every three days, use 1/3 which means every three days starting on the 1st of the month. so 7/3 would mean every three days starting on the 7th of the month, etc.

How can I pass parameters to a partial view in mvc 4

For Asp.Net core you better use

<partial name="_MyPartialView" model="MyModel" />

So for example

@foreach (var item in Model)
{
   <partial name="_MyItemView" model="item" />
}

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

jQuery.ajax returns 400 Bad Request

Add this to your ajax call:

contentType: "application/json; charset=utf-8",
dataType: "json"

How do I add a simple jQuery script to WordPress?

"We have Google" cit. For properly use script inside wordpress just add hosted libraries. Like Google

After selected library that you need link it before your custom script: exmpl

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

and after your own script

<script type="text/javascript">
    $(document).ready(function () {
        $('.text_container').addClass("hidden");
    });
</script>

How to delete cookies on an ASP.NET website

Though this is an old thread, i thought if someone is still searching for solution in the future.

HttpCookie mycookie = new HttpCookie("aa");
mycookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(mycookie1);

Thats what did the trick for me.

Remove a marker from a GoogleMap

Add the marker to the map like this

Marker markerName = map.addMarker(new MarkerOptions().position(latLng).title("Title"));

Then you'll be able to use the remove method, it will remove only that marker

markerName.remove();

How to check if all of the following items are in a list?

I would probably use set in the following manner :

set(l).issuperset(set(['a','b'])) 

or the other way round :

set(['a','b']).issubset(set(l)) 

I find it a bit more readable, but it may be over-kill. Sets are particularly useful to compute union/intersection/differences between collections, but it may not be the best option in this situation ...

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

DB2 Query to retrieve all table names for a given schema

On my iSeries I have to run this command from iNavigator:

select *
from QSYS2.SYSTABLES
where TABLE_SCHEMA
like 'SCHEMA_NAME'
and TYPE = 'T';

Reporting Services Remove Time from DateTime in Expression

If you have to display the field on report header then try this... RightClick on Textbox > Properties > Category > date > select *Format (Note this will maintain the regional settings).

Since this question has been viewed many times, I'm posting it... Hope it helps.

enter image description here

MySQL: Grant **all** privileges on database

This will be helpful for some people:

From MySQL command line:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

Sadly, at this point newuser has no permissions to do anything with the databases. In fact, if newuser even tries to login (with the password, password), they will not be able to reach the MySQL shell.

Therefore, the first thing to do is to provide the user with access to the information they will need.

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

The asterisks in this command refer to the database and table (respectively) that they can access—this specific command allows to the user to read, edit, execute and perform all tasks across all the databases and tables.

Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.

FLUSH PRIVILEGES;

Your changes will now be in effect.

For more information: http://dev.mysql.com/doc/refman/5.6/en/grant.html

If you are not comfortable with the command line then you can use a client like MySQL workbench, Navicat or SQLyog

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.

To trigger an event after ng-repeat has rendered try this directive:

var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            $timeout(function () {
                scope.$emit('ngRepeatFinished');
            });
        }
    }
}
});

Complete example in angular: http://jsfiddle.net/ADukg/6880/

I got the directive from here: Use AngularJS just for routing purposes

How to calculate mean, median, mode and range from a set of numbers

Here's the complete clean and optimised code in JAVA 8

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {

    /*Take input from user*/
    Scanner sc = new Scanner(System.in);

    int n =0;
    n = sc.nextInt();
    
    int arr[] = new int[n];
    
    //////////////mean code starts here//////////////////
    int sum = 0;
    for(int i=0;i<n; i++)
    {
         arr[i] = sc.nextInt();
         sum += arr[i]; 
    }
    System.out.println((double)sum/n); 
    //////////////mean code ends here//////////////////


    //////////////median code starts here//////////////////
    Arrays.sort(arr);
    int val = arr.length/2;
    System.out.println((arr[val]+arr[val-1])/2.0); 
    //////////////median code ends here//////////////////


    //////////////mode code starts here//////////////////
    int maxValue=0;
    int maxCount=0;

    for(int i=0; i<n; ++i)
    {
        int count=0;

        for(int j=0; j<n; ++j)
        {
            if(arr[j] == arr[i])
            {
                ++count;
            }

            if(count > maxCount)
            {
                maxCount = count;
                maxValue = arr[i];
            }
        }
    } 
    System.out.println(maxValue);
   //////////////mode code ends here//////////////////

  }

}

Is it possible to wait until all javascript files are loaded before executing javascript code?

Expanding a bit on @Eruant's answer,

$(window).on('load', function() {
    // your code here
});

Works very well with both async and defer while loading on scripts.

So you can import all scripts like this:

<script src="/js/script1.js" async defer></script>
<script src="/js/script2.js" async defer></script>
<script src="/js/script3.js" async defer></script>

Just make sure script1 doesn't call functions from script3 before $(window).on('load' ..., make sure to call them inside window load event.

More about async/defer here.

Failed to connect to mailserver at "localhost" port 25

First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.

How do I apply the for-each loop to every character in a String?

In Java 8 we can solve it as:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));    

The method chars() returns an IntStream as mentioned in doc:

Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

Why use forEachOrdered and not forEach ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

We could also use codePoints() to print, see this answer for more details.

Can I install/update WordPress plugins without providing FTP access?

I saw a lot of people recommending to set permission to 777. I had same problem like 2 days ago and all I did was, add this to wp-content

define('FS_METHOD', 'direct');

and

set permission to 775 for plugin folder

This solved my problem of asking FTP access login/password.

Before that, I had to add plugin manually by adding .zip file to plugin folder and then go to wp-admin/plugins and had to installed it.

Performing Inserts and Updates with Dapper

Using Dapper.Contrib it is as simple as this:

Insert list:

public int Insert(IEnumerable<YourClass> yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Insert(yourClass) ;
    }
}

Insert single:

public int Insert(YourClass yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Insert(yourClass) ;
    }
}

Update list:

public bool Update(IEnumerable<YourClass> yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Update(yourClass) ;
    }
}

Update single:

public bool Update(YourClass yourClass)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        conn.Open();
        return conn.Update(yourClass) ;
    }
}

Source: https://github.com/StackExchange/Dapper/tree/master/Dapper.Contrib

How to solve a timeout error in Laravel 5

If you are hosting your Laravel app on Heroku, you can create custom_php.ini in the root of your project and simply add max_execution_time = 60

Using global variables between files?

Your 2nd attempt will work perfectly, and is actually a really good way to handle variable names that you want to have available globally. But you have a name error in the last line. Here is how it should be:

# ../myproject/main.py

# Import globfile    
import globfile

# Save myList into globfile
globfile.myList = []

# Import subfile
import subfile

# Do something
subfile.stuff()
print(globfile.myList[0])

See the last line? myList is an attr of globfile, not subfile. This will work as you want.

Mike

How is malloc() implemented internally?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

Best way to load module/class from lib folder in Rails 3?

The magic of autoloading stuff

I think the option controlling the folders from which autoloading stuff gets done has been sufficiently covered in other answers. However, in case someone else is having trouble stuff loaded though they've had their autoload paths modified as required, then this answer tries to explain what is the magic behind this autoload thing.

So when it comes to loading stuff from subdirectories there's a gotcha or a convention you should be aware. Sometimes the Ruby/Rails magic (this time mostly Rails) can make it difficult to understand why something is happening. Any module declared in the autoload paths will only be loaded if the module name corresponds to the parent directory name. So in case you try to put into lib/my_stuff/bar.rb something like:

module Foo
  class Bar
  end
end

It will not be loaded automagically. Then again if you rename the parent dir to foo thus hosting your module at path: lib/foo/bar.rb. It will be there for you. Another option is to name the file you want autoloaded by the module name. Obviously there can only be one file by that name then. In case you need to split your stuff into many files you could of course use that one file to require other files, but I don't recommend that, because then when on development mode and you modify those other files then Rails is unable to automagically reload them for you. But if you really want you could have one file by the module name that then specifies the actual files required to use the module. So you could have two files: lib/my_stuff/bar.rb and lib/my_stuff/foo.rb and the former being the same as above and the latter containing a single line: require "bar" and that would work just the same.

P.S. I feel compelled to add one more important thing. As of lately, whenever I want to have something in the lib directory that needs to get autoloaded, I tend to start thinking that if this is something that I'm actually developing specifically for this project (which it usually is, it might some day turn into a "static" snippet of code used in many projects or a git submodule, etc.. in which case it definitely should be in the lib folder) then perhaps its place is not in the lib folder at all. Perhaps it should be in a subfolder under the app folder· I have a feeling that this is the new rails way of doing things. Obviously, the same magic is in work wherever in you autoload paths you put your stuff in so it's good to these things. Anyway, this is just my thoughts on the subject. You are free to disagree. :)


UPDATE: About the type of magic..

As severin pointed out in his comment, the core "autoload a module mechanism" sure is part of Ruby, but the autoload paths stuff isn't. You don't need Rails to do autoload :Foo, File.join(Rails.root, "lib", "my_stuff", "bar"). And when you would try to reference the module Foo for the first time then it would be loaded for you. However what Rails does is it gives us a way to try and load stuff automagically from registered folders and this has been implemented in such a way that it needs to assume something about the naming conventions. If it had not been implemented like that, then every time you reference something that's not currently loaded it would have to go through all of the files in all of the autoload folders and check if any of them contains what you were trying to reference. This in turn would defeat the idea of autoloading and autoreloading. However, with these conventions in place it can deduct from the module/class your trying to load where that might be defined and just load that.

Configuring Git over SSH to login once

Add a single line AddKeysToAgent yes on the top of the .ssh/config file. Ofcourse ssh-agent must be running beforehand. If its not running ( check by prep ssh-agent ) , then simply run it eval $(ssh-agent)

Now, the key is loaded systemwide into the memory and you dont have to type in the passphrase again.

The source of the solution is https://askubuntu.com/questions/362280/enter-ssh-passphrase-once/853578#853578

Float a div in top right corner without overlapping sibling header

Get rid from your <Button> wrap div using display:block and float:left in both <Button> and <h1> and specifying their width with a position:relative to your Section. This approach has the advantage of not needing another div only to position your <Button>

html

<section>  
    <h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>     
    <button>button</button>
</section>

? css

section {
    position: relative;
    width: 50%;
    border: 1px solid;
    float:left;
}
h1 {
    display: block;
    width:70%;
    float:left;
}
button
{
    position:relative;
    top:0;
    left:0;
    float:left;
}

?

VC++ fatal error LNK1168: cannot open filename.exe for writing

I know this is an old question but thought I'd share how I resolved the issue.

If you're using Visual Studio and this error occurs, you can try to attach to process (CTRL+ALT+P) and find the "(program).exe" process. When you try to attach to it, an error will display stating that it failed to attach which removes the process from "running" (even though it's not...) You'll also be able to delete the (program).exe from your Debug folder.

Hope this helps someone! :)

No module named setuptools

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

This Row already belongs to another table error when trying to add rows?

This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();

// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    DataRow myRow = dtSpecificOrders.NewRow();  // <-- create a brand-new row
    myRow[dcID] = int.Parse(dr["ID"]);
    myRow[dcName] = dr["Name"].ToString();
    dtSpecificOrders.Rows.Add(myRow);   // <-- this will add the new row
}

The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.

How to read a file line-by-line into a list?

If you want the \n included:

with open(fname) as f:
    content = f.readlines()

If you do not want \n included:

with open(fname) as f:
    content = f.read().splitlines()

iPhone keyboard, Done button and resignFirstResponder

From the documentation (any version):

It is your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. You might also configure your text field delegate to dismiss the keyboard when the user presses the “return” key on the keyboard itself. To dismiss the keyboard, send the resignFirstResponder message to the text field that is currently the first responder. Doing so causes the text field object to end the current editing session (with the delegate object’s consent) and hide the keyboard.

So, you have to send resignFirstResponder somehow. But there is a possibility that textfield loses focus another way during processing of textFieldShouldReturn: message. This also will cause keyboard to disappear.

Difference between PACKETS and FRAMES

Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.

Return a `struct` from a function in C

struct emp {
    int id;
    char *name;
};

struct emp get() {
    char *name = "John";

    struct emp e1 = {100, name};

    return (e1);
}

int main() {

    struct emp e2 = get();

    printf("%s\n", e2.name);
}

works fine with newer versions of compilers. Just like id, content of the name gets copied to the assigned structure variable.

Collection that allows only unique items in .NET?

You may look into something kind of Unique List as follows

public class UniqueList<T>
{
    public List<T> List
    {
        get;
        private set;
    }
    List<T> _internalList;

    public static UniqueList<T> NewList
    {
        get
        {
            return new UniqueList<T>();
        }
    }

    private UniqueList()
    {            
        _internalList = new List<T>();
        List = new List<T>();
    }

    public void Add(T value)
    {
        List.Clear();
        _internalList.Add(value);
        List.AddRange(_internalList.Distinct());
        //return List;
    }

    public void Add(params T[] values)
    {
        List.Clear();
        _internalList.AddRange(values);
        List.AddRange(_internalList.Distinct());
       // return List;
    }

    public bool Has(T value)
    {
        return List.Contains(value);
    }
}

and you can use it like follows

var uniquelist = UniqueList<string>.NewList;
uniquelist.Add("abc","def","ghi","jkl","mno");
uniquelist.Add("abc","jkl");
var _myList = uniquelist.List;

will only return "abc","def","ghi","jkl","mno" always even when duplicates are added to it

How can I give the Intellij compiler more heap space?

I had a similar problem with Ant build (started by hand from IDEA GUI). In my case there was the right solution to right click on the Ant task, choose properties and set a higher value to "Maximum heap space (Mb):" and "Maximum stack space (Mb):" input fields.

enter image description here

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

cd into directory without having permission

I know this post is old, but what i had to do in the case of the above answers on Linux machine was:

sudo chmod +x directory

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

How do I analyze a program's core dump file with GDB when it has command-line parameters?

objdump + gdb minimal runnable example

TL;DR:

Now for the full educational test setup:

main.c

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int myfunc(int i) {
    *(int*)(NULL) = i; /* line 7 */
    return i - 1;
}

int main(int argc, char **argv) {
    /* Setup some memory. */
    char data_ptr[] = "string in data segment";
    char *mmap_ptr;
    char *text_ptr = "string in text segment";
    (void)argv;
    mmap_ptr = (char *)malloc(sizeof(data_ptr) + 1);
    strcpy(mmap_ptr, data_ptr);
    mmap_ptr[10] = 'm';
    mmap_ptr[11] = 'm';
    mmap_ptr[12] = 'a';
    mmap_ptr[13] = 'p';
    printf("text addr: %p\n", text_ptr);
    printf("data addr: %p\n", data_ptr);
    printf("mmap addr: %p\n", mmap_ptr);

    /* Call a function to prepare a stack trace. */
    return myfunc(argc);
}

Compile, and run to generate core:

gcc -ggdb3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
ulimit -c unlimited
rm -f core
./main.out

Output:

text addr: 0x4007d4
data addr: 0x7ffec6739220
mmap addr: 0x1612010
Segmentation fault (core dumped)

GDB points us to the exact line where the segmentation fault happened, which is what most users want while debugging:

gdb -q -nh main.out core

then:

Reading symbols from main.out...done.
[New LWP 27479]
Core was generated by `./main.out'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000000000400635 in myfunc (i=1) at main.c:7
7           *(int*)(NULL) = i;
(gdb) bt
#0  0x0000000000400635 in myfunc (i=1) at main.c:7
#1  0x000000000040072b in main (argc=1, argv=0x7ffec6739328) at main.c:28

which points us directly to the buggy line 7.

CLI arguments are stored in the core file and don't need to be passed again

To answer the specific CLI argument questions, we see that if we change the cli arguments e.g. with:

rm -f core
./main.out 1 2

then this does get reflected in the previous bactrace without any changes in our commands:

Reading symbols from main.out...done.
[New LWP 21838]
Core was generated by `./main.out 1 2'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000564583cf2759 in myfunc (i=3) at main.c:7
7           *(int*)(NULL) = i; /* line 7 */
(gdb) bt
#0  0x0000564583cf2759 in myfunc (i=3) at main.c:7
#1  0x0000564583cf2858 in main (argc=3, argv=0x7ffcca4effa8) at main.c:2

So note how now argc=3. Therefore this must mean that the core file stores that information. I'm guessing it just stores it as the arguments of main, just like it stores the arguments of any other functions.

This makes sense if you consider that the core dump must be storing the entire memory and register state of the program, and so it has all the information needed to determine the value of function arguments on the current stack.

Less obvious is how to inspect the environment variables: How to get environment variable from a core dump Environment variables are also present in memory so the objdump does contain that information, but I'm not sure how to list all of them in one go conveniently, one by one as follows did work on my tests though:

p __environ[0]

Binutils analysis

By using binutils tools like readelf and objdump, we can bulk dump information contained in the core file such as the memory state.

Most/all of it must also be visible through GDB, but those binutils tools offer a more bulk approach which is convenient for certain use cases, while GDB is more convenient for a more interactive exploration.

First:

file core

tells us that the core file is actually an ELF file:

core: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from './main.out'

which is why we are able to inspect it more directly with usual binutils tools.

A quick look at the ELF standard shows that there is actually an ELF type dedicated to it:

Elf32_Ehd.e_type == ET_CORE

Further format information can be found at:

man 5 core

Then:

readelf -Wa core

gives some hints about the file structure. Memory appears to be contained in regular program headers:

Program Headers:
  Type           Offset   VirtAddr           PhysAddr           FileSiz  MemSiz   Flg Align
  NOTE           0x000468 0x0000000000000000 0x0000000000000000 0x000b9c 0x000000     0
  LOAD           0x002000 0x0000000000400000 0x0000000000000000 0x001000 0x001000 R E 0x1000
  LOAD           0x003000 0x0000000000600000 0x0000000000000000 0x001000 0x001000 R   0x1000
  LOAD           0x004000 0x0000000000601000 0x0000000000000000 0x001000 0x001000 RW  0x1000

and there is some more metadata present in a notes area, notably prstatus contains the PC:

Displaying notes found at file offset 0x00000468 with length 0x00000b9c:
  Owner                 Data size       Description
  CORE                 0x00000150       NT_PRSTATUS (prstatus structure)
  CORE                 0x00000088       NT_PRPSINFO (prpsinfo structure)
  CORE                 0x00000080       NT_SIGINFO (siginfo_t data)
  CORE                 0x00000130       NT_AUXV (auxiliary vector)
  CORE                 0x00000246       NT_FILE (mapped files)
    Page size: 4096
                 Start                 End         Page Offset
    0x0000000000400000  0x0000000000401000  0x0000000000000000
        /home/ciro/test/main.out
    0x0000000000600000  0x0000000000601000  0x0000000000000000
        /home/ciro/test/main.out
    0x0000000000601000  0x0000000000602000  0x0000000000000001
        /home/ciro/test/main.out
    0x00007f8d939ee000  0x00007f8d93bae000  0x0000000000000000
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93bae000  0x00007f8d93dae000  0x00000000000001c0
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93dae000  0x00007f8d93db2000  0x00000000000001c0
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93db2000  0x00007f8d93db4000  0x00000000000001c4
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93db8000  0x00007f8d93dde000  0x0000000000000000
        /lib/x86_64-linux-gnu/ld-2.23.so
    0x00007f8d93fdd000  0x00007f8d93fde000  0x0000000000000025
        /lib/x86_64-linux-gnu/ld-2.23.so
    0x00007f8d93fde000  0x00007f8d93fdf000  0x0000000000000026
        /lib/x86_64-linux-gnu/ld-2.23.so
  CORE                 0x00000200       NT_FPREGSET (floating point registers)
  LINUX                0x00000340       NT_X86_XSTATE (x86 XSAVE extended state)

objdump can easily dump all memory with:

objdump -s core

which contains:

Contents of section load1:

 4007d0 01000200 73747269 6e672069 6e207465  ....string in te
 4007e0 78742073 65676d65 6e740074 65787420  xt segment.text 

Contents of section load15:

 7ffec6739220 73747269 6e672069 6e206461 74612073  string in data s
 7ffec6739230 65676d65 6e740000 00a8677b 9c6778cd  egment....g{.gx.

Contents of section load4:

 1612010 73747269 6e672069 6e206d6d 61702073  string in mmap s
 1612020 65676d65 6e740000 11040000 00000000  egment..........

which matches exactly with the stdout value in our run.

This was tested on Ubuntu 16.04 amd64, GCC 6.4.0, and binutils 2.26.1.

GDB: Listing all mapped memory regions for a crashed process

If you have the program and the core file, you can do the following steps.

1) Run the gdb on the program along with core file

 $gdb ./test core

2) type info files and see what different segments are there in the core file.

    (gdb)info files

A sample output:

    (gdb)info files 

    Symbols from "/home/emntech/debugging/test".
    Local core dump file:
`/home/emntech/debugging/core', file type elf32-i386.
  0x0055f000 - 0x0055f000 is load1
  0x0057b000 - 0x0057c000 is load2
  0x0057c000 - 0x0057d000 is load3
  0x00746000 - 0x00747000 is load4
  0x00c86000 - 0x00c86000 is load5
  0x00de0000 - 0x00de0000 is load6
  0x00de1000 - 0x00de3000 is load7
  0x00de3000 - 0x00de4000 is load8
  0x00de4000 - 0x00de7000 is load9
  0x08048000 - 0x08048000 is load10
  0x08049000 - 0x0804a000 is load11
  0x0804a000 - 0x0804b000 is load12
  0xb77b9000 - 0xb77ba000 is load13
  0xb77cc000 - 0xb77ce000 is load14
  0xbf91d000 - 0xbf93f000 is load15

In my case I have 15 segments. Each segment has start of the address and end of the address. Choose any segment to search data for. For example lets select load11 and search for a pattern. Load11 has start address 0x08049000 and ends at 0x804a000.

3) Search for a pattern in the segment.

(gdb) find /w 0x08049000 0x0804a000 0x8048034
 0x804903c
 0x8049040
 2 patterns found

If you don't have executable file you need to use a program which prints data of all segments of a core file. Then you can search for a particular data at an address. I don't find any program as such, you can use the program at the following link which prints data of all segments of a core or an executable file.

 http://emntech.com/programs/printseg.c

ORA-28040: No matching authentication protocol exception

Adding

SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

is the perfect solution sql.ora directory ..\product\12.1.0\dbhome_1\NETWORK\ADMIN

Get multiple elements by Id

Here is a function I came up with

function getElementsById(elementID){
    var elementCollection = new Array();
    var allElements = document.getElementsByTagName("*");
    for(i = 0; i < allElements.length; i++){
        if(allElements[i].id == elementID)
            elementCollection.push(allElements[i]);

    }
    return elementCollection;
}

Apparently there is a convention supported by prototype, and probably other major JavaScript libraries.

However, I have come to discover that dollar sign function has become the more-or-less de facto shortcut to document.getElementById(). Let’s face it, we all use document.getElementById() a lot. Not only does it take time to type, but it adds bytes to your code as well.

here is the function from prototype:

function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

[Source]

$.focus() not working

You can try this id is tries

window.location.hash = '#tries';

How do I check out a remote Git branch?

To clone a Git repository, do:

git clone <either ssh url /http url>

The above command checks out all of the branches, but only the master branch will be initialized. If you want to checkout the other branches, do:

git checkout -t origin/future_branch (for example)

This command checks out the remote branch, and your local branch name will be same as the remote branch.

If you want to override your local branch name on checkout:

git checkout -t -b enhancement origin/future_branch

Now your local branch name is enhancement, but your remote branch name is future_branch.

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

Git ignore file for Xcode projects

Adding a .gitignore file for

Mac OS X + Xcode + Swift

This is how I have added a .gitignore file into my Swift project:

  1. Select you project in Xcode and right click → New Group → name it "Git"
  2. Select the Git folder and right click → Add new file
  3. Within the iOS tab → select Otherempty file

Enter image description here

  1. Give the file name here ".gitignore"

Enter image description here

  1. Confirm the file name and type

Enter image description here

Here is the result structure:

Enter image description here

  1. Open the file and past the below code

# file

#########################################################################
#                                                                       #
#       Title         - .gitignore file                                 #
#       For           - Mac OS X, Xcode 7 and Swift Source projects     #
#       Updated by    - Ramdhan Choudhary                               #
#       Updated on    - 13 - November - 2015                            #
#                                                                       #
#########################################################################

########### Xcode ###########
# Xcode temporary files that should never be committed

## Build generated
build/
DerivedData

# NB: NIB/XIB files still exist even on Storyboard projects, so we want this
*~.nib
*.swp

## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata

## Other
*.xccheckout
*.moved-aside
*.xcuserstate
*.xcscmblueprint
*.xcscheme

########### Mac OS X ###########
# Mac OS X temporary files that should never be committed

.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

########## Objective-C/Swift specific ##########
*.hmap
*.ipa

# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# Pods/

# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts

Carthage/Build

# fastlane
#
# It is recommended to not store the screenshots in the Git repository. Instead, use fastlane to re-generate the

fastlane/report.xml
fastlane/screenshots

Well, thanks to Adam. His answer helped me a lot, but still I had to add a few more entries as I wanted a .gitignore file for:

Mac OS X + Xcode + Swift

References: this and this

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

C# equivalent to Java's charAt()?

please try to make it as a character

string str = "Tigger";
//then str[0] will return 'T' not "T"

HTML Canvas Full Screen

The javascript has

var canvasW     = 640;
var canvasH     = 480;

in it. Try changing those as well as the css for the canvas.

Or better yet, have the initialize function determine the size of the canvas from the css!

in response to your edits, change your init function:

function init()
{
    canvas = document.getElementById("mainCanvas");
    canvas.width = document.body.clientWidth; //document.width is obsolete
    canvas.height = document.body.clientHeight; //document.height is obsolete
    canvasW = canvas.width;
    canvasH = canvas.height;

    if( canvas.getContext )
    {
        setup();
        setInterval( run , 33 );
    }
}

Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.

html, body {
    overflow: hidden;
}

Edit: document.width and document.height are obsolete. Replace with document.body.clientWidth and document.body.clientHeight

Disable button in jQuery

disable button:

$('#button_id').attr('disabled','disabled');

enable button:

$('#button_id').removeAttr('disabled');

How do I get rid of an element's offset using CSS?

This seems weird, but you can try setting vertical-align: top in the CSS for the inputs. That fixes it in IE8, at least.

Change URL and redirect using jQuery

you can do it simpler without jquery

location = "https://example.com/" + txt.value

_x000D_
_x000D_
function send() {_x000D_
  location = "https://example.com/" + txt.value;_x000D_
}
_x000D_
<form id="abc">_x000D_
  <input type="text" id="txt" />_x000D_
</form>_x000D_
_x000D_
<button onclick="send()">Send</button>
_x000D_
_x000D_
_x000D_

How do I convert an interval into a number of hours with postgres?

To get the number of days the easiest way would be:

SELECT EXTRACT(DAY FROM NOW() - '2014-08-02 08:10:56');

As far as I know it would return the same as:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int;

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

You can not add ON DELETE CASCADE to an already existing constraint. You will have to drop and re-create the constraint. The documentation shows that the MODIFY CONSTRAINT clause can only modify the state of a constraint (i-e: ENABLED/DISABLED...).

Capitalize only first character of string and leave others alone? (Rails)

Most of these answers edit the string in place, when you are just formatting for view output you may not want to be changing the underlying string so you can use tap after a dup to get an edited copy

'test'.dup.tap { |string| string[0] = string[0].upcase }

I need an unordered list without any bullets

If you're unable to make it work at the <ul> level, you might need to place the list-style-type: none; at the <li> level:

<ul>
    <li style="list-style-type: none;">Item 1</li>
    <li style="list-style-type: none;">Item 2</li>
</ul>

You can create a CSS class to avoid this repetition:

<style>
ul.no-bullets li
{
    list-style-type: none;
}
</style>

<ul class="no-bullets">
    <li>Item 1</li>
    <li>Item 2</li>
</ul>

When necessary, use !important:

<style>
ul.no-bullets li
{
    list-style-type: none !important;
}
</style>

invalid conversion from 'const char*' to 'char*'

string::c.str() returns a string of type const char * as seen here

A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str());

While the above may work, it is undefined behaviour, and unsafe.

Here's a nicer solution using templates:

char * my_argument = const_cast<char*> ( ...c_str() );

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

It means you don't have privileges to create the trigger with root@localhost user..

try removing definer from the trigger command:

CREATE DEFINER = root@localhost FUNCTION fnc_calcWalkedDistance

Picking a random element from a set

you can also transfer the set to array use array it will probably work on small scale i see the for loop in the most voted answer is O(n) anyway

Object[] arr = set.toArray();

int v = (int) arr[rnd.nextInt(arr.length)];

Run / Open VSCode from Mac Terminal

I simply created a file called code:

#!/bin/bash

open /Applications/Visual\ Studio\ Code.app $1

Make it executable:

$ chmod 755 code

Then put that in /usr/local/bin

$ sudo mv code /usr/local/bin

As long as the file sits someplace that is in your path you can open a file by just typing: code

How to check if a value exists in an array in Ruby

There are multiple ways to accomplish this. A few of them are as follows:

a = [1,2,3,4,5]

2.in? a  #=> true

8.in? a #=> false

a.member? 1 #=> true

a.member? 8 #=> false

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

This link may help you. Try checking in your manifest for problems. If you can get it to happen again, post your entire stack trace so that we can see what the error actually is.

EDIT: I'm sure you've checked this, but what is on line 12 of the XML file you use for the TourActivity layout?

how to access parent window object using jquery?

If you are in a po-up and you want to access the opening window, use window.opener. The easiest would be if you could load JQuery in the parent window as well:

window.opener.$("#serverMsg").html // this uses JQuery in the parent window

or you could use plain old document.getElementById to get the element, and then extend it using the jquery in your child window. The following should work (I haven't tested it, though):

element = window.opener.document.getElementById("serverMsg");
element = $(element);

If you are in an iframe or frameset and want to access the parent frame, use window.parent instead of window.opener.

According to the Same Origin Policy, all this works effortlessly only if both the child and the parent window are in the same domain.

Gridview get Checkbox.Checked value

If you want a method other than findcontrol try the following:

 GridViewRow row = Gridview1.SelectedRow;
 int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
 CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this

What is The Rule of Three?

The Rule of Three is a rule of thumb for C++, basically saying

If your class needs any of

  • a copy constructor,
  • an assignment operator,
  • or a destructor,

defined explictly, then it is likely to need all three of them.

The reasons for this is that all three of them are usually used to manage a resource, and if your class manages a resource, it usually needs to manage copying as well as freeing.

If there is no good semantic for copying the resource your class manages, then consider to forbid copying by declaring (not defining) the copy constructor and assignment operator as private.

(Note that the forthcoming new version of the C++ standard (which is C++11) adds move semantics to C++, which will likely change the Rule of Three. However, I know too little about this to write a C++11 section about the Rule of Three.)

How to pass integer from one Activity to another?

In Sender Activity Side:

Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);

In Receiver Activity Side:

int receiveValue = getIntent().getIntExtra("value", 0);

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

If you get an exception for : Invalid column type

Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()

 List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
 getRowMapper());

Note that the second two arguments are swapped around.

Disable eslint rules for folder

YAML version :

overrides:
  - files: *-tests.js
    rules:
      no-param-reassign: 0

Example of specific rules for mocha tests :

You can also set a specific env for a folder, like this :

overrides:
  - files: test/*-tests.js
    env:
      mocha: true

This configuration will fix error message about describe and it not defined, only for your test folder:

/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef

Writing data into CSV file in C#

Instead of reinventing the wheel a library could be used. CsvHelper is great for creating and reading csv files. It's read and write operations are stream based and therefore also support operations with a big amount of data.


You can write your csv like the following.

using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv"))
{
    var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
    writer.Configuration.Delimiter = ",";

    foreach (var item in list)
    {
        writer.WriteField( "a" );
        writer.WriteField( 2 );
        writer.WriteField( true );
        writer.NextRecord();
    }
}

As the library is using reflection it will take any type and parse it directly.

public class CsvRow
{
    public string Column1 { get; set; }
    public bool Column2 { get; set; }

    public CsvRow(string column1, bool column2)
    {
        Column1 = column1;
        Column2 = column2;
    }
}

IEnumerable<CsvRow> rows = new [] {
    new CsvRow("value1", true),
    new CsvRow("value2", false)
};
using(var textWriter = new StreamWriter(@"C:\mypath\myfile.csv")
{
    var writer = new CsvWriter(textWriter, CultureInfo.InvariantCulture);
    writer.Configuration.Delimiter = ",";
    writer.WriteRecords(rows);
}

value1,true

value2,false


If you want to read more about the librarys configurations and possibilities you can do so here.

How can I verify a Google authentication API access token?

For user check, just post get the access token as accessToken and post it and get the response

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken

you can try in address bar in browsers too, use httppost and response in java also

response will be like

{
     "issued_to": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
     "audience": "xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
     "user_id": "xxxxxxxxxxxxxxxxxxxxxxx",
     "scope": "https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com",
     "expires_in": 3340,
     "access_type": "offline"
    }

The scope is the given permission of the accessToken. you can check the scope ids in this link

Update: New API post as below

https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123

Response will be as

 {
 // These six fields are included in all Google ID Tokens.
 "iss": "https://accounts.google.com",
 "sub": "110169484474386276334",
 "azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
 "iat": "1433978353",
 "exp": "1433981953",

 // These seven fields are only included when the user has granted the "profile" and
 // "email" OAuth scopes to the application.
 "email": "[email protected]",
 "email_verified": "true",
 "name" : "Test User",
 "picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
 "given_name": "Test",
 "family_name": "User",
 "locale": "en"
}

For more info, https://developers.google.com/identity/sign-in/android/backend-auth

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

Check your .ssh config for heroku. Go to the .ssh folder and open the config file

cd ~/.ssh
subl config

The 'subl' is for Sublime Text, but you can use whatever editor you wish. Look for the line "IdentityFile" and make sure it has the non public key listed:

IdentityFile "/Users/ircmullaney/.ssh/my_ssh"

not

IdentityFile "/Users/ircmullaney/.ssh/my_ssh.pub"

That did it for me. I'm not sure why mine had the public version in the config file, but it did and it was throwing the error:

Permissions 0644 for '/Users/ircmullaney/.ssh/my_ssh.pub' are too open.

Generate SHA hash in C++ using OpenSSL library

OpenSSL has a horrible documentation with no code examples, but here you are:

#include <openssl/sha.h>

bool simpleSHA256(void* input, unsigned long length, unsigned char* md)
{
    SHA256_CTX context;
    if(!SHA256_Init(&context))
        return false;

    if(!SHA256_Update(&context, (unsigned char*)input, length))
        return false;

    if(!SHA256_Final(md, &context))
        return false;

    return true;
}

Usage:

unsigned char md[SHA256_DIGEST_LENGTH]; // 32 bytes
if(!simpleSHA256(<data buffer>, <data length>, md))
{
    // handle error
}

Afterwards, md will contain the binary SHA-256 message digest. Similar code can be used for the other SHA family members, just replace "256" in the code.

If you have larger data, you of course should feed data chunks as they arrive (multiple SHA256_Update calls).

Difference between Math.Floor() and Math.Truncate()

Going by the Mathematical Definition of Floor, that is, "Greatest integer less than or equal to a number", This is completely unambiguous, whereas, Truncate just removes the fractional part, which is equivalent to round towards 0.

Domain Account keeping locking out with correct password every few minutes

We just had a similar issue, looks like the user reset his password on Friday and over the weekend and on Monday he kept getting locked out.

Turned out to be he forgot to update his password on his mobile phone.

How to concatenate properties from multiple JavaScript objects

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

Spread syntax for object literals was introduced in ECMAScript 2018):

const a = { "one": 1, "two": 2 };
const b = { "three": 3 };
const c = { "four": 4, "five": 5 };

const result = {...a, ...b, ...c};
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }

Spread (...) operator is supported in many modern browsers but not all of them.

So, it is recommend to use a transpiler like Babel to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.

This is the equivalent code Babel will generate for you:

"use strict";

var _extends = Object.assign || function(target) {
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    for (var key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key];
      }
    }
  }
  return target;
};

var a = { "one": 1, "two": 2 };
var b = { "three": 3 };
var c = { "four": 4, "five": 5 };

var result = _extends({}, a, b, c);
// Object { "one": 1, "two": 2 , "three": 3, "four": 4, "five": 5 }

Can I scale a div's height proportionally to its width using CSS?

You can use View Width for the "width" and again half of the View Width for the "height". In this way you're guaranteed the correct ratio regardless of the viewport size.

<div class="ss"></div>

.ss
{
    width: 30vw;
    height: 15vw;
}

Fiddle

How to remove item from a python list in a loop?

You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:

y = [s for s in x if len(s) == 2]

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

A column-vector y was passed when a 1d array was expected

I had the same problem. The problem was that the labels were in a column format while it expected it in a row. use np.ravel()

knn.score(training_set, np.ravel(training_labels))

Hope this solves it.

How do you convert a jQuery object into a string?

Just use .get(0) to grab the native element, and get its outerHTML property:

var $elem = $('<a href="#">Some element</a>');
console.log("HTML is: " + $elem.get(0).outerHTML);

Resize height with Highcharts

I had a similar problem with height except my chart was inside a bootstrap modal popup, which I'm already controlling the size of with css. However, for some reason when the window was resized horizontally the height of the chart container would expand indefinitely. If you were to drag the window back and forth it would expand vertically indefinitely. I also don't like hard-coded height/width solutions.

So, if you're doing this in a modal, combine this solution with a window resize event.

// from link
$('#ChartModal').on('show.bs.modal', function() {
    $('.chart-container').css('visibility', 'hidden');
});

$('#ChartModal').on('shown.bs.modal.', function() {
    $('.chart-container').css('visibility', 'initial');
    $('#chartbox').highcharts().reflow()
    //added
    ratio = $('.chart-container').width() / $('.chart-container').height();
});

Where "ratio" becomes a height/width aspect ratio, that will you resize when the bootstrap modal resizes. This measurement is only taken when he modal is opened. I'm storing ratio as a global but that's probably not best practice.

$(window).on('resize', function() {
    //chart-container is only visible when the modal is visible.
    if ( $('.chart-container').is(':visible') ) {
        $('#chartbox').highcharts().setSize( 
            $('.chart-container').width(),
            ($('.chart-container').width() / ratio),
            doAnimation = true );
    }       
});

So with this, you can drag your screen to the side (resizing it) and your chart will maintain its aspect ratio.

Widescreen

enter image description here

vs smaller

enter image description here

(still fiddling around with vw units, so everything in the back is too small to read lol!)

Android difference between Two Dates

I use this: send start and end date in millisecond

public int GetDifference(long start,long end){
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(start);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int min = cal.get(Calendar.MINUTE);
    long t=(23-hour)*3600000+(59-min)*60000;

    t=start+t;

    int diff=0;
    if(end>t){
        diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
    }

    return  diff;
}

get client time zone from browser

Here is a jsfiddle

It provides the abbreviation of the current user timezone.

Here is the code sample

var tz = jstz.determine();
console.log(tz.name());
console.log(moment.tz.zone(tz.name()).abbr(new Date().getTime()));

Change background color of edittext in android

This is my working solution

View view = new View(getApplicationContext());
view.setBackgroundResource(R.color.background);
myEditText.setBackground(view.getBackground());

Limit text length to n lines using CSS

I really like line-clamp, but no support for firefox yet.. so i go with a math calc and just hide the overflow

.body-content.body-overflow-hidden h5 {
    max-height: 62px;/* font-size * line-height * lines-to-show(4 in this case) 63px if you go with jquery */
    overflow: hidden;
}
.body-content h5 {
    font-size: 14px; /* need to know this*/
    line-height:1,1; /*and this*/
}

now lets say you want to remove and add this class via jQuery with a link, you will need to have an extra pixel so the max-height it will be 63 px, this is because you need to check every time if the height greather than 62px, but in the case of 4 lines you will get a false true, so an extra pixel will fix this and it will no create any extra problems

i will paste a coffeescript for this just to be an example, uses a couple of links that are hidden by default, with classes read-more and read-less, it will remove the ones that the overflow is not need it and remove the body-overflow classes

jQuery ->

    $('.read-more').each ->
        if $(this).parent().find("h5").height() < 63
             $(this).parent().removeClass("body-overflow-hidden").find(".read-less").remove()
             $(this).remove()
        else
            $(this).show()

    $('.read-more').click (event) ->
        event.preventDefault()
        $(this).parent().removeClass("body-overflow-hidden")
        $(this).hide()
        $(this).parent().find('.read-less').show()

    $('.read-less').click (event) ->
        event.preventDefault()
        $(this).parent().addClass("body-overflow-hidden")
        $(this).hide()
        $(this).parent().find('.read-more').show()

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Base64 Decoding in iOS 7+

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

Objective-C

NSString *plainString = @"foo";

Encoding

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Twitter bootstrap scrollable table

None of these answers worked satisfactorily for me. They either didn't fix the table heading row in place or they required fixed column widths to work, and even then tended to have the heading row and body rows misaligned in various browsers.

I recommend biting the bullet and using a proper grid control like jsGrid or my personal favorite, SlickGrid. It obviously introduces a dependency but if you want your tables to behave like real grids with cross-browser support, this will save you pulling your hair out. It also gives you the option of sorting and resizing columns plus tons of other features if you want them.

Directory-tree listing in Python

Here is a one line Pythonic version:

import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]

This code lists the full path of all files and directories in the given directory name.

Why does visual studio 2012 not find my tests?

I had same issue, but a bit different.

I was using visual studio 2012. For some reason, only the tests of the initial generated file was running. But tests in another file were not running. Tried out different solutions posted here, did not work.

Finally I figured out that I had a private method in the test class which was the first method inside the class. I just moved the private method after a test method; so now, a method with [TestMethod] attribute is the first method inside the class. Strange, but now it works.

Hope this helps someone someday.

Styling Google Maps InfoWindow

I used the following code to apply some external CSS:

boxText = document.createElement("html");
boxText.innerHTML = "<head><link rel='stylesheet' href='style.css'/></head><body>[some html]<body>";

infowindow.setContent(boxText);
infowindow.open(map, marker);

Rails: Why "sudo" command is not recognized?

sudo is a Unix/Linux command. It's not available in Windows.

Using fonts with Rails asset pipeline

I was having this problem on Rails 4.2 (with ruby 2.2.3) and had to edit the font-awesome _paths.scss partial to remove references to $fa-font-path and removing a leading forward slash. The following was broken:

@font-face {
  font-family: 'FontAwesome';
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?v=#{$fa-version}');
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
    font-url('#{$fa-font-path}/fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

And the following works:

@font-face {
  font-family: 'FontAwesome';
  src: font-url('fontawesome-webfont.eot?v=#{$fa-version}');
  src: font-url('fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
    font-url('fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
    font-url('fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
    font-url('fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
    font-url('fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

An alternative would be to simply remove the forward slash following the interpolated $fa-font-path and then define $fa-font-path as an empty string or subdirectory with trailing forward slash (as needed).

Remember to recompile assets and restart your server as needed. For example, on a passenger setup:

prompt> rake assets:clean; rake assets:clobber
prompt> RAILS_ENV=production RAILS_GROUPS=assets rake assets:precompile
prompt> service passenger restart

Then reload your browser.

Download history stock prices automatically from yahoo finance in python

Extending @Def_Os's answer with an actual demo...

As @Def_Os has already said - using Pandas Datareader makes this task a real fun

In [12]: from pandas_datareader import data

pulling all available historical data for AAPL starting from 1980-01-01

#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')

# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')

first 5 rows

In [14]: aapl.head()
Out[14]:
                 Open       High     Low   Close     Volume  Adj Close
Date
1980-12-12  28.750000  28.875000  28.750  28.750  117258400   0.431358
1980-12-15  27.375001  27.375001  27.250  27.250   43971200   0.408852
1980-12-16  25.375000  25.375000  25.250  25.250   26432000   0.378845
1980-12-17  25.875000  25.999999  25.875  25.875   21610400   0.388222
1980-12-18  26.625000  26.750000  26.625  26.625   18362400   0.399475

last 5 rows

In [15]: aapl.tail()
Out[15]:
                 Open       High        Low      Close    Volume  Adj Close
Date
2016-06-07  99.250000  99.870003  98.959999  99.029999  22366400  99.029999
2016-06-08  99.019997  99.559998  98.680000  98.940002  20812700  98.940002
2016-06-09  98.500000  99.989998  98.459999  99.650002  26419600  99.650002
2016-06-10  98.529999  99.349998  98.480003  98.830002  31462100  98.830002
2016-06-13  98.690002  99.120003  97.099998  97.339996  37612900  97.339996

save all data as CSV file

In [16]: aapl.to_csv('d:/temp/aapl_data.csv')

d:/temp/aapl_data.csv - 5 first rows

Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...

Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

it's actually happening because the phone is on offscreen, or you pressed the power button while starting the service. solution for this which worked for me is to start an activity and when it will go in onResume then start the service. in my case, it was booting up and starting a service.

java Compare two dates

java.util.Date class has before and after method to compare dates.

Date date1 = new Date();
Date date2 = new Date();

if(date1.before(date2)){
    //Do Something
}

if(date1.after(date2)){
    //Do Something else
}

How to detect a textbox's content has changed

I would recommend taking a look at jQuery UI autocomplete widget. They handled most of the cases there since their code base is more mature than most ones out there.

Below is a link to a demo page so you can verify it works. http://jqueryui.com/demos/autocomplete/#default

You will get the most benefit from reading the source and seeing how they solved it. You can find it here: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js.

Basically they do it all, they bind to input, keydown, keyup, keypress, focus and blur. Then they have special handling for all sorts of keys like page up, page down, up arrow key and down arrow key. A timer is used before getting the contents of the textbox. When a user types a key that does not correspond to a command (up key, down key and so on) there is a timer that explorers the content after about 300 milliseconds. It looks like this in the code:

// switch statement in the 
switch( event.keyCode ) {
            //...
            case keyCode.ENTER:
            case keyCode.NUMPAD_ENTER:
                // when menu is open and has focus
                if ( this.menu.active ) {
                    // #6055 - Opera still allows the keypress to occur
                    // which causes forms to submit
                    suppressKeyPress = true;
                    event.preventDefault();
                    this.menu.select( event );
                }
                break;
            default:
                suppressKeyPressRepeat = true;
                // search timeout should be triggered before the input value is changed
                this._searchTimeout( event );
                break;
            }
// ...
// ...
_searchTimeout: function( event ) {
    clearTimeout( this.searching );
    this.searching = this._delay(function() { // * essentially a warpper for a setTimeout call *
        // only search if the value has changed
        if ( this.term !== this._value() ) { // * _value is a wrapper to get the value *
            this.selectedItem = null;
            this.search( null, event );
        }
    }, this.options.delay );
},

The reason to use a timer is so that the UI gets a chance to be updated. When Javascript is running the UI cannot be updated, therefore the call to the delay function. This works well for other situations such as keeping focus on the textbox (used by that code).

So you can either use the widget or copy the code into your own widget if you are not using jQuery UI (or in my case developing a custom widget).

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

Set UILabel line spacing

Of course, Mike's answer doesn't work if you pass the string programmatically. In this case you need to pass a attributed string and change it's style.

NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"Your \nregular \nstring"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:4];
[attrString addAttribute:NSParagraphStyleAttributeName
                   value:style
                   range:NSMakeRange(0, attrString.length)];
_label.attributedText = attrString;

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

XAMPP uses a file called mysql_start.bat to start MySQL and if you open that file with a text editor you can see what config file is trying to use, in the current version it is:

mysql\bin\mysqld --defaults-file=mysql\bin\my.ini --standalone --console

If you installed XAMPP on the default path it means it is on c:/xampp/mysql/bin/my.ini


If somehow the file doesn't exist you should open a console terminal (start-> type "cmd", press enter) and then write "mysql --help" and it prints a text mentioning the default locations, in the current version of XAMPP is:

C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf C:\xampp\mysql\my.ini C:\xampp\mysql\my.cnf

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

How to add a local repo and treat it as a remote repo

If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.

For example:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Similarly you can clone as if this were a remote repo:

$ git clone ~/repos/myproject.git

Setting ANDROID_HOME enviromental variable on Mac OS X

1) Open base profile :

open  ~/.bash_profile

2) Add below line in base profile :

export PATH=${PATH}:/Users/<username>/Library/Android/sdk/build-tools/27.0.3

Save and close base profile.

For me 27.0.3 working great.

Change the location of an object programmatically

Location is a struct. If there aren't any convenience members, you'll need to reassign the entire Location:

this.balancePanel.Location = new Point(
    this.optionsPanel.Location.X,
    this.balancePanel.Location.Y);

Most structs are also immutable, but in the rare (and confusing) case that it is mutable, you can also copy-out, edit, copy-in;

var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;

Although I don't recommend the above, since structs should ideally be immutable.

Simple way to unzip a .zip file using zlib

zlib handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.

You can try libzip. It is free, portable and easy to use.

UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:

#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, name, 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);

    //Do something with the contents
    //delete allocated memory
    delete[] contents;
}

Check if int is between two numbers

You could make your own

public static boolean isBetween(int a, int b, int c) {
    return b > a ? c > a && c < b : c > b && c < a;
}

Edit: sorry checks if c is between a and b

Open CSV file via VBA (performance)

This function reads a CSV file of 15MB and copies its content into a sheet in about 3 secs. What is probably taking a lot of time in your code is the fact that you copy data cell by cell instead of putting the whole content at once.

Option Explicit

Public Sub test()

  copyDataFromCsvFileToSheet "C:\temp\test.csv", ",", "Sheet1"

End Sub

Private Sub copyDataFromCsvFileToSheet(parFileName As String, parDelimiter As String, parSheetName As String)

  Dim data As Variant

  data = getDataFromFile(parFileName, parDelimiter)
  If Not isArrayEmpty(data) Then
    With Sheets(parSheetName)
      .Cells.ClearContents
      .Cells(1, 1).Resize(UBound(data, 1), UBound(data, 2)) = data
    End With
  End If

End Sub

Public Function isArrayEmpty(parArray As Variant) As Boolean
'Returns false if not an array or dynamic array that has not been initialised (ReDim) or has been erased (Erase)

  If IsArray(parArray) = False Then isArrayEmpty = True
  On Error Resume Next
  If UBound(parArray) < LBound(parArray) Then isArrayEmpty = True: Exit Function Else: isArrayEmpty = False

End Function

Private Function getDataFromFile(parFileName As String, parDelimiter As String, Optional parExcludeCharacter As String = "") As Variant
'parFileName is supposed to be a delimited file (csv...)
'parDelimiter is the delimiter, "," for example in a comma delimited file
'Returns an empty array if file is empty or can't be opened
'number of columns based on the line with the largest number of columns, not on the first line
'parExcludeCharacter: sometimes csv files have quotes around strings: "XXX" - if parExcludeCharacter = """" then removes the quotes


  Dim locLinesList() As Variant
  Dim locData As Variant
  Dim i As Long
  Dim j As Long
  Dim locNumRows As Long
  Dim locNumCols As Long
  Dim fso As Variant
  Dim ts As Variant
  Const REDIM_STEP = 10000

  Set fso = CreateObject("Scripting.FileSystemObject")

  On Error GoTo error_open_file
  Set ts = fso.OpenTextFile(parFileName)
  On Error GoTo unhandled_error

  'Counts the number of lines and the largest number of columns
  ReDim locLinesList(1 To 1) As Variant
  i = 0
  Do While Not ts.AtEndOfStream
    If i Mod REDIM_STEP = 0 Then
      ReDim Preserve locLinesList(1 To UBound(locLinesList, 1) + REDIM_STEP) As Variant
    End If
    locLinesList(i + 1) = Split(ts.ReadLine, parDelimiter)
    j = UBound(locLinesList(i + 1), 1) 'number of columns
    If locNumCols < j Then locNumCols = j
    i = i + 1
  Loop

  ts.Close

  locNumRows = i

  If locNumRows = 0 Then Exit Function 'Empty file

  ReDim locData(1 To locNumRows, 1 To locNumCols + 1) As Variant

  'Copies the file into an array
  If parExcludeCharacter <> "" Then

    For i = 1 To locNumRows
      For j = 0 To UBound(locLinesList(i), 1)
        If Left(locLinesList(i)(j), 1) = parExcludeCharacter Then
          If Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
            locLinesList(i)(j) = Mid(locLinesList(i)(j), 2, Len(locLinesList(i)(j)) - 2)       'If locTempArray = "", Mid returns ""
          Else
            locLinesList(i)(j) = Right(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
          End If
        ElseIf Right(locLinesList(i)(j), 1) = parExcludeCharacter Then
          locLinesList(i)(j) = Left(locLinesList(i)(j), Len(locLinesList(i)(j)) - 1)
        End If
        locData(i, j + 1) = locLinesList(i)(j)
      Next j
    Next i

  Else

    For i = 1 To locNumRows
      For j = 0 To UBound(locLinesList(i), 1)
        locData(i, j + 1) = locLinesList(i)(j)
      Next j
    Next i

  End If

  getDataFromFile = locData

  Exit Function

error_open_file:             'returns empty variant
unhandled_error:             'returns empty variant

End Function

How do I include inline JavaScript in Haml?

You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript, which is was I needed to do for MathJax.

You can use the plain filter to keep HAML from parsing the script and throwing an illegal nesting error:

%script{type: "text/x-mathjax-config"}
  :plain
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [["$","$"],["\\(","\\)"]]
      }
    });

Handling the null value from a resultset in JAVA

The String being null is a very good chance, but when you see values in your table, yet a null is printed by the ResultSet, it might mean that the connection was closed before the value of ResultSet was used.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
con.close();
System.out.println(rs.getString(1));

Would print null even if there are values.

Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:My_db.db");
String sql = ("select * from cust where cust_id='" + cus + "'");
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs.getString(1));
con.close();

Wouldn't print null if there are values in the table.

How to change Tkinter Button state from disabled to normal?

I think a quick way to change the options of a widget is using the configure method.

In your case, it would look like this:

self.x.configure(state=NORMAL)

How to make a radio button unchecked by clicking it?

I'm surprised no-one has posted this "neat trick" version which doesn't use any JavaScript, it only uses CSS.

_x000D_
_x000D_
#radio1 {
    display: none;
}

#wrapper {
    /* NOTE: This wrapper div is not needed provided you can position the label for #radio1 on top of #radio2 using some other technique. */
    position: relative;
}

#radio1:not(:checked) ~ * label[for="radio1"] {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
#radio1:checked ~ * label[for="radio1"] {
    display: none;
}

/* Non-essential styles: */ 

label[for],
label:not([for="radio1"]) {
    cursor: pointer;
    border-radius: 7px;
}
label[for]:hover + label,
label:not([for="radio1"]):hover {
    background-color: #ccc;
}
_x000D_
<input type="radio" name="group1" id="radio1" checked="checked"  />

<p>Look mum, <strong>no JavaScript!</strong></p>

<div id="wrapper">
    <label for="radio1"></label>
    <label>
        <input type="radio" name="group1" id="radio2" />
        You can toggle me on and off!
    </label>
</div>
_x000D_
_x000D_
_x000D_


Explanation:

  • #radio1 (<input type="radio" id="radio2" />) is always hidden.
  • Using CSS's :checked and :not(:checked) pseudo-class selectors with sibling selectors (+ and ~) allow other elements' style to be affected depending on whether or not an <input type="checkbox" /> or <input type="radio" /> is checked.
    • So when #radio1 is un-checked (or when #radio2 is checked) that causes a <label> to be overlayed on-top of #radio2 and that label has for="radio1", so clicking it will cause #radio1 to be checked, not #radio2.
    • IMPORTANT CAVEAT: CSS's sibling selector rules only allows selectors to select elements based on their ancestors and their ancestors earlier siblings. So you cannot style an element based on any other descendants of its ancestors.
      • This limitation will be removed when CSS4's :has() selector function is supported but as of November 2020 only PrinceXML supports :has() and it's currently looking like :has() will be dropped from CSS4 entirely owing to the difficulty of implementation.

This approach can be scaled to support multiple radio buttons:

_x000D_
_x000D_
#uncheckAll {
    display: none;
}

#uncheckAll:checked ~ * label[for="uncheckAll"] {
    display: none;
}

label {
    cursor: pointer;
}

label:not([for]) {
    position: relative;
}

label[for="uncheckAll"] {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

input[name="group1"]:not(:checked) + label[for="uncheckAll"] {
    display: none;
}
_x000D_
<input type="radio" name="group1" id="uncheckAll" checked="checked"  />

<label>
    <input type="radio" name="group1" id="radio2" />
    <label for="uncheckAll"></label>
    You can toggle me on and off!
</label>

<label>
    <input type="radio" name="group1" id="radio3" />
    <label for="uncheckAll"></label>
    And me!
</label>

<label>
    <input type="radio" name="group1" id="aragorn" />
    <label for="uncheckAll"></label>
    And my sword!
</label>

<label>
    <input type="radio" name="group1" id="gimli" />
    <label for="uncheckAll"></label>
    And my axe!
</label>
_x000D_
_x000D_
_x000D_

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):
    os.makedirs(path)

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
    temp_file.write(buff)

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

How do I center text horizontally and vertically in a TextView?

Try this:

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" />

The process cannot access the file because it is being used by another process (File is created but contains nothing)

using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine(message);
}

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

Google Spreadsheet, Count IF contains a string

Try just =COUNTIF(A2:A51,"iPad")

htaccess redirect to https://www

BAD SOLUTION AND WHY!

Don't ever use the solution below because when you are using their code that is something like:

RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]

The browser goes to:

http://example.com

Then redirects to:

https://example.com

Then redirects to:

https://www.example.com

This is too much request to the server.

Most of the answers even accepted one has this problem.


BEST SOLUTION AND THE ANSWER

This code has an [OR] condition to prevent dual changes at url!

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.example.com%{REQUEST_URI} [R=301,L]

Call a function on click event in Angular 2

Exact transfer to Angular2+ is as below:

<button (click)="myFunc()"></button>

also in your component file:

import { Component, OnInit } from "@angular/core";

@Component({
  templateUrl:"button.html" //this is the component which has the above button html
})

export class App implements OnInit{
  constructor(){}

  ngOnInit(){

  }

  myFunc(){
    console.log("function called");
  }
}

Java double.MAX_VALUE?

Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.

double has 64 bits. The first one is reserved for the sign.

Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.

Then there are 52 bits that hold the mantissa.

This is easily computed like this for example:

public static void main(String[] args) {

    String test = Strings.repeat("1", 52);

    double first = 0.5;
    double result = 0.0;
    for (char c : test.toCharArray()) {
        result += first;
        first = first / 2;
    }

    System.out.println(result); // close approximation of 1
    System.out.println(Math.pow(2, 1023) * (1 + result));
    System.out.println(Double.MAX_VALUE);

} 

You can also prove this in reverse order :

    String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));

    String sign = max.substring(0, 1);
    String exponent = max.substring(1, 12); // 11111111110
    String mantissa = max.substring(12, 64);

    System.out.println(sign); // 0 - positive
    System.out.println(exponent); // 2046 - 1023 = 1023
    System.out.println(mantissa); // 0.99999...8

Displaying a message in iOS which has the same functionality as Toast in Android

I thought off a simple way to do the toast! using UIAlertController without button! We use the button text as our message! get it? see below code:

func alert(title: String?, message: String?, bdy:String) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
    let okAction = UIAlertAction(title: bdy, style: .Cancel, handler: nil)
    alertController.addAction(okAction)
        self.presentViewController(alertController, animated: true, completion: nil)


    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue()) {
        //print("Bye. Lovvy")
        alertController.dismissViewControllerAnimated(true, completion: nil) 
    }    
}

use it like this:

self.alert(nil,message:nil,bdy:"Simple Toast!") // toast
self.alert(nil,message:nil,bdy:"Alert") // alert with "Alert" button

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

to have unit-testing AND integration-testing you can use maven-surefire-plugin and maven-failsafe-plugin with restricted includes/excludes. I was playing with CDI while getting in touch with sonar/jacoco, so i ended up in this project:

https://github.com/FibreFoX/cdi-sessionscoped-login/

Maybe it helps you a little bit. in my pom.xml i use "-javaagent" implicit by setting the argLine-option in the configuration-section of the specified testing-plugins. Explicit using ANT in MAVEN projects is something i would not give a try, for me its to much mixing two worlds.

I only have a single-module maven project, but maybe it helps you to adjust yours to work.

note: maybe not all maven-plugins are up2date, maybe some issues are fixed in later versions

Android XML Percent Symbol

Try this one (right):

<string name="content" formatted="false">Great application %s  ?  %s  ?  %s \\n\\nGo to download this application %s</string>

Python - Module Not Found

If it's your root module just add it to PYTHONPATH (PyCharm usually does that)

export PYTHONPATH=$PYTHONPATH:<root module path>

for Docker:

ENV PYTHONPATH="${PYTHONPATH}:<root module path in container>"

How to differentiate single click event and double click event?

You need to use a timeout to check if there is an another click after the first click.

Here is the trick:

// Author:  Jacek Becela
// Source:  http://gist.github.com/399624
// License: MIT

jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
  return this.each(function(){
    var clicks = 0, self = this;
    jQuery(this).click(function(event){
      clicks++;
      if (clicks == 1) {
        setTimeout(function(){
          if(clicks == 1) {
            single_click_callback.call(self, event);
          } else {
            double_click_callback.call(self, event);
          }
          clicks = 0;
        }, timeout || 300);
      }
    });
  });
}

Usage:

$("button").single_double_click(function () {
  alert("Try double-clicking me!")
}, function () {
  alert("Double click detected, I'm hiding")
  $(this).hide()
})
<button>Click Me!</button>

EDIT:

As stated below, prefer using the native dblclick event: http://www.quirksmode.org/dom/events/click.html

Or the one provided by jQuery: http://api.jquery.com/dblclick/

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

This worked for me:

Check the current role you are logged into by using: SELECT CURRENT_USER, SESSION_USER;

Note: It must match with Owner of the schema.

Schema | Name | Type | Owner
--------+--------+-------+----------

If the owner is different, then give all the grants to the current user role from the admin role by :

GRANT 'ROLE_OWNER' to 'CURRENT ROLENAME';

Then try to execute the query, it will give the output as it has access to all the relations now.

Can I use if (pointer) instead of if (pointer != NULL)?

I think as a rule of thumb, if your if-expression can be re-written as

const bool local_predicate = *if-expression*;
if (local_predicate) ...

such that it causes NO WARNINGS, then THAT should be the preferred style for the if-expression. (I know I get warnings when I assign an old C BOOL (#define BOOL int) to a C++ bool, let alone pointers.)

How do I make a WinForms app go Full Screen

You need to set your window to be topmost.

Getting data from selected datagridview row and which event?

You should check your designer file. Open Form1.Designer.cs and
find this line: windows Form Designer Generated Code.
Expand this and you will see a lot of code. So check Whether this line is there inside datagridview1 controls if not place it.

this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick); 

I hope it helps.

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

Playing m3u8 Files with HTML Video Tag

Use Flowplayer:

<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
    <style>

   </style>
   <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
  <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script> 
  <script>
  flowplayer(function (api) {
    api.on("load", function (e, api, video) {
      $("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
    }); });
  </script>

<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
      style="    width: 85.5%;
    height: 80%;
    margin-left: 7.2%;
    margin-top: 6%;
    z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625"  data-logo="">
      <video autoplay="true" stretch="true">

         <source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
      </video>   
   </div>

Different methods are available in flowplayer.org website.

Is there any use for unique_ptr with array?

One additional reason to allow and use std::unique_ptr<T[]>, that hasn't been mentioned in the responses so far: it allows you to forward-declare the array element type.

This is useful when you want to minimize the chained #include statements in headers (to optimize build performance.)

For instance -

myclass.h:

class ALargeAndComplicatedClassWithLotsOfDependencies;

class MyClass {
   ...
private:
   std::unique_ptr<ALargeAndComplicatedClassWithLotsOfDependencies[]> m_InternalArray;
};

myclass.cpp:

#include "myclass.h"
#include "ALargeAndComplicatedClassWithLotsOfDependencies.h"

// MyClass implementation goes here

With the above code structure, anyone can #include "myclass.h" and use MyClass, without having to include the internal implementation dependencies required by MyClass::m_InternalArray.

If m_InternalArray was instead declared as a std::array<ALargeAndComplicatedClassWithLotsOfDependencies>, or a std::vector<...>, respectively - the result would be attempted usage of an incomplete type, which is a compile-time error.

Android 'Unable to add window -- token null is not for an application' exception

I tried with this in the context field:

this.getActivity().getParent()

and it works fine for me. This was from a class which extends from "Fragment":

public class filtro extends Fragment{...

Unable to allocate array with shape and data type

Sometimes, this error pops up because of the kernel has reached its limit. Try to restart the kernel redo the necessary steps.

Java random numbers using a seed

The easy way is to use:

Random rand = new Random(System.currentTimeMillis());

This is the best way to generate Random numbers.

CSS get height of screen resolution

You can get the window height quite easily in pure CSS, using the units "vh", each corresponding to 1% of the window height. On the example below, let's begin to centralize block.foo by adding a margin-top half the size of the screen.

.foo{
    margin-top: 50vh;
}

But that only works for 'window' size. With a dab of javascript, you could make it more versatile.

$(':root').css("--windowHeight", $( window ).height() );

That code will create a CSS variable named "--windowHeight" that carries the height of the window. To use it, just add the rule:

.foo{
    margin-top: calc( var(--windowHeight) / 2 );
}

And why is it more versatile than simply using "vh" units? Because you can get the height of any element. Now if you want to centralize a block.foo in any container.bar, you could:

$(':root').css("--containerHeight", $( .bar ).height() );
$(':root').css("--blockHeight", $( .foo ).height() );

.foo{
    margin-top: calc( var(--containerHeight) / 2 - var(--blockHeight) / 2);
}

And finally, for it to respond to changes on the window size, you could use (in this example, the container is 50% the window height):

$( window ).resize(function() {
    $(':root').css("--containerHeight", $( .bar ).height()*0.5 );
});

Extracting time from POSIXct

There have been previous answers that showed the trick. In essence:

  • you must retain POSIXct types to take advantage of all the existing plotting functions

  • if you want to 'overlay' several days worth on a single plot, highlighting the intra-daily variation, the best trick is too ...

  • impose the same day (and month and even year if need be, which is not the case here)

which you can do by overriding the day-of-month and month components when in POSIXlt representation, or just by offsetting the 'delta' relative to 0:00:00 between the different days.

So with times and val as helpfully provided by you:

## impose month and day based on first obs
ntimes <- as.POSIXlt(times)    # convert to 'POSIX list type'
ntimes$mday <- ntimes[1]$mday  # and $mon if it differs too
ntimes <- as.POSIXct(ntimes)   # convert back

par(mfrow=c(2,1))
plot(times,val)   # old times
plot(ntimes,val)  # new times

yields this contrasting the original and modified time scales:

enter image description here

Set style for TextView programmatically

I do not believe you can set the style programatically. To get around this you can create a template layout xml file with the style assigned, for example in res/layout create tvtemplate.xml as with the following content:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is a template"
        style="@style/my_style" />

then inflate this to instantiate your new TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);

Hope this helps.

Ajax call Into MVC Controller- Url Issue

In order for this to work that Javascript must be placed within a Razor view so that the line

@Url.Action("Action","Controller")

is parsed by Razor and the real value replaced.

If you don't want to move your Javascript into your View you could look at creating a settings object in the view and then referencing that from your Javascript file.

e.g.

var MyAppUrlSettings = {
    MyUsefulUrl : '@Url.Action("Action","Controller")'
}

and in your .js file

$.ajax({
 type: "POST",
 url: MyAppUrlSettings.MyUsefulUrl,
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
 alert("here" + data.d.toString());
});

or alternatively look at levering the framework's built in Ajax methods within the HtmlHelpers which allow you to achieve the same without "polluting" your Views with JS code.

Check if a row exists, otherwise insert

The best approach to this problem is first making the database column UNIQUE

ALTER TABLE table_name ADD UNIQUE KEY

THEN INSERT IGNORE INTO table_name ,the value won't be inserted if it results in a duplicate key/already exists in the table.

Java - What does "\n" mean?

Its is a new line

Escape Sequences
Escape Sequence Description
\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

http://docs.oracle.com/javase/tutorial/java/data/characters.html

Inline JavaScript onclick function

This should work

 <a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>

You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block

Convert factor to integer

Quoting directly from the help page for factor:

To transform a factor f to its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

ngrok command not found

On Windows 10, for me

ngrok http 80

behaves like this:

  • works from Command Prompt (cmd.exe)
  • does not work from Git Bash
  • does not work from Windows PowerShell