Programs & Examples On #Paintcomponent

paintComponent (JComponent.paintComponent(Graphics g)) is a method that Java Swing engine calls on JComponent, in order to draw it using the passed Graphics.

How to draw in JPanel? (Swing/graphics Java)

Note the extra comments.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

class JavaPaintUI extends JFrame {

    private int tool = 1;
    int currentX, currentY, oldX, oldY;

    public JavaPaintUI() {
        initComponents();
    }

    private void initComponents() {
        // we want a custom Panel2, not a generic JPanel!
        jPanel2 = new Panel2();

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jPanel2.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                jPanel2MousePressed(evt);
            }
            public void mouseReleased(MouseEvent evt) {
                jPanel2MouseReleased(evt);
            }
        });
        jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent evt) {
                jPanel2MouseDragged(evt);
            }
        });

        // add the component to the frame to see it!
        this.setContentPane(jPanel2);
        // be nice to testers..
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }// </editor-fold>

    private void jPanel2MouseDragged(MouseEvent evt) {
        if (tool == 1) {
            currentX = evt.getX();
            currentY = evt.getY();
            oldX = currentX;
            oldY = currentY;
            System.out.println(currentX + " " + currentY);
            System.out.println("PEN!!!!");
        }
    }

    private void jPanel2MousePressed(MouseEvent evt) {
        oldX = evt.getX();
        oldY = evt.getY();
        System.out.println(oldX + " " + oldY);
    }


    //mouse released//
    private void jPanel2MouseReleased(MouseEvent evt) {
        if (tool == 2) {
            currentX = evt.getX();
            currentY = evt.getY();
            System.out.println("line!!!! from" + oldX + "to" + currentX);
        }
    }

    //set ui visible//
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaPaintUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private JPanel jPanel2;
    // End of variables declaration

    // This class name is very confusing, since it is also used as the
    // name of an attribute!
    //class jPanel2 extends JPanel {
    class Panel2 extends JPanel {

        Panel2() {
            // set a preferred size for the custom panel.
            setPreferredSize(new Dimension(420,420));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.drawString("BLAH", 20, 20);
            g.drawRect(200, 200, 200, 200);
        }
    }
}

Screen Shot

enter image description here

Other examples - more tailored to multiple lines & multiple line segments

HFOE put a good link as the first comment on this thread. Camickr also has a description of active painting vs. drawing to a BufferedImage in the Custom Painting Approaches article.

See also this approach using painting in a BufferedImage.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

The fillOval fits an oval inside a rectangle, with width=r, height = r you get a circle. If you want fillOval(x,y,r,r) to draw a circle with the center at (x,y) you will have to displace the rectangle by half its width and half its height.

public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
  x = x-(r/2);
  y = y-(r/2);
  g.fillOval(x,y,r,r);
}

This will draw a circle with center at x,y

How does paintComponent work?

Two things you can do here:

  1. Read Painting in AWT and Swing
  2. Use a debugger and put a breakpoint in the paintComponent method. Then travel up the stacktrace and see how provides the Graphics parameter.

Just for info, here is the stacktrace that I got from the example of code I posted at the end:

Thread [AWT-EventQueue-0] (Suspended (breakpoint at line 15 in TestPaint))  
    TestPaint.paintComponent(Graphics) line: 15 
    TestPaint(JComponent).paint(Graphics) line: 1054    
    JPanel(JComponent).paintChildren(Graphics) line: 887    
    JPanel(JComponent).paint(Graphics) line: 1063   
    JLayeredPane(JComponent).paintChildren(Graphics) line: 887  
    JLayeredPane(JComponent).paint(Graphics) line: 1063 
    JLayeredPane.paint(Graphics) line: 585  
    JRootPane(JComponent).paintChildren(Graphics) line: 887 
    JRootPane(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5228   
    RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1482 
    RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1413  
    RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1206   
    JRootPane(JComponent).paint(Graphics) line: 1040    
    GraphicsCallback$PaintCallback.run(Component, Graphics) line: 39    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runOneComponent(Component, Rectangle, Graphics, Shape, int) line: 78    
    GraphicsCallback$PaintCallback(SunGraphicsCallback).runComponents(Component[], Graphics, int) line: 115 
    JFrame(Container).paint(Graphics) line: 1967    
    JFrame(Window).paint(Graphics) line: 3867   
    RepaintManager.paintDirtyRegions(Map<Component,Rectangle>) line: 781    
    RepaintManager.paintDirtyRegions() line: 728    
    RepaintManager.prePaintDirtyRegions() line: 677 
    RepaintManager.access$700(RepaintManager) line: 59  
    RepaintManager$ProcessingRunnable.run() line: 1621  
    InvocationEvent.dispatch() line: 251    
    EventQueue.dispatchEventImpl(AWTEvent, Object) line: 705    
    EventQueue.access$000(EventQueue, AWTEvent, Object) line: 101   
    EventQueue$3.run() line: 666    
    EventQueue$3.run() line: 664    
    AccessController.doPrivileged(PrivilegedAction<T>, AccessControlContext) line: not available [native method]    
    ProtectionDomain$1.doIntersectionPrivilege(PrivilegedAction<T>, AccessControlContext, AccessControlContext) line: 76    
    EventQueue.dispatchEvent(AWTEvent) line: 675    
    EventDispatchThread.pumpOneEventForFilters(int) line: 211   
    EventDispatchThread.pumpEventsForFilter(int, Conditional, EventFilter) line: 128    
    EventDispatchThread.pumpEventsForHierarchy(int, Conditional, Component) line: 117   
    EventDispatchThread.pumpEvents(int, Conditional) line: 113  
    EventDispatchThread.pumpEvents(Conditional) line: 105   
    EventDispatchThread.run() line: 90  

The Graphics parameter comes from here:

RepaintManager.paintDirtyRegions(Map) line: 781 

The snippet involved is the following:

Graphics g = JComponent.safelyGetGraphics(
                        dirtyComponent, dirtyComponent);
                // If the Graphics goes away, it means someone disposed of
                // the window, don't do anything.
                if (g != null) {
                    g.setClip(rect.x, rect.y, rect.width, rect.height);
                    try {
                        dirtyComponent.paint(g); // This will eventually call paintComponent()
                    } finally {
                        g.dispose();
                    }
                }

If you take a look at it, you will see that it retrieve the graphics from the JComponent itself (indirectly with javax.swing.JComponent.safelyGetGraphics(Component, Component)) which itself takes it eventually from its first "Heavyweight parent" (clipped to the component bounds) which it self takes it from its corresponding native resource.

Regarding the fact that you have to cast the Graphics to a Graphics2D, it just happens that when working with the Window Toolkit, the Graphics actually extends Graphics2D, yet you could use other Graphics which do "not have to" extends Graphics2D (it does not happen very often but AWT/Swing allows you to do that).

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

class TestPaint extends JPanel {

    public TestPaint() {
        setBackground(Color.WHITE);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(0, 0, getWidth(), getHeight());
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(300, 300);
        jFrame.add(new TestPaint());
        jFrame.setVisible(true);
    }
}

Reloading submodules in IPython

Module named importlib allow to access to import internals. Especially, it provide function importlib.reload():

import importlib
importlib.reload(my_module)

In contrary of %autoreload, importlib.reload() also reset global variables set in module. In most cases, it is what you want.

importlib is only available since Python 3.1. For older version, you have to use module imp.

makefile execute another target

If you removed the make all line from your "fresh" target:

fresh :
    rm -f *.o $(EXEC)
    clear

You could simply run the command make fresh all, which will execute as make fresh; make all.

Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.

How to fully clean bin and obj folders within Visual Studio?

In windows just open the explorer navigate to your SLN folder click into search field and type kind:=folder;obj --> for obj folders use CTRL+A and delete 'em - same for bin Done

No need for any tool or extra software ;)

Default values in a C Struct

You can change your secret special value to 0, and exploit C's default structure-member semantics

struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);

will then pass 0 as members of bar unspecified in the initializer.

Or you can create a macro that will do the default initialization for you:

#define FOO_INIT(...) { .id = -1, .current_route = -1, .quux = -1, ## __VA_ARGS__ }

struct foo bar = FOO_INIT( .id = 42, .current_route = new_route );
update(&bar);

Delete rows with foreign key in PostgreSQL

It's been a while since this question was asked, hope can help. Because you can not change or alter the db structure, you can do this. according the postgresql docs.

TRUNCATE -- empty a table or set of tables.

TRUNCATE [ TABLE ] [ ONLY ] name [ * ] [, ... ]
    [ RESTART IDENTITY | CONTINUE IDENTITY ] [ CASCADE | RESTRICT ]

Description

TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables.


Truncate the table othertable, and cascade to any tables that reference othertable via foreign-key constraints:

TRUNCATE othertable CASCADE;

The same, and also reset any associated sequence generators:

TRUNCATE bigtable, fattable RESTART IDENTITY;

Truncate and reset any associated sequence generators:

TRUNCATE revinfo RESTART IDENTITY CASCADE ;

Can you do a partial checkout with Subversion?

If you already have the full local copy, you can remove unwanted sub folders by using --set-depth command.

svn update --set-depth=exclude www

See: http://blogs.collab.net/subversion/sparse-directories-now-with-exclusion

The set-depth command support multipile paths.

Updating the root local copy will not change the depth of the modified folder.

To restore the folder to being recusively checkingout, you could use --set-depth again with infinity param.

svn update --set-depth=infinity www

How do you get the currently selected <option> in a <select> via JavaScript?

The .selectedIndex of the select object has an index; you can use that to index into the .options array.

How to detect READ_COMMITTED_SNAPSHOT is enabled?

SELECT is_read_committed_snapshot_on FROM sys.databases 
WHERE name= 'YourDatabase'

Return value:

  • 1: READ_COMMITTED_SNAPSHOT option is ON. Read operations under the READ COMMITTED isolation level are based on snapshot scans and do not acquire locks.
  • 0 (default): READ_COMMITTED_SNAPSHOT option is OFF. Read operations under the READ COMMITTED isolation level use Shared (S) locks.

for each loop in groovy

This one worked for me:

def list = [1,2,3,4]
for(item in list){
    println item
}

Source: Wikia.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

you can use this method just pass your date to it

-(NSString *)getDateFromString:(NSString *)string
{

    NSString * dateString = [NSString stringWithFormat: @"%@",string];

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"your current date format"];
    NSDate* myDate = [dateFormatter dateFromString:dateString];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"your desired format"];
    NSString *stringFromDate = [formatter stringFromDate:myDate];

    NSLog(@"%@", stringFromDate);
    return stringFromDate;
}

Can two applications listen to the same port?

Yes.

From this article:
https://lwn.net/Articles/542629/

The new socket option allows multiple sockets on the same host to bind to the same port

How do I use modulus for float/double?

You probably had a typo when you first ran it.

evaluating 0.5 % 0.3 returns '0.2' (A double) as expected.

Mindprod has a good overview of how modulus works in Java.

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

Laravel >= 5.3 method lists() is deprecated use pluck()

$items = Items::pluck('name', 'id');

{!! Form::select('items', $items, null, ['class' => 'some_css_class']) !!}

This will give you a select box with same select options as id numbers in DB

for example if you have this in your DB table:

id name
1  item1
2  item2
3  item3
4  item4

in select box it will be like this

<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>

I found out that pluck now returns a collection, and you need to add ->toArray() at the end of pluck...so like this: pluck('name', 'id')->toArray();

How do I see the current encoding of a file in Sublime Text?

With the EncodingHelper plugin you can view the encoding of the file on the status bar. Also you can convert the encoding of the file and extended another functionalities.

Demo

Checking for an empty file in C++

char ch;
FILE *f = fopen("file.txt", "r");

if(fscanf(f,"%c",&ch)==EOF)
{
    printf("File is Empty");
}
fclose(f);

jQuery find and replace string

You could do something like this:

HTML

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>


jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});

Start thread with member function

Since you are using C++11, lambda-expression is a nice&clean solution.

class blub {
    void test() {}
  public:
    std::thread spawn() {
      return std::thread( [this] { this->test(); } );
    }
};

since this-> can be omitted, it could be shorten to:

std::thread( [this] { test(); } )

or just (deprecated)

std::thread( [=] { test(); } )

AngularJS sorting rows by table header

Here is an example that sorts by the header. This table is dynamic and changes with the JSON size.

I was able to build a dynamic table off of some other people's examples and documentation. http://jsfiddle.net/lastlink/v7pszemn/1/

<tr>
    <th class="{{header}}" ng-repeat="(header, value) in items[0]" ng-click="changeSorting(header)">
    {{header}}
  <i ng-class="selectedCls2(header)"></i>
</tr>

<tbody>
    <tr ng-repeat="row in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse">
        <td ng-repeat="cell in row">
              {{cell}}
       </td>
    </tr>

Although the columns are out of order, on my .NET project they are in order.

Why is this HTTP request not working on AWS Lambda?

Yes, there's in fact many reasons why you can access AWS Lambda like and HTTP Endpoint.

The architecture of AWS Lambda

It's a microservice. Running inside EC2 with Amazon Linux AMI (Version 3.14.26–24.46.amzn1.x86_64) and runs with Node.js. The memory can be beetwen 128mb and 1gb. When the data source triggers the event, the details are passed to a Lambda function as parameter's.

What happen?

AWS Lambda run's inside a container, and the code is directly uploaded to this container with packages or modules. For example, we NEVER can do SSH for the linux machine running your lambda function. The only things that we can monitor are the logs, with CloudWatchLogs and the exception that came from the runtime.

AWS take care of launch and terminate the containers for us, and just run the code. So, even that you use require('http'), it's not going to work, because the place where this code runs, wasn't made for this.

Make copy of an array

All solution that call length from array, add your code redundant null checkersconsider example:

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();

//What if array a comes as local parameter? You need to use null check:

public void someMethod(int[] a) {
    if (a!=null) {
        int[] b = Arrays.copyOf(a, a.length);
        int[] c = a.clone();
    }
}

I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:

public void someMethod(int[] a) {
    int[] b = ArrayUtils.clone(a);
}

Apache commons you can find there

Left align and right align within div in Bootstrap

Instead of using pull-right class, it is better to use text-right class in the column, because pull-right creates problems sometimes while resizing the page.

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

extract column value based on another column pandas dataframe

It's easier for me to think in these terms, but borrowing from other answers. The value you want is located in the series:

df[*column*][*row*]

where column and row point to the value you want returned. For your example, column is 'A' and for row you use a mask:

df['B'] == 3

To get the value from the series there are several options:

df['A'][df['B'] == 3].values[0]
df['A'][df['B'] == 3].iloc[0]
df['A'][df['B'] == 3].to_numpy()[0]

Why maven? What are the benefits?

Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.

Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.

And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).

So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.

On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.

And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).

Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.

First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.

Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).

So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.

Date formatting in WPF datagrid

Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"

Rails: How do I create a default value for attributes in Rails activerecord's model?

Just strengthening Jim's answer

Using presence one can do

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status = status.presence || 'P'
  end
end

Add spaces between the characters of a string in Java?

If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Length is going to be 2*lengthofString-1.

Or creating a char array and converting it back to the string would yield the same result.

Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete.

Java logical operator short-circuiting

There are a couple of differences between the & and && operators. The same differences apply to | and ||. The most important thing to keep in mind is that && is a logical operator that only applies to boolean operands, while & is a bitwise operator that applies to integer types as well as booleans.

With a logical operation, you can do short circuiting because in certain cases (like the first operand of && being false, or the first operand of || being true), you do not need to evaluate the rest of the expression. This is very useful for doing things like checking for null before accessing a filed or method, and checking for potential zeros before dividing by them. For a complex expression, each part of the expression is evaluated recursively in the same manner. For example, in the following case:

(7 == 8) || ((1 == 3) && (4 == 4))

Only the emphasized portions will evaluated. To compute the ||, first check if 7 == 8 is true. If it were, the right hand side would be skipped entirely. The right hand side only checks if 1 == 3 is false. Since it is, 4 == 4 does not need to be checked, and the whole expression evaluates to false. If the left hand side were true, e.g. 7 == 7 instead of 7 == 8, the entire right hand side would be skipped because the whole || expression would be true regardless.

With a bitwise operation, you need to evaluate all the operands because you are really just combining the bits. Booleans are effectively a one-bit integer in Java (regardless of how the internals work out), and it is just a coincidence that you can do short circuiting for bitwise operators in that one special case. The reason that you can not short-circuit a general integer & or | operation is that some bits may be on and some may be off in either operand. Something like 1 & 2 yields zero, but you have no way of knowing that without evaluating both operands.

What is the Swift equivalent to Objective-C's "@synchronized"?

Why make it difficult and hassle with locks? Use Dispatch Barriers.

A dispatch barrier creates a synchronization point within a concurrent queue.

While it’s running, no other block on the queue is allowed to run, even if it’s concurrent and other cores are available.

If that sounds like an exclusive (write) lock, it is. Non-barrier blocks can be thought of as shared (read) locks.

As long as all access to the resource is performed through the queue, barriers provide very cheap synchronization.

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

You cannot check window.history.length as it contains the amount of pages in you visited in total in a given session:

window.history.length (Integer)

Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1

Lets say a user visits your page, clicks on some links and goes back:

www.mysite.com/index.html <-- first page and now current page                  <----+
www.mysite.com/about.html                                                           |
www.mysite.com/about.html#privacy                                                   | 
www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back

Now window.history.length is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.

You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:

window.goBack = function (e){
    var defaultLocation = "http://www.mysite.com";
    var oldHash = window.location.hash;

    history.back(); // Try to go back

    var newHash = window.location.hash;

    /* If the previous page hasn't been loaded in a given time (in this case
    * 1000ms) the user is redirected to the default location given above.
    * This enables you to redirect the user to another page.
    *
    * However, you should check whether there was a referrer to the current
    * site. This is a good indicator for a previous entry in the history
    * session.
    *
    * Also you should check whether the old location differs only in the hash,
    * e.g. /index.html#top --> /index.html# shouldn't redirect to the default
    * location.
    */

    if(
        newHash === oldHash &&
        (typeof(document.referrer) !== "string" || document.referrer  === "")
    ){
        window.setTimeout(function(){
            // redirect to default location
            window.location.href = defaultLocation;
        },1000); // set timeout in ms
    }
    if(e){
        if(e.preventDefault)
            e.preventDefault();
        if(e.preventPropagation)
            e.preventPropagation();
    }
    return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>

Note that typeof(document.referrer) !== "string" is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.

EDIT: Don't use <a href='#'>...</a>, as this will add another entry to the session history. It's better to use a <span> or some other element. Note that typeof document.referrer is always "string" and not empty if your page is inside of a (i)frame.

See also:

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

How to specify line breaks in a multi-line flexbox layout?

I tried several answers here, and none of them worked. Ironically, what did work was about the simplest alternative to a <br/> one could attempt:

<div style="flex-basis: 100%;"></div>

or you could also do:

<div style="width: 100%;"></div>

Place that wherever you want a new line. It seems to work even with adjacent <span>'s, but I'm using it with adjacent <div>'s.

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

How to serialize Object to JSON?

You make the http request

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

import org.json.JSONObject;

How do I reference a cell within excel named range?

You can use Excel's Index function:

=INDEX(Age, 5)

Generate ER Diagram from existing MySQL database, created for CakePHP

Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).

This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.

Invoking JavaScript code in an iframe from the parent page

Same things but a bit easier way will be How to refresh parent page from page within iframe. Just call the parent page's function to invoke javascript function to reload the page:

window.location.reload();

Or do this directly from the page in iframe:

window.parent.location.reload();

Both works.

What is @ModelAttribute in Spring MVC?

Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.

public String add(@ModelAttribute("specified") Model model) {
    ...
}

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

Android - how do I investigate an ANR?

I've been learning android for the last few months, so I'm far from an expert, but I've been really disappointed with the documentation on ANRs.

Most of the advice seems to be geared towards avoiding them or fixing them by blindly looking through your code, which is great, but I couldn't find anything on analyzing the trace.

There are three things you really need to look for with ANR logs.

1) Deadlocks: When a thread is in the WAIT state, you can look through the details to find who it's "heldby=". Most of the time, it'll be held by itself, but if it's held by another thread, that's likely to be a danger sign. Go look at that thread and see what it's held by. You might find a loop, which is a clear sign that something has gone wrong. This is pretty rare, but it's the first point because when it happens, it's a nightmare

2) Main thread Waiting: If your main thread is in the WAIT state, check if it's held by another thread. This shouldn't happen, because your UI thread shouldn't be held by a background thread.

Both of these scenarios, mean you need to rework your code significantly.

3) Heavy operations on the main thread: This is the most common cause of ANRs, but sometimes one of the harder to find and fix. Look at the main thread details. Scroll down the stack trace and until you see classes you recognize (from your app). Look at the methods in the trace and figure out if you're making network calls, db calls, etc. in these places.

Finally, and I apologize for shamelessly plugging my own code, you can use the python log analyzer I wrote at https://github.com/HarshEvilGeek/Android-Log-Analyzer This will go through your log files, open ANR files, find deadlocks, find waiting main threads, find uncaught exceptions in your agent logs and print it all out on the screen in a relatively easy to read manner. Read the ReadMe file (which I'm about to add) to learn how to use it. It's helped me a ton in the last week!

How to paste yanked text into the Vim command line

I was having a similar problem. I wanted the selected text to end up in a command, but not rely on pasting it in. Here's the command I was trying to write a mapping for:

:call VimuxRunCommand("python")

The docs for this plugin only show using string literals. The following will break if you try to select text that contains doublequotes:

vnoremap y:call VimuxRunCommand("<c-r>"")<cr>

To get around this, you just reference the contents of the macro using @ :

vnoremap y:call VimuxRunCommand(@")<cr>

Passes the contents of the unnamed register in and works with my double quote and multiline edgecases.

How to select date without time in SQL

The fastest is datediff, e.g.

select dateadd(d, datediff(d,0, [datecolumn]), 0), other..
from tbl

But if you only need to use the value, then you can skip the dateadd, e.g.

select ...
WHERE somedate <= datediff(d, 0, getdate())

where the expression datediff(d, 0, getdate()) is sufficient to return today's date without time portion.

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

In my case the problem was that the class was located in test package. Moving it to main package has solved the problem.

What is the simplest SQL Query to find the second largest value?

SELECT 
    * 
FROM 
    table 
WHERE 
    column < (SELECT max(columnq) FROM table) 
ORDER BY 
    column DESC LIMIT 1

How can I run dos2unix on an entire directory?

I have had the same problem and thanks to the posts here I have solved it. I knew that I have around a hundred files and I needed to run it for *.js files only. find . -type f -name '*.js' -print0 | xargs -0 dos2unix

Thank you all for your help.

display: inline-block extra margin

The divs are treated as inline-elements. Just as a space or line-break between two spans would create a gap, it does between inline-blocks. You could either give them a negative margin or set word-spacing: -1; on the surrounding container.

How to set a cron job to run every 3 hours

The unix setup should be like the following:

 0 */3 * * * sh cron/update_old_citations.sh

good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

Console.log not working at all

I just had a same issue of none of my console message showing. It was simply because I was using the new Edge (Chromium based) browser on Windows 10. It does not show my console messages whereas Chrome does. I guessed it was an issue with Edge because I had another odd issue with Edge because it treated strings with single quotes and double quotes differently.

Export pictures from excel file into jpg using VBA

New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.

Option Explicit

Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

Sub weGucciFam()

Dim tmp As Variant, str As String, h As Double, w As Double

Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"

keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28

str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height

Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
    .PageSetup.PaperSize = xlPaper11x17
    .PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
    .PageSetup.BottomMargin = 0
    .PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
    .PageSetup.LeftMargin = 0
    .PageSetup.HeaderMargin = 0
    .PageSetup.FooterMargin = 0
    .SeriesCollection(1).Delete
    DoEvents
    .Paste
    DoEvents
    .Export Filename:=str, Filtername:="jpeg"
    .Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
    wsTMP.Shapes(1).Delete
Loop

Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False

End Sub

vuejs update parent data from child component

I think this will do the trick:

@change="$emit(variable)"

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

I have incorporated this (with little to no modification) into a UWP DataBinding Converter for my project and thought it might also be useful to others.

The code is:

using System;
using System.Text;
using Windows.UI.Xaml.Data;

namespace MyApp.Converters
{
    public class ByteSizeConverter : IValueConverter
    {
        static readonly string[] sSizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

        // The number of decimal places the formatter should include in the scaled output - default 1dp
        public int DecimalPlaces { get; set; } = 1;

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            Int64 intVal = System.Convert.ToInt64(value);

            return SizeSuffix(intVal);
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            // TODO: Parse string into number and suffix
            //       Scale number by suffix multiplier to get bytes
            throw new NotImplementedException();
        }

        string SizeSuffix(Int64 value)
        {
            if (this.DecimalPlaces < 0) { throw new ArgumentOutOfRangeException(String.Format("DecimalPlaces = {0}", this.DecimalPlaces)); }
            if (value < 0) { return "-" + SizeSuffix(-value); }
            if (value == 0) { return string.Format("{0:n" + this.DecimalPlaces + "} bytes", 0); }

            // magnitude is 0 for bytes, 1 for KB, 2, for MB, etc.
            int magnitude = (int)Math.Log(value, 1024);
            // clip magnitude - only 8 values currently supported, this prevents out-of-bounds exception
            magnitude = Math.Min(magnitude, 8);

            // 1L << (magnitude * 10) == 2 ^ (10 * magnitude) [i.e. the number of bytes in the unit corresponding to magnitude]
            decimal adjustedSize = (decimal)value / (1L << (magnitude * 10));

            // make adjustment when the value is large enough that it would round up to 1000 or more
            if (Math.Round(adjustedSize, this.DecimalPlaces) >= 1000)
            {
                magnitude += 1;
                adjustedSize /= 1024;
            }

            return String.Format("{0:n" + this.DecimalPlaces + "} {1}", adjustedSize, sSizeSuffixes[magnitude]);
        }
    }
}

To use it, add a local resource to your UserControl or Page XAML:

<UserControl.Resources>
    <converters:ByteSizeConverter x:Key="ByteFormat" DecimalPlaces="3" />
</UserControl.Resources>

Reference it in a data binding template or data binding instance:

<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center"
    Text="{x:Bind MyItem.FileSize_bytes, Mode=OneWay, Converter={StaticResource ByteFormat}}" />

And hey presto. The magic happens.

ArrayList - How to modify a member of an object?

I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:

import java.util.*;

public class Customer {

    private String name;
    private String email;

    public Customer(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return name + " | " + email;
    }

    public static String toString(Collection<Customer> customers) {
        String s = "";
        for(Customer customer : customers) {
            s += customer + "\n";
        }
        return s;
    }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer("Bert", "[email protected]"));
        customers.add(new Customer("Ernie", "[email protected]"));
        System.out.println("customers before email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
        customers.get(1).setEmail("[email protected]");
        System.out.println("customers after email change - start");
        System.out.println(Customer.toString(customers));
        System.out.println("end");
    }

}

to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.

What's the simplest way to print a Java array?

You could loop through the array, printing out each item, as you loop. For example:

String[] items = {"item 1", "item 2", "item 3"};

for(int i = 0; i < items.length; i++) {

    System.out.println(items[i]);

}

Output:

item 1
item 2
item 3

Using Python, how can I access a shared folder on windows network?

Use forward slashes to specify the UNC Path:

open('//HOST/share/path/to/file')

(if your Python client code is also running under Windows)

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

You can use:

var dictionary = myList.ToDictionary(x => x);

How to split a dataframe string column into two columns?

You can extract the different parts out quite neatly using a regex pattern:

In [11]: df.row.str.extract('(?P<fips>\d{5})((?P<state>[A-Z ]*$)|(?P<county>.*?), (?P<state_code>[A-Z]{2}$))')
Out[11]: 
    fips                    1           state           county state_code
0  00000        UNITED STATES   UNITED STATES              NaN        NaN
1  01000              ALABAMA         ALABAMA              NaN        NaN
2  01001   Autauga County, AL             NaN   Autauga County         AL
3  01003   Baldwin County, AL             NaN   Baldwin County         AL
4  01005   Barbour County, AL             NaN   Barbour County         AL

[5 rows x 5 columns]

To explain the somewhat long regex:

(?P<fips>\d{5})
  • Matches the five digits (\d) and names them "fips".

The next part:

((?P<state>[A-Z ]*$)|(?P<county>.*?), (?P<state_code>[A-Z]{2}$))

Does either (|) one of two things:

(?P<state>[A-Z ]*$)
  • Matches any number (*) of capital letters or spaces ([A-Z ]) and names this "state" before the end of the string ($),

or

(?P<county>.*?), (?P<state_code>[A-Z]{2}$))
  • matches anything else (.*) then
  • a comma and a space then
  • matches the two digit state_code before the end of the string ($).

In the example:
Note that the first two rows hit the "state" (leaving NaN in the county and state_code columns), whilst the last three hit the county, state_code (leaving NaN in the state column).

Asynchronous Requests with Python requests

from threading import Thread

threads=list()

for requestURI in requests:
    t = Thread(target=self.openURL, args=(requestURI,))
    t.start()
    threads.append(t)

for thread in threads:
    thread.join()

...

def openURL(self, requestURI):
    o = urllib2.urlopen(requestURI, timeout = 600)
    o...

Convert IQueryable<> type object to List<T> type?

Add the following:

using System.Linq

...and call ToList() on the IQueryable<>.

How to insert TIMESTAMP into my MySQL table?

If you have a specific integer timestamp to insert/update, you can use PHP date() function with your timestamp as second arg :

date("Y-m-d H:i:s", $myTimestamp)

Regex date format validation on Java

Below added code is working for me if you are using pattern dd-MM-yyyy.

public boolean isValidDate(String date) {
        boolean check;
        String date1 = "^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-([12][0-9]{3})$";
        check = date.matches(date1);

        return check;
    }

How to provide user name and password when connecting to a network share

One option that might work is using WindowsIdentity.Impersonate (and change the thread principal) to become the desired user, like so. Back to p/invoke, though, I'm afraid...

Another cheeky (and equally far from ideal) option might be to spawn a process to do the work... ProcessStartInfo accepts a .UserName, .Password and .Domain.

Finally - perhaps run the service in a dedicated account that has access? (removed as you have clarified that this isn't an option).

Disable mouse scroll wheel zoom on embedded Google Maps

For google maps v2 - GMap2:

ar map = new GMap2(document.getElementById("google_map"));
map.disableScrollWheelZoom();

What is the Windows version of cron?

pycron is close match on Windows. The following entries are supported:

1    Minute (0-59)
2    Hour (2-24)
3    Day of month (1-31)
4    Month (1-12, Jan, Feb, etc)
5    Day of week (0-6) 0 = Sunday, 1 = Monday etc or Sun, Mon, etc)
6    User that the command will run as
7    Command to execute

C99 stdint.h header and MS Visual Studio

Microsoft do not support C99 and haven't announced any plans to. I believe they intend to track C++ standards but consider C as effectively obsolete except as a subset of C++.

New projects in Visual Studio 2003 and later have the "Compile as C++ Code (/TP)" option set by default, so any .c files will be compiled as C++.

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

Android ViewPager with bottom dots

If anyone wants to build a viewPager with thumbnails as indicators, using this library could be an option: ThumbIndicator for viewPager that works also with image links as resources.

How to vertically align a html radio button to it's label?

input {
    display: table-cell;
    vertical-align: middle
}

Put class for all radio. This will work for all radio button on the html page.

Fiddle

How to get CRON to call in the correct PATHs

@Trevino: your answer helped me solve my problem. However, for a beginner, trying to give a step by step approach.

  1. Get your current installation of java via $ echo $JAVA_HOME
  2. $ crontab -e
  3. * * * * * echo $PATH - this lets you understand whats the PATH value being used by crontab at present. Run crontab and grab $PATH value used by crontab.
  4. Now edit crontab again to set your desired java bin path: a) crontab -e; b) PATH=<value of $JAVA_HOME>/bin:/usr/bin:/bin (its a sample path); c) now your scheduled job/script like */10 * * * * sh runMyJob.sh &; d) remove echo $PATH from crontab as its not needed now.

Enter key press behaves like a Tab in Javascript

The simplest vanilla JS snippet I came up with:

document.addEventListener('keydown', function (event) {
  if (event.keyCode === 13 && event.target.nodeName === 'INPUT') {
    var form = event.target.form;
    var index = Array.prototype.indexOf.call(form, event.target);
    form.elements[index + 1].focus();
    event.preventDefault();
  }
});

Works in IE 9+ and modern browsers.

How to decode a QR-code image in (preferably pure) Python?

You can try the following steps and code using qrtools:

  • Create a qrcode file, if not already existing

    • I used pyqrcode for doing this, which can be installed using pip install pyqrcode
    • And then use the code:

      >>> import pyqrcode
      >>> qr = pyqrcode.create("HORN O.K. PLEASE.")
      >>> qr.png("horn.png", scale=6)
      
  • Decode an existing qrcode file using qrtools

    • Install qrtools using sudo apt-get install python-qrtools
    • Now use the following code within your python prompt

      >>> import qrtools
      >>> qr = qrtools.QR()
      >>> qr.decode("horn.png")
      >>> print qr.data
      u'HORN O.K. PLEASE.'
      

Here is the complete code in a single run:

In [2]: import pyqrcode
In [3]: qr = pyqrcode.create("HORN O.K. PLEASE.")
In [4]: qr.png("horn.png", scale=6)
In [5]: import qrtools
In [6]: qr = qrtools.QR()
In [7]: qr.decode("horn.png")
Out[7]: True
In [8]: print qr.data
HORN O.K. PLEASE.

Caveats

  • You might need to install PyPNG using pip install pypng for using pyqrcode
  • In case you have PIL installed, you might get IOError: decoder zip not available. In that case, try uninstalling and reinstalling PIL using:

    pip uninstall PIL
    pip install PIL
    
  • If that doesn't work, try using Pillow instead

    pip uninstall PIL
    pip install pillow
    

How can I run code on a background thread on Android?

If you need run thread predioticly with different codes here is example:

Listener:

public interface ESLThreadListener {

    public List onBackground();

    public void onPostExecute(List list);

}

Thread Class

public class ESLThread extends AsyncTask<Void, Void, List> {


    private ESLThreadListener mListener;

    public ESLThread() {

        if(mListener != null){

            mListener.onBackground();
        }
    }

    @Override
    protected List doInBackground(Void... params) {

        if(mListener != null){

            List list = mListener.onBackground();

            return list;
        }

        return null;
    }

    @Override
    protected void onPostExecute(List t) {
        if(mListener != null){

            if ( t != null) {
                mListener.onPostExecute(t);
            }
        }

    }


    public void setListener(ESLThreadListener mListener){

        this.mListener = mListener;
    }
}

Run different codes:

  ESLThread thread = new ESLThread();
                        thread.setListener(new ESLThreadListener() {
                            @Override
                            public List onBackground() {
                                List<EntityShoppingListItems>  data = RoomDB.getDatabase(context).sliDAO().getSL(fId);

                                return data;

                            }

                            @Override
                            public void onPostExecute(List t) {

                                List<EntityShoppingListItems> data = (List<EntityShoppingListItems>)t;
                                adapter.setList(data);
                            }
                        });

                        thread.execute();

Marker in leaflet, click event

I found the solution:

function onClick(e) {alert(this.getLatLng());}

used the method getLatLng() of the marker

How to convert hex to rgb using Java?

If you don't want to use the AWT Color.decode, then just copy the contents of the method:

int i = Integer.decode("#FFFFFF");
int[] rgb = new int[]{(i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF};

Integer.decode handles the # or 0x, depending on how your string is formatted

Creating an iframe with given HTML dynamically

Do this

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

console.log(frame_win);
...

getIframeWindow is defined here

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

How to handle anchor hash linking in AngularJS

You're looking for $anchorScroll().

Here's the (crappy) documentation.

And here's the source.

Basically you just inject it and call it in your controller, and it will scroll you to any element with the id found in $location.hash()

app.controller('TestCtrl', function($scope, $location, $anchorScroll) {
   $scope.scrollTo = function(id) {
      $location.hash(id);
      $anchorScroll();
   }
});

<a ng-click="scrollTo('foo')">Foo</a>

<div id="foo">Here you are</div>

Here is a plunker to demonstrate

EDIT: to use this with routing

Set up your angular routing as usual, then just add the following code.

app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
  //when the route is changed scroll to the proper element.
  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
    $location.hash($routeParams.scrollTo);
    $anchorScroll();  
  });
});

and your link would look like this:

<a href="#/test?scrollTo=foo">Test/Foo</a>

Here is a Plunker demonstrating scrolling with routing and $anchorScroll

And even simpler:

app.run(function($rootScope, $location, $anchorScroll) {
  //when the route is changed scroll to the proper element.
  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
    if($location.hash()) $anchorScroll();  
  });
});

and your link would look like this:

<a href="#/test#foo">Test/Foo</a>

How to remove focus from input field in jQuery?

Use .blur().

The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

$("#myInputID").blur(); 

HTTP 404 when accessing .svc file in IIS

I found these instructions on a blog post that indicated this step, which worked for me (Windows 8, 64-bit):

Make sure that in windows features, you have both WCF options under .Net framework are ticked. So go to Control Panel –> Programs and Features –> Turn Windows Features ON/Off –> Features –> Add Features –> .NET Framework X.X Features. Make sure that .Net framework says it is installed, and make sure that the WCF Activation node underneath it is selected (checkbox ticked) and both options under WCF Activation are also checked.
These are:
* HTTP Activation
* Non-HTTP Activation
Both options need to be selected (checked box ticked).

python: after installing anaconda, how to import pandas

  1. Another alternative is to use Pycharm IDE. For each project, you can set the Project Interpreter in Settings.

  2. For example, if anaconda is installed in /home/user/anaconda2/bin/python, you can select the Project Interpreter and set to this folder.

  3. Since the whole project is set to Anaconda's path, you can import any module which is packaged within Anaconda.

How to list all functions in a Python module?

dir(module) is the standard way when using a script or the standard interpreter, as mentioned in most answers.

However with an interactive python shell like IPython you can use tab-completion to get an overview of all objects defined in the module. This is much more convenient, than using a script and print to see what is defined in the module.

  • module.<tab> will show you all objects defined in the module (functions, classes and so on)
  • module.ClassX.<tab> will show you the methods and attributes of a class
  • module.function_xy? or module.ClassX.method_xy? will show you the docstring of that function / method
  • module.function_x?? or module.SomeClass.method_xy?? will show you the source code of the function / method.

Create tap-able "links" in the NSAttributedString of a UILabel?

I follow this version,

Swift 4:

import Foundation

class AELinkedClickableUILabel: UILabel {

    typealias YourCompletion = () -> Void

    var linkedRange: NSRange!
    var completion: YourCompletion?

    @objc func linkClicked(sender: UITapGestureRecognizer){

        if let completionBlock = completion {

            let textView = UITextView(frame: self.frame)
            textView.text = self.text
            textView.attributedText = self.attributedText
            let index = textView.layoutManager.characterIndex(for: sender.location(in: self),
                                                              in: textView.textContainer,
                                                              fractionOfDistanceBetweenInsertionPoints: nil)

            if linkedRange.lowerBound <= index && linkedRange.upperBound >= index {

                completionBlock()
            }
        }
    }

/**
 *  This method will be used to set an attributed text specifying the linked text with a
 *  handler when the link is clicked
 */
    public func setLinkedTextWithHandler(text:String, link: String, handler: @escaping ()->()) -> Bool {

        let attributextText = NSMutableAttributedString(string: text)
        let foundRange = attributextText.mutableString.range(of: link)

        if foundRange.location != NSNotFound {
            self.linkedRange = foundRange
            self.completion = handler
            attributextText.addAttribute(NSAttributedStringKey.link, value: text, range: foundRange)
            self.isUserInteractionEnabled = true
            self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(linkClicked(sender:))))
            return true
        }
        return false
    }
}

Call Example:

button.setLinkedTextWithHandler(text: "This website (stackoverflow.com) is awesome", link: "stackoverflow.com") 
{
    // show popup or open to link
}

How do I 'foreach' through a two-dimensional array?

Remember that a multi-dimensional array is like a table. You don't have an x element and a y element for each entry; you have a string at (for instance) table[1,2].

So, each entry is still only one string (in your example), it's just an entry at a specific x/y value. So, to get both entries at table[1, x], you'd do a nested for loop. Something like the following (not tested, but should be close)

for (int x = 0; x < table.Length; x++)
{
    for (int y = 0; y < table.Length; y += 2)
    {
        Console.WriteLine("{0} {1}", table[x, y], table[x, y + 1]);
    }
}

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

How do I include a path to libraries in g++

To specify a directory to search for (binary) libraries, you just use -L:

-L/data[...]/lib

To specify the actual library name, you use -l:

-lfoo  # (links libfoo.a or libfoo.so)

To specify a directory to search for include files (different from libraries!) you use -I:

-I/data[...]/lib

So I think what you want is something like

g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test

These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Run it under a different user name, using "runas" or by scheduling it under a different user in Windows Scheduled Tasks.

HttpWebRequest using Basic authentication

The spec can be read as "ISO-8859-1" or "undefined". Your choice. It's known that many servers use ISO-8859-1 (like it or not) and will fail when you send something else.

For more information and a proposal to fix the situation, see http://greenbytes.de/tech/webdav/draft-reschke-basicauth-enc-latest.html

How to stretch a table over multiple pages

You should \usepackage{longtable}.

How to make multiple divs display in one line but still retain width?

I used the property

display: table;

and

display: table-cell;

to achieve the same.Link to fiddle below shows 3 tables wrapped in divs and these divs are further wrapped in a parent div

<div id='content'>
   <div id='div-1'><!-- COntains table --></div>
   <div id='div-2'><!-- contains two more divs that require to be arranged one below other --></div>
</div>

Here is the jsfiddle: http://jsfiddle.net/vikikamath/QU6WP/1/ I thought this might be helpful to someone looking to set divs in same line without using display-inline

How to resolve conflicts in EGit

I know this is an older post, but I just got hit with a similar issue and was able to resolve it, so I thought I'd share.

(Update: As noted in the comments below, this answer was before the inclusion of the "git stash" feature to eGit.)

What I did was:

  1. Copy out the local copy of the conflicting file that may or may not have any changes from the version on the upstream.
  2. Within Eclipse, "Revert" the file to the version right before the conflict.
  3. Run a "Pull" from the remote repository, allowing all changes to be synced to the local work directory. This should clear the updates coming down to your filesystem, leaving only what you have left to push.
  4. Check the current version of the conflicting file in your work directory with the copy you copied out. If there are any differences, do a proper merge of the files and commit that version of the file in the work directory.
  5. Now "Push" your changes up.

Hope that helps.

counting number of directories in a specific directory

Get a count of only the directories in the current directory

echo */ | wc

you will get out put like 1 309 4594

2nd digit represents no. of directories.

or

tree -L 1 | tail -1

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
    this.parentElement.removeChild(this);
};

var table = document.getElementById('content');
table.appendChild(newTH);

Working example: http://jsfiddle.net/23tBM/

You can also just hide with this.style.display = 'none'.

How should I print types like off_t and size_t?

For Microsoft, the answer is different. VS2013 is largely C99 compliant but "[t]he hh, j, z, and t length prefixes are not supported." For size_t "that is, unsigned __int32 on 32-bit platforms, unsigned __int64 on 64-bit platforms" use prefix I (capital eye) with type specifier o, u, x, or X. See VS2013 Size specification

As for off_t, it is defined as long in VC\include\sys\types.h.

What are database constraints?

Constraints are nothing but the rules on the data. What data is valid and what is invalid can be defined using constraints. So, that integrity of data can be maintained. Following are the widely used constraints:

  1. Primary Key : which uniquely identifies the data . If this constraint has been specified for certain column then we can't enter duplicate data in that column
  2. Check : Such as NOT NULL . Here we can specify what data we can enter for that particular column and what is not expected for that column.
  3. Foreign key : Foreign key references to the row of other table. So that data referred in one table from another table is always available for the referencing table.

List of phone number country codes

I copy-pasted the whole pdf in a text editor and got something like:

...
31 Netherlands (Kingdom of the)  
32 Belgium  
33 France  
34 Spain  
350 Gibraltar  
351 Portugal  
352 Luxembourg  
353 Ireland  
354 Iceland
...

You could easily parse this to create a xml :)

Convert JSON string to array of JSON objects in Javascript

Append extra an [ and ] to the beginning and end of the string. This will make it an array. Then use eval() or some safe JSON serializer to serialize the string and make it a real JavaScript datatype.

You should use https://github.com/douglascrockford/JSON-js instead of eval(). eval is only if you're doing some quick debugging/testing.

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

The time complexity of ArrayList.clear() is O(n) and of removeAll is O(n^2).

So yes, ArrayList.clear is much faster.

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

I have Python 2 and Python 3 installed on my computer. For some strange reason I have in the sys.path of Python 3 also a path to the sitepackage library directory of Python2 when the re module is called. If I run Python 3 and import enum and print(enum.__file__) the system does not show this Python 2 path to site-packages. So a very rough and dirty hack is, to directly modify the module in which enum is imported (follow the traceback paths) and insert the following code just before importing enum:

import sys
for i, p in enumerate(sys.path):
    if "python27" in p.lower() or "python2.7" in p.lower(): sys.path.pop(i)
import enum

That solved my problem.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

you can do it like this:

cell[B1]: 0:04:58.727

cell[B2]: =FIND(".";B1)

cell[B3]: =LEFT(B1;B2-7)

cell[B4]: =MID(B1;11-8;2)

cell[B5]: =RIGHT(B1;6)

cell[B6]: =B3*3600000+B4*60000+B5

maybe you have to multiply B5 also with 1000.

=FIND(".";B1) is only necessary because you might have inputs like '0:04:58.727' or '10:04:58.727' with different length.

What is the difference between Jupyter Notebook and JupyterLab?

To answer your question directly:

The single most important difference between the two is that you should start using JupyterLab straight away, and that you should not worry about Jupyter Notebook at all. Because:

JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab

But you would also like to also know this:

Other posts have suggested that Jupyter Notebook (JN) could potentially be easier to use than JupyterLab (JL) for beginners. But I would have to disagree.

A great advantage with JL, and arguably one of the most important differences between JL and JN, is that you can more easily run a single line and even highlighted text. I prefer using a keyboard shortcut for this, and assigning shortcuts is pretty straight-forward.

And the fact that you can execute code in a Python console makes JL much more fun to work with. Other answers have already mentioned this, but JL can in some ways be considered a tool to run Notebooks and more. So the way I use JupyterLab is by having it set up with an .ipynb file, a file browser and a python console like this:

enter image description here

And now you have these tools at your disposal:

  1. View Files, running kernels, Commands, Notebook Tools, Open Tabs or Extension manager
  2. Run cells using, among other options, Ctrl+Enter
  3. Run single expression, line or highlighted text using menu options or keyboard shortcuts
  4. Run code directly in a console using Shift+Enter
  5. Inspect variables, dataframes or plots quickly and easily in a console without cluttering your notebook output.

Numpy where function multiple conditions

One interesting thing to point here; the usual way of using OR and AND too will work in this case, but with a small change. Instead of "and" and instead of "or", rather use Ampersand(&) and Pipe Operator(|) and it will work.

When we use 'and':

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) and (ar<6), 'yo', ar)

Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

When we use Ampersand(&):

ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) & (ar<6), 'yo', ar)

Output:
array(['3', 'yo', 'yo', '14', '2', 'yo', '3', '7'], dtype='<U11')

And this is same in the case when we are trying to apply multiple filters in case of pandas Dataframe. Now the reasoning behind this has to do something with Logical Operators and Bitwise Operators and for more understanding about same, I'd suggest to go through this answer or similar Q/A in stackoverflow.

UPDATE

A user asked, why is there a need for giving (ar>3) and (ar<6) inside the parenthesis. Well here's the thing. Before I start talking about what's happening here, one needs to know about Operator precedence in Python.

Similar to what BODMAS is about, python also gives precedence to what should be performed first. Items inside the parenthesis are performed first and then the bitwise operator comes to work. I'll show below what happens in both the cases when you do use and not use "(", ")".

Case1:

np.where( ar>3 & ar<6, 'yo', ar)
np.where( np.array([3,4,5,14,2,4,3,7])>3 & np.array([3,4,5,14,2,4,3,7])<6, 'yo', ar)

Since there are no brackets here, the bitwise operator(&) is getting confused here that what are you even asking it to get logical AND of, because in the operator precedence table if you see, & is given precedence over < or > operators. Here's the table from from lowest precedence to highest precedence.

enter image description here

It's not even performing the < and > operation and being asked to perform a logical AND operation. So that's why it gives that error.

One can check out the following link to learn more about: operator precedence

Now to Case 2:

If you do use the bracket, you clearly see what happens.

np.where( (ar>3) & (ar<6), 'yo', ar)
np.where( (array([False,  True,  True,  True, False,  True, False,  True])) & (array([ True,  True,  True, False,  True,  True,  True, False])), 'yo', ar)

Two arrays of True and False. And you can easily perform logical AND operation on them. Which gives you:

np.where( array([False,  True,  True, False, False,  True, False, False]),  'yo', ar)

And rest you know, np.where, for given cases, wherever True, assigns first value(i.e. here 'yo') and if False, the other(i.e. here, keeping the original).

That's all. I hope I explained the query well.

Creating a batch file, for simple javac and java command execution

The only other thing I would add is to make it a tad more flexible. Most times I'll have a trivial java file I want to run like - Main.java, Simple.java, Example.java, or Playground.java (you get the idea).

I use the following to strike off a javac and corresponding java.

@echo off
javac %~n1.java
java %~n1

The %~n1 gets the filename (sans extension) of the first argument passed to the batch file. So this way I can run it using tab completion and not have to worry about it working with either the .class or .java extension.

So both of the following will have the same result:

run.bat Main.class
and
run.bat Main.java

Doesn't 100% answer the original posters question, but I think it is a good next step/evolution for simple javac/java programs.

JavaScript/regex: Remove text between parentheses

var str = "Hello, this is Mike (example)";

alert(str.replace(/\s*\(.*?\)\s*/g, ''));

That'll also replace excess whitespace before and after the parentheses.

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

How to set conditional breakpoints in Visual Studio?

Set the breakpoint as you do normally, right click the break point and select condion option and sets your condition.

Copy mysql database from remote server to local computer

This answer is not remote server but local server. The logic should be the same. To copy and backup my local machine MAMP database to my local desktop machine folder, go to console then

mysqldump -h YourHostName -u YourUserNameHere -p YourDataBaseNameHere > DestinationPath/xxxwhatever.sql

In my case YourHostName was localhost. DestinationPath is the path to the download; you can drag and drop your desired destination folder and it will paste the path in.

Then password may be asked:

Enter password: xxxxxxxx

Getting last month's date in php

echo date('Y',strtotime("-1 year"));        //last year<br>
echo date('d',strtotime("-1 day"));     //last day<br>
echo date('m',strtotime("-1 month"));       //last month<br>

Cheap way to search a large text file for a string

I've had a go at putting together a multiprocessing example of file text searching. This is my first effort at using the multiprocessing module; and I'm a python n00b. Comments quite welcome. I'll have to wait until at work to test on really big files. It should be faster on multi core systems than single core searching. Bleagh! How do I stop the processes once the text has been found and reliably report line number?

import multiprocessing, os, time
NUMBER_OF_PROCESSES = multiprocessing.cpu_count()

def FindText( host, file_name, text):
    file_size = os.stat(file_name ).st_size 
    m1 = open(file_name, "r")

    #work out file size to divide up to farm out line counting

    chunk = (file_size / NUMBER_OF_PROCESSES ) + 1
    lines = 0
    line_found_at = -1

    seekStart = chunk * (host)
    seekEnd = chunk * (host+1)
    if seekEnd > file_size:
        seekEnd = file_size

    if host > 0:
        m1.seek( seekStart )
        m1.readline()

    line = m1.readline()

    while len(line) > 0:
        lines += 1
        if text in line:
            #found the line
            line_found_at = lines
            break
        if m1.tell() > seekEnd or len(line) == 0:
            break
        line = m1.readline()
    m1.close()
    return host,lines,line_found_at

# Function run by worker processes
def worker(input, output):
    for host,file_name,text in iter(input.get, 'STOP'):
        output.put(FindText( host,file_name,text ))

def main(file_name,text):
    t_start = time.time()
    # Create queues
    task_queue = multiprocessing.Queue()
    done_queue = multiprocessing.Queue()
    #submit file to open and text to find
    print 'Starting', NUMBER_OF_PROCESSES, 'searching workers'
    for h in range( NUMBER_OF_PROCESSES ):
        t = (h,file_name,text)
        task_queue.put(t)

    #Start worker processes
    for _i in range(NUMBER_OF_PROCESSES):
        multiprocessing.Process(target=worker, args=(task_queue, done_queue)).start()

    # Get and print results

    results = {}
    for _i in range(NUMBER_OF_PROCESSES):
        host,lines,line_found = done_queue.get()
        results[host] = (lines,line_found)

    # Tell child processes to stop
    for _i in range(NUMBER_OF_PROCESSES):
        task_queue.put('STOP')
#        print "Stopping Process #%s" % i

    total_lines = 0
    for h in range(NUMBER_OF_PROCESSES):
        if results[h][1] > -1:
            print text, 'Found at', total_lines + results[h][1], 'in', time.time() - t_start, 'seconds'
            break
        total_lines += results[h][0]

if __name__ == "__main__":
    main( file_name = 'testFile.txt', text = 'IPI1520' )

Getting a better understanding of callback functions in JavaScript

_x000D_
_x000D_
function checkCallback(cb) {_x000D_
  if (cb || cb != '') {_x000D_
    if (typeof window[cb] === 'undefined') alert('Callback function not found.');_x000D_
    else window[cb].call(this, Arg1, Arg2);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

<form action="" method="POST" enctype="multipart/form-data">
  Select image to upload:
  <input type="file"   name="file[]" multiple/>
  <input type="submit" name="submit" value="Upload Image" />
</form>

Using FOR Loop

<?php    
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    for ($x = 0; $x < count($_FILES['file']['name']); $x++) {               

      $file_name   = $_FILES['file']['name'][$x];
      $file_tmp    = $_FILES['file']['tmp_name'][$x];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }    
?>

Using FOREACH Loop

<?php
  $file_dir  = "uploads";    
  if (isset($_POST["submit"])) {

    foreach ($_FILES['file']['name'] as $key => $value) {                   

      $file_name   = $_FILES['file']['name'][$key];
      $file_tmp    = $_FILES['file']['tmp_name'][$key];

      /* location file save */
      $file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */

      if (move_uploaded_file($file_tmp, $file_target)) {                        
        echo "{$file_name} has been uploaded. <br />";                      
      } else {                      
        echo "Sorry, there was an error uploading {$file_name}.";                               
      }                 

    }               
  }
?>

How to count instances of character in SQL Column

Here's what I used in Oracle SQL to see if someone was passing a correctly formatted phone number:

WHERE REPLACE(TRANSLATE('555-555-1212','0123456789-','00000000000'),'0','') IS NULL AND
LENGTH(REPLACE(TRANSLATE('555-555-1212','0123456789','0000000000'),'0','')) = 2

The first part checks to see if the phone number has only numbers and the hyphen and the second part checks to see that the phone number has only two hyphens.

Update using LINQ to SQL

AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;

// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away

bootstrap popover not showing on top of all elements

This is Working for me

$().popover({container: 'body'})

Eloquent get only one column as an array

That can be done in short as:

Model::pluck('column')

where model is the Model such as User model & column as column name like id

if you do

User::pluck('id') // [1,2,3, ...]

& of course you can have any other clauses like where clause before pluck

How to replace a string in a SQL Server Table Column

all answers are great but I just want to give you a good example

select replace('this value from table', 'table',  'table but updated')

this SQL statement will replace the existence of the word "table" (second parameter) inside the given statement(first parameter) with the third parameter

the initial value is this value from table but after executing replace function it will be this value from table but updated

and here is a real example

UPDATE publication
SET doi = replace(doi, '10.7440/perifrasis', '10.25025/perifrasis')
WHERE doi like '10.7440/perifrasis%'

for example if we have this value

10.7440/perifrasis.2010.1.issue-1

it will become

10.25025/perifrasis.2010.1.issue-1

hope this gives you better visualization

How can I set focus on an element in an HTML form using JavaScript?

If your code is:

<input type="text" id="mytext"/>

And If you are using JQuery, You can use this too:

<script>
function setFocusToTextBox(){
    $("#mytext").focus();
}
</script>

Keep in mind that you must draw the input first $(document).ready()

Is there a max size for POST parameter content?

Yes there is 2MB max and it can be increased by configuration change like this. If your POST body is not in form of multipart file then you might need to add the max-http-post configuration for tomcat in the application yml configuration file.

Increase max size of each multipart file to 10MB and total payload size of 100MB max

 spring:
    servlet:
      multipart:max-file-size: 10MB
      multipart:max-request-size: 100MB
 

Setting max size of post requests which might just be the formdata in string format to ~10 MB

 server:
    tomcat:
        max-http-post-size: 100000000 # max-http-form-post-size: 10MB for new version

You might need to add this for the latest sprintboot version ->

server: tomcat: max-http-form-post-size: 10MB

Which MySQL data type to use for storing boolean values

You can use BOOL, BOOLEAN data type for storing boolean values.

These types are synonyms for TINYINT(1)

However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.

MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).

Further, read documentation

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

This is how you should be using mysql_fetch_assoc():

$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
    // Do stuff with $row
}

$result should be a resource. Even if the query returns no rows, $result is still a resource. The only time $result is a boolean value, is if there was an error when querying the database. In which case, you should find out what that error is by using mysql_error() and ensure that it can't happen. Then you don't have to hide from any errors.

You should always cover the base that errors may happen by doing:

if (!$result) {
    die(mysql_error());
}

At least then you'll be more likely to actually fix the error, rather than leave the users with a glaring ugly error in their face.

WinForms DataGridView font size

For changing particular single column font size use following statement

DataGridView.Columns[1].DefaultCellStyle.Font = new Font("Verdana", 16, FontStyle.Bold);

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

I just ran into this problem myself.

First, modify your code slightly:

var download = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                  +"<"+this.gamesave.tagName+">"
                  +this.xml.firstChild.innerHTML
                  +"</"+this.gamesave.tagName+">";

this.loader.src = "data:application/x-forcedownload;base64,"+
                  btoa(download);

Then use your favorite web inspector, put a breakpoint on the line of code that assigns this.loader.src, then execute this code:

for (var i = 0; i < download.length; i++) {
  if (download[i].charCodeAt(0) > 255) {
    console.warn('found character ' + download[i].charCodeAt(0) + ' "' + download[i] + '" at position ' + i);
  }
}

Depending on your application, replacing the characters that are out of range may or may not work, since you'll be modifying the data. See the note on MDN about unicode characters with the btoa method:

https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

PHP: merge two arrays while keeping keys instead of reindexing?

You can simply 'add' the arrays:

>> $a = array(1, 2, 3);
array (
  0 => 1,
  1 => 2,
  2 => 3,
)
>> $b = array("a" => 1, "b" => 2, "c" => 3)
array (
  'a' => 1,
  'b' => 2,
  'c' => 3,
)
>> $a + $b
array (
  0 => 1,
  1 => 2,
  2 => 3,
  'a' => 1,
  'b' => 2,
  'c' => 3,
)

HTML5 <video> element on Android

After much research, in many different devices, up to now, I've reached the simple conclusion that MP4 is much less supported than MOV format. So, I'm using MOV format, which is supported by all Android and Apple devices, on all browsers. I've detected weather the device is a mobile device or a desktop browser, and set the SRC accordingly:

if (IsMobile()) {
    $('#vid').attr('src', '/uploads/' + name + '.mov');
}
else {
    $('#vid').attr('src', '/uploads/' + name + '.webm');        
}

function IsMobile() {
    var isMobile = false; //initiate as false

    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
                || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;
    return isMobile;
}

How can I color Python logging output?

Now there is a released PyPi module for customizable colored logging output:

https://pypi.python.org/pypi/rainbow_logging_handler/

and

https://github.com/laysakura/rainbow_logging_handler

  • Supports Windows

  • Supports Django

  • Customizable colors

As this is distributed as a Python egg, it is very easy to install for any Python application.

List all column except for one in R

You can index and use a negative sign to drop the 3rd column:

data[,-3]

Or you can list only the first 2 columns:

data[,c("c1", "c2")]
data[,1:2]

Don't forget the comma and referencing data frames works like this: data[row,column]

Double value to round up in Java

double TotalPrice=90.98989898898;

  DecimalFormat format_2Places = new DecimalFormat("0.00");

    TotalPrice = Double.valueOf(format_2Places.format(TotalPrice));

log4j configuration via JVM argument(s)?

Relative Path is also ok:

java -Dlog4j.configuration=file:".\log4j.properties" -jar com.your-1.0-SNAPSHOT.jar

or

java -Dlog4j.configuration=file:".\log4j.xml" -jar com.your-1.0-SNAPSHOT.jar

How to remove empty cells in UITableView?

in the below method:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (([array count]*65) > [UIScreen mainScreen].bounds.size.height - 66)
    {
        Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [array count]*65)); 
    }
    else
    {
        Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 66);
    }
    return [array count];
}

here 65 is the height of the cell and 66 is the height of the navigation bar in UIViewController.

Javascript find json value

Just use the ES6 find() function in a functional way:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
_x000D_
_x000D_

or Lodash _.find:

_x000D_
_x000D_
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];

let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

jquery find class and get the value

You can get value of id,name or value in this way. class name my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

How to make a .jar out from an Android Studio project

  1. Go to Gradle tab in Android Studio , then select library project .

  2. Then go to Tasks

  3. Then go to Other

  4. Double click on bundleReleaseaar

You can find your .aar files under your_module/build/outputs/aar/your-release.aar

Here image

Passing data between controllers in Angular JS?

To improve the solution proposed by @Maxim using $broadcast, send data don't change

$rootScope.$broadcast('SOME_TAG', 'my variable');

but to listening data

$scope.$on('SOME_TAG', function(event, args) {
    console.log("My variable is", args);// args is value of your variable
})

How to manage exceptions thrown in filters in Spring?

I wanted to provide a solution based on the answer of @kopelitsa. The main differences being:

  1. Reusing the controller exception handling by using the HandlerExceptionResolver.
  2. Using Java config over XML config

First, you need to make sure, that you have a class that handles exceptions occurring in a regular RestController/Controller (a class annotated with @RestControllerAdvice or @ControllerAdvice and method(s) annotated with @ExceptionHandler). This handles your exceptions occurring in a controller. Here is an example using the RestControllerAdvice:

@RestControllerAdvice
public class ExceptionTranslator {

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorDTO processRuntimeException(RuntimeException e) {
        return createErrorDTO(HttpStatus.INTERNAL_SERVER_ERROR, "An internal server error occurred.", e);
    }

    private ErrorDTO createErrorDTO(HttpStatus status, String message, Exception e) {
        (...)
    }
}

To reuse this behavior in the Spring Security filter chain, you need to define a Filter and hook it into your security configuration. The filter needs to redirect the exception to the above defined exception handling. Here is an example:

@Component
public class FilterChainExceptionHandler extends OncePerRequestFilter {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.error("Spring Security Filter Chain Exception:", e);
            resolver.resolveException(request, response, null, e);
        }
    }
}

The created filter then needs to be added to the SecurityConfiguration. You need to hook it into the chain very early, because all preceding filter's exceptions won't be caught. In my case, it was reasonable to add it before the LogoutFilter. See the default filter chain and its order in the official docs. Here is an example:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private FilterChainExceptionHandler filterChainExceptionHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(filterChainExceptionHandler, LogoutFilter.class)
            (...)
    }

}

How to insert multiple rows from array using CodeIgniter framework?

I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl), table-field ($insertFieldsArr) against your inserting data, data array ($arr).

insert_batch('table',array('field1','field2'),$dataArray);

    function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array(); 
    foreach( $arr as $row ) {
        $strVals='';
        $cnt=0;
        foreach($insertFieldsArr as $key=>$val){
            if(is_array($row)){
                $strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
            }
            else{
                $strVals.="'".mysql_real_escape_string($row).'\',';
            }
            $cnt++;
        }
        $strVals=rtrim($strVals,',');
        $sql[] = '('.$strVals.')';
    }

    $fields=implode(',',$insertFieldsArr);
    mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}

Display label text with line breaks in c#

Also you can use the following

@"Italian naval...<br><br>"+

Above code you can achieve double space. If you want single one means you simply use
.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

http://www.lfd.uci.edu/~gohlke/pythonlibs/

press contrl F type Pillow-2.4.0.win-amd64-py3.3.exe

then click and downloadd the 64 bit version

Pillow is a replacement for PIL, the Python Image Library, which provides image processing functionality and supports many file formats. Note: use from PIL import Image instead of import Image. PIL-1.1.7.win-amd64-py2.5.exe PIL-1.1.7.win32-py2.5.exe Pillow-2.4.0.win-amd64-py2.6.exe Pillow-2.4.0.win-amd64-py2.7.exe Pillow-2.4.0.win-amd64-py3.2.exe Pillow-2.4.0.win-amd64-py3.3.exe Pillow-2.4.0.win-amd64-py3.4.exe Pillow-2.4.0.win32-py2.6.exe Pillow-2.4.0.win32-py2.7.exe Pillow-2.4.0.win32-py3.2.exe Pillow-2.4.0.win32-py3.3.exe Pillow-2.4.0.win32-py3.4.exe

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

Add two numbers and display result in textbox with Javascript

Here a working fiddle: http://jsfiddle.net/sjh36otu/

        function add_number() {

            var first_number = parseInt(document.getElementById("Text1").value);
            var second_number = parseInt(document.getElementById("Text2").value);
            var result = first_number + second_number;

            document.getElementById("txtresult").value = result;
        }

Javascript : Send JSON Object with Ajax?

Adding Json.stringfy around the json that fixed the issue

Return multiple values from a function, sub or type?

you can return 2 or more values to a function in VBA or any other visual basic stuff but you need to use the pointer method called Byref. See my example below. I will make a function to add and subtract 2 values say 5,6

sub Macro1
    ' now you call the function this way
    dim o1 as integer, o2 as integer
    AddSubtract 5, 6, o1, o2
    msgbox o2
    msgbox o1
end sub


function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
    sum = a + b
    dif = b - 1
end function

How to detect a mobile device with JavaScript?

A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:

if( screen.width <= 480 ) {
    location.href = '/mobile.html';
}

The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.

The only exception here are tablet pc's like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.

How can I tell when a MySQL table was last updated?

Just grab the file date modified from file system. In my language that is:

 tbl_updated = file.update_time(
        "C:\ProgramData\MySQL\MySQL Server 5.5\data\mydb\person.frm")

Output:

1/25/2013 06:04:10 AM

Using Excel OleDb to get sheet names IN SHEET ORDER

As per MSDN, In a case of spreadsheets inside of Excel it might not work because Excel files are not real databases. So you will be not able to get the sheets name in order of their visualization in workbook.

Code to get sheets name as per their visual appearance using interop:

Add reference to Microsoft Excel 12.0 Object Library.

Following code will give the sheets name in the actual order stored in workbook, not the sorted name.

Sample Code:

using Microsoft.Office.Interop.Excel;

string filename = "C:\\romil.xlsx";

object missing = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

Microsoft.Office.Interop.Excel.Workbook wb =excel.Workbooks.Open(filename,  missing,  missing,  missing,  missing,missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing);

ArrayList sheetname = new ArrayList();

foreach (Microsoft.Office.Interop.Excel.Worksheet  sheet in wb.Sheets)
{
    sheetname.Add(sheet.Name);
}

Cannot open Windows.h in Microsoft Visual Studio

The right combination of Windows SDK Version and Platform Toolset needs to be selected Depends of course what toolset you have currently installed

SDK Version and Platform Toolset

How to reset Jenkins security settings from the command line?

The answer on modifying was correct. Yet, I think it should be mentioned that /var/lib/jenkins/config.xml looks something like this if you have activated "Project-based Matrix Authorization Strategy". Deleting /var/lib/jenkins/config.xml and restarting jenkins also does the trick. I also deleted the users in /var/lib/jenkins/users to start from scratch.

<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
    <permission>hudson.model.Computer.Configure:jenkins-admin</permission>
    <permission>hudson.model.Computer.Connect:jenkins-admin</permission>
    <permission>hudson.model.Computer.Create:jenkins-admin</permission>
    <permission>hudson.model.Computer.Delete:jenkins-admin</permission>
    <permission>hudson.model.Computer.Disconnect:jenkins-admin</permission>
    <!-- if this is missing for your user and it is the only one, bad luck -->
    <permission>hudson.model.Hudson.Administer:jenkins-admin</permission>
    <permission>hudson.model.Hudson.Read:jenkins-admin</permission>
    <permission>hudson.model.Hudson.RunScripts:jenkins-admin</permission>
    <permission>hudson.model.Item.Build:jenkins-admin</permission>
    <permission>hudson.model.Item.Cancel:jenkins-admin</permission>
    <permission>hudson.model.Item.Configure:jenkins-admin</permission>
    <permission>hudson.model.Item.Create:jenkins-admin</permission>
    <permission>hudson.model.Item.Delete:jenkins-admin</permission>
    <permission>hudson.model.Item.Discover:jenkins-admin</permission>
    <permission>hudson.model.Item.Read:jenkins-admin</permission>
    <permission>hudson.model.Item.Workspace:jenkins-admin</permission>
    <permission>hudson.model.View.Configure:jenkins-admin</permission>
    <permission>hudson.model.View.Create:jenkins-admin</permission>
    <permission>hudson.model.View.Delete:jenkins-admin</permission>
    <permission>hudson.model.View.Read:jenkins-admin</permission>
  </authorizationStrategy>

Apply CSS rules to a nested class inside a div

If you need to target multiple classes use:

#main_text .title, #main_text .title2 {
  /* Properties */
}

How to convert "0" and "1" to false and true

My solution (vb.net):

Private Function ConvertToBoolean(p1 As Object) As Boolean
    If p1 Is Nothing Then Return False
    If IsDBNull(p1) Then Return False
    If p1.ToString = "1" Then Return True
    If p1.ToString.ToLower = "true" Then Return True
    Return False
End Function

In PowerShell, how do I test whether or not a specific variable exists in global scope?

$myvar = if ($env:variable) { $env:variable } else { "default_value" } 

How to remove an HTML element using Javascript?

Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.

How do I center a window onscreen in C#?

In Windows Forms:

this.StartPosition = FormStartPosition.CenterScreen;

In WPF:

this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

That's all you have to do...

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

add onclick function to a submit button

I have this code:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() {     _x000D_
    document.getElementById("boton").style.display = 'none';_x000D_
    document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando...";     _x000D_
    return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio"  /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
   <input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

If I understand your question correctly, I've made a fiddle that has this working correctly. This issue is with how you're assigning the event handlers and as others have said you have over riding event handlers. The current jQuery best practice is to use on() to register event handlers. Here's a link to the jQuery docs about on: link

Your original solution was pretty close but the way you added the event handlers is a bit confusing. It's considered best practice to not add events to HTML elements. I recommend reading up on Unobstrusive JavaScript.

Here's the JavaScript code. I added a counter variable so you can see that it is working correctly.

$('#answer').on('click', function() {
  feedback('hey there');
});

var counter = 0;

function feedback(message) {

  $('#feedback').remove();

  $('.answers').append('<div id="feedback">' + message + ' ' + counter + '</div>');

  counter++;    
}

Can you remove elements from a std::list while iterating through it?

You need to do the combination of Kristo's answer and MSN's:

// Note: Using the pre-increment operator is preferred for iterators because
//       there can be a performance gain.
//
// Note: As long as you are iterating from beginning to end, without inserting
//       along the way you can safely save end once; otherwise get it at the
//       top of each loop.

std::list< item * >::iterator iter = items.begin();
std::list< item * >::iterator end  = items.end();

while (iter != end)
{
    item * pItem = *iter;

    if (pItem->update() == true)
    {
        other_code_involving(pItem);
        ++iter;
    }
    else
    {
        // BTW, who is deleting pItem, a.k.a. (*iter)?
        iter = items.erase(iter);
    }
}

Of course, the most efficient and SuperCool® STL savy thing would be something like this:

// This implementation of update executes other_code_involving(Item *) if
// this instance needs updating.
//
// This method returns true if this still needs future updates.
//
bool Item::update(void)
{
    if (m_needsUpdates == true)
    {
        m_needsUpdates = other_code_involving(this);
    }

    return (m_needsUpdates);
}

// This call does everything the previous loop did!!! (Including the fact
// that it isn't deleting the items that are erased!)
items.remove_if(std::not1(std::mem_fun(&Item::update)));

Select top 2 rows in Hive

select * from employee_list order by salary desc limit 2;

Define a struct inside a class in C++

declare class & nested struct probably in some header file

class C {
    // struct will be private without `public:` keyword
    struct S {
        // members will be public without `private:` keyword
        int sa;
        void func();
    };
    void func(S s);
};

if you want to separate the implementation/definition, maybe in some CPP file

void C::func(S s) {
    // implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
    // implementation here
}

if you want to inline the implementation, other answers will do fine.

Make one div visible and another invisible

Making it invisible with visibility still makes it use up space. Rather try set the display to none to make it invisible, and then set the display to block to make it visible.

Get text from DataGridView selected cells

In this specific case, the ToString() will return the name of the object retruned by the SelectedCell Property.( a collection of the currently selected cells).

This behavior occurs when an object has no specific implenetation for the ToString() methods.

in our case, all you have to do is to iterate the collection of the cells and to accumulate its values to a string. then push this string to the TextBox.

have a look here how to implement the iteration:

msdn

How can I increase the size of a bootstrap button?

bootstrap comes with clas btn-lg http://getbootstrap.com/components/#btn-dropdowns-sizing

<div class="btn btn-default btn-block">
  Active
</div>

but if you want to have the button of the width of your column / container add btn-block

<div class="btn btn-default btn-lg">
      Active
    </div>

However this will expand to 100% so make surt ethat you will wrap your button in certain amount of columns e.g. then you know its always stays 3 columns until xs screen

<div class="col-sm-3">
             <div class="btn btn-default btn-block">
          Active
            </div>
        </div>

Which exception should I raise on bad/illegal argument combinations in Python?

I've mostly just seen the builtin ValueError used in this situation.

IDEA: javac: source release 1.7 requires target release 1.7

Make sure right depency is selected. File > Project Structure

Select your project and navigate to Dependencies tab. Select right dependancy from dropdown or create new.

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

Returning JSON from a PHP Script

<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>

check if array is empty (vba excel)

this worked for me:

Private Function arrIsEmpty(arr as variant)
    On Error Resume Next
    arrIsEmpty = False
    arrIsEmpty = IsNumeric(UBound(arr))
End Function

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

git reset --soft origin/my_remote_tracking_branch

This way you will not loose your local changes

Splitting a C++ std::string using tokens, e.g. ";"

You could use a string stream and read the elements into the vector.

Here are many different examples...

A copy of one of the examples:

std::vector<std::string> split(const std::string& s, char seperator)
{
   std::vector<std::string> output;

    std::string::size_type prev_pos = 0, pos = 0;

    while((pos = s.find(seperator, pos)) != std::string::npos)
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );

        output.push_back(substring);

        prev_pos = ++pos;
    }

    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word

    return output;
}

Using UPDATE in stored procedure with optional parameters

Try this.

ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
    @id uniqueidentifier,
    @ordering smallint = NULL,
    @title nvarchar(20) = NULL,
    @content text = NULL
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE tbl_ClientNotes
    SET ordering=ISNULL(@ordering,ordering), 
        title=ISNULL(@title,title), 
        content=ISNULL(@content, content)
    WHERE id=@id
END

It might also be worth adding an extra part to the WHERE clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.

WHERE id=@id AND (@ordering IS NOT NULL OR
                  @title IS NOT NULL OR
                  @content IS NOT NULL)

Spaces cause split in path with PowerShell

Just put ${yourpathtofile/folder}

PowerShell does not count spaces; to tell PowerShell to consider the whole path including spaces, add your path in between ${ & }.

What is The difference between ListBox and ListView

A ListView let you define a set of views for it and gives you a native way (WPF binding support) to control the display of ListView by using defined views.

Example:

XAML

<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave">
        <ListView.Resources>
            <GridView x:Key="one">
                <GridViewColumn Header="ID" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding id}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
            <GridView x:Key="two">                    
                <GridViewColumn Header="Name" >
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding name}" />
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.Resources>
        <ListView.Style>
            <Style TargetType="ListView">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ViewType}" Value="1">
                        <Setter Property="View" Value="{StaticResource one}" />
                    </DataTrigger>
                </Style.Triggers>
                <Setter Property="View" Value="{StaticResource two}" />
            </Style>
        </ListView.Style>  

Code Behind:

private int viewType;

public int ViewType
{
    get { return viewType; }
    set 
    { 
        viewType = value;
        UpdateProperty("ViewType");
    }
}        

private void listv_MouseEnter(object sender, MouseEventArgs e)
{
    ViewType = 1;
}

private void listv_MouseLeave(object sender, MouseEventArgs e)
{
    ViewType = 2;
}

OUTPUT:

Normal View: View 2 in above XAML

Normal

MouseOver View: View 1 in above XAML

Mouse Over

If you try to achieve above in a ListBox, probably you'll end up writing a lot more code forControlTempalate/ItemTemplate of ListBox.

Is there a command to list all Unix group names?

To list all local groups which have users assigned to them, use this command:

cut -d: -f1 /etc/group | sort

For more info- > Unix groups, Cut command, sort command

Version of Apache installed on a Debian machine

I am using Red Hat Linux and the following command works:

httpd -V

Definitive way to trigger keypress events with jQuery

Slightly more concise now with jQuery 1.6+:

var e = jQuery.Event( 'keydown', { which: $.ui.keyCode.ENTER } );

$('input').trigger(e);

(If you're not using jQuery UI, sub in the appropriate keycode instead.)

Use of "global" keyword in Python

While you can access global variables without the global keyword, if you want to modify them you have to use the global keyword. For example:

foo = 1
def test():
    foo = 2 # new local foo

def blub():
    global foo
    foo = 3 # changes the value of the global foo

In your case, you're just accessing the list sub.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Javascript - get array of dates between 2 dates

Here's a canned method that will accept Moment dates or strings or a mixture as inputs and generate an array of dates as Moment dates. If you don't want Moment dates as output then change what the map() method returns.

const moment = require('moment');

// ...

/**
 * @param {string|import('moment').Moment} start
 * @param {string|import('moment').Moment} end
 * @returns {import('moment').Moment[]}
 */
const getDateRange = (start, end) => {
  const s = moment.isMoment(start) ? start : moment(start);
  const e = moment.isMoment(end) ? end : moment(end);
  return [...Array(1 + e.diff(s, 'days')).keys()].map(n => moment(s).add(n, 'days'));
};

Error: Segmentation fault (core dumped)

There is one more reason for such failure which I came to know when mine failed

  • You might be working with a lot of data and your RAM is full

This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.

Get all parameters from JSP page

The fastest way should be:

<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
    if (entry.getKey().startsWith("question")) {
        String[] values = entry.getValue();
        // etc.

Note that you can't do:

for (Map.Entry<String, String[]> entry : 
     request.getParameterMap().entrySet()) { // WRONG!

for reasons explained here.

Import mysql DB with XAMPP in command LINE

It works:

mysql -u root -p db_name < "C:\folder_name\db_name.sql"

C:\ is for example

Application_Start not firing?

If you are using the System.Diagnostics.Debugger.Break(); workaround (which I think is just fine for temporary use) and it's "just not working" on your Windows 8 Machine. The reason is a bug in Visual Studio's "Just in time debugging".

The fix is as follows is to fix the key for the "Visual Studio Just-In-Time Debugger"

Open regedit and go to HKEY_CLASSES_ROOT\AppID{E62A7A31-6025-408E-87F6-81AEB0DC9347} for the ‘AppIDFlags’ registry value, set the flag to 0x8

More info here: http://connect.microsoft.com/VisualStudio/feedback/details/770786/just-in-time-debugging-operation-attempted-is-not-supported

Using "If cell contains" in VBA excel

Dim celltxt As String
Range("C6").Select
Selection.End(xlToRight).Select
celltxt = Selection.Text
If InStr(1, celltext, "TOTAL") > 0 Then
Range("C7").Select 
Selection.End(xlToRight).Select
Selection.Value = "-"
End If

You declared "celltxt" and used "celltext" in the instr.

How do I add an "Add to Favorites" button or link on my website?

  if (window.sidebar) { // Mozilla Firefox Bookmark
     window.sidebar.addPanel(document.title,location.href,"");

It adds the bookmark but in the sidebar.

Display two fields side by side in a Bootstrap Form

The problem is that .form-control class renders like a DIV element which according to the normal-flow-of-the-page renders on a new line.

One way of fixing issues like this is to use display:inline property. So, create a custom CSS class with display:inline and attach it to your component with a .form-control class. You have to have a width for your component as well.

There are other ways of handling this issue (like arranging your form-control components inside any of the .col classes), but the easiest way is to just make your .form-control an inline element (the way a span would render)

How get total sum from input box values using Javascript?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
  //iterate through each textboxes and add keyup_x000D_
  //handler to trigger sum event_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   $(this).keyup(function(){_x000D_
    calculateSum();_x000D_
   });_x000D_
  });_x000D_
_x000D_
 });_x000D_
_x000D_
 function calculateSum() {_x000D_
_x000D_
  var sum = 0;_x000D_
  //iterate through each textboxes and add the values_x000D_
  $(".txt").each(function() {_x000D_
_x000D_
   //add only if the value is number_x000D_
   if(!isNaN(this.value) && this.value.length!=0) {_x000D_
    sum += parseFloat(this.value);_x000D_
   }_x000D_
_x000D_
  });_x000D_
  //.toFixed() method will roundoff the final sum to 2 decimal places_x000D_
  $("#sum").html(sum.toFixed(2));_x000D_
 }
_x000D_
body {_x000D_
    font-family: sans-serif;_x000D_
   }_x000D_
   #summation {_x000D_
    font-size: 18px;_x000D_
    font-weight: bold;_x000D_
    color:#174C68;_x000D_
   }_x000D_
   .txt {_x000D_
    background-color: #FEFFB0;_x000D_
    font-weight: bold;_x000D_
    text-align: right;_x000D_
   }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<table width="300px" border="1" style="border-collapse:collapse;background-color:#E8DCFF">_x000D_
 <tr>_x000D_
  <td width="40px">1</td>_x000D_
  <td>Butter</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>2</td>_x000D_
  <td>Cheese</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>3</td>_x000D_
  <td>Eggs</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>4</td>_x000D_
  <td>Milk</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>5</td>_x000D_
  <td>Bread</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr>_x000D_
  <td>6</td>_x000D_
  <td>Soap</td>_x000D_
  <td><input class="txt" type="text" name="txt"/></td>_x000D_
 </tr>_x000D_
 <tr id="summation">_x000D_
  <td>&nbsp;</td>_x000D_
  <td align="right">Sum :</td>_x000D_
  <td align="center"><span id="sum">0</span></td>_x000D_
 </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to sum columns in a dataTable?

 for (int i=0;i<=dtB.Columns.Count-1;i++)
 {
   array(0, i) = dtB.Compute("SUM([" & dtB.Columns(i).ColumnName & "])", "")                   
 }

Duplicate AssemblyVersion Attribute

Edit you AssemblyInfo.cs and #if !NETCOREAPP3_0 ... #endif

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

#if !NETCOREAPP3_0  

[assembly: AssemblyTitle(".Net Core Testing")]
[assembly: AssemblyDescription(".Net Core")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(".Net Core")]
[assembly: AssemblyCopyright("Copyright ©")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("000b119c-2445-4977-8604-d7a736003d34")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

#endif

Is there a JavaScript function that can pad a string to get to a determined length?

Using the ECMAScript 6 method String#repeat, a pad function is as simple as:

String.prototype.padLeft = function(char, length) { 
    return char.repeat(Math.max(0, length - this.length)) + this;
}

String#repeat is currently supported in Firefox and Chrome only. for other implementation, one might consider the following simple polyfill:

String.prototype.repeat = String.prototype.repeat || function(n){ 
    return n<=1 ? this : (this + this.repeat(n-1)); 
}

What is Vim recording and how can it be disabled?

As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.

get current page from url

A simple function like below will help :

public string GetCurrentPageName() 
{ 
    string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath); 
    string sRet = oInfo.Name; 
    return sRet; 
} 

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

For tables you must loop that:

for tbl in `psql -qAt -c "select tablename from pg_tables where schemaname = 'public';" YOUR_DB` ; do  psql -U postgres -c "alter table \"$tbl\" owner to NEW_USER" YOUR_DB ; done

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get