Programs & Examples On #Overlapping

The overlapping tag is used to describe elements on a webpage, absolutely positioned with CSS so they overlap each other.

How do I use Safe Area Layout programmatically?

For those of you who use SnapKit, just like me, the solution is anchoring your constraints to view.safeAreaLayoutGuide like so:

yourView.snp.makeConstraints { (make) in
    if #available(iOS 11.0, *) {
        //Bottom guide
        make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottomMargin)
        //Top guide
        make.top.equalTo(view.safeAreaLayoutGuide.snp.topMargin)
        //Leading guide
        make.leading.equalTo(view.safeAreaLayoutGuide.snp.leadingMargin)
        //Trailing guide
        make.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailingMargin)

     } else {
        make.edges.equalToSuperview()
     }
}

CSS Grid Layout not working in IE11 even with prefixes

IE11 uses an older version of the Grid specification.

The properties you are using don't exist in the older grid spec. Using prefixes makes no difference.

Here are three problems I see right off the bat.


repeat()

The repeat() function doesn't exist in the older spec, so it isn't supported by IE11.

You need to use the correct syntax, which is covered in another answer to this post, or declare all row and column lengths.

Instead of:

.grid {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: repeat( 4, 1fr );
      grid-template-columns: repeat( 4, 1fr );
  -ms-grid-rows: repeat( 4, 270px );
      grid-template-rows: repeat( 4, 270px );
  grid-gap: 30px;
}

Use:

.grid {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 1fr 1fr 1fr 1fr;             /* adjusted */
      grid-template-columns:  repeat( 4, 1fr );
  -ms-grid-rows: 270px 270px 270px 270px;        /* adjusted */
      grid-template-rows: repeat( 4, 270px );
  grid-gap: 30px;
}

Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-repeating-columns-and-rows


span

The span keyword doesn't exist in the older spec, so it isn't supported by IE11. You'll have to use the equivalent properties for these browsers.

Instead of:

.grid .grid-item.height-2x {
  -ms-grid-row: span 2;
      grid-row: span 2;
}
.grid .grid-item.width-2x {
  -ms-grid-column: span 2;
      grid-column: span 2;
}

Use:

.grid .grid-item.height-2x {
  -ms-grid-row-span: 2;          /* adjusted */
      grid-row: span 2;
}
.grid .grid-item.width-2x {
  -ms-grid-column-span: 2;       /* adjusted */
      grid-column: span 2;
}

Older spec reference: https://www.w3.org/TR/2011/WD-css3-grid-layout-20110407/#grid-row-span-and-grid-column-span


grid-gap

The grid-gap property, as well as its long-hand forms grid-column-gap and grid-row-gap, don't exist in the older spec, so they aren't supported by IE11. You'll have to find another way to separate the boxes. I haven't read the entire older spec, so there may be a method. Otherwise, try margins.


grid item auto placement

There was some discussion in the old spec about grid item auto placement, but the feature was never implemented in IE11. (Auto placement of grid items is now standard in current browsers).

So unless you specifically define the placement of grid items, they will stack in cell 1,1.

Use the -ms-grid-row and -ms-grid-column properties.

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I ran into this problem because I had OpenVPN running. As soon as I killed OpenVPN, docker-compose up fired right up, and the error disappeared.

How to prevent "The play() request was interrupted by a call to pause()" error?

This piece of code fixed for me!

Modified code of @JohnnyCoder

HTML:

 <video id="captureVideoId" muted width="1280" height="768"></video>
                <video controls id="recordedVideoId" muted width="1280" 
 style="display:none;" height="768"></video>

JS:

  var recordedVideo = document.querySelector('video#recordedVideoId');
  var superBuffer = new Blob(recordedBlobs, { type: 'video/webm' });
  recordedVideo.src = window.URL.createObjectURL(superBuffer);
  // workaround for non-seekable video taken from
  // https://bugs.chromium.org/p/chromium/issues/detail?id=642012#c23
  recordedVideo.addEventListener('loadedmetadata', function () {
    if (recordedVideo.duration === Infinity) {
        recordedVideo.currentTime = 1e101;
        recordedVideo.ontimeupdate = function () {
            recordedVideo.currentTime = 0;
            recordedVideo.ontimeupdate = function () {
                delete recordedVideo.ontimeupdate;
                var isPlaying = recordedVideo.currentTime > 0 && 
     !recordedVideo.paused && !recordedVideo.ended && 
      recordedVideo.readyState > 2;
                if (isPlaying) {
                    recordedVideo.play();
                }
            };
        };
       }
      });

Toolbar overlapping below status bar

For me, the problem was that I copied something from an example and used

<item name="android:windowTranslucentStatus">true</item>

just removing this fixed my problem.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

you should also check if you are connecting via proxy. If there is a proxy set it up using File > Settings > Appearance and Behavior > System settings > HTTP Proxy

What is the order of precedence for CSS?

There are several rules ( applied in this order ) :

  1. inline css ( html style attribute ) overrides css rules in style tag and css file
  2. a more specific selector takes precedence over a less specific one
  3. rules that appear later in the code override earlier rules if both have the same specificity.
  4. A css rule with !important always takes precedence.

In your case its rule 3 that applies.

Specificity for single selectors from highest to lowest:

  • ids (example: #main selects <div id="main">)
  • classes (ex.: .myclass), attribute selectors (ex.: [href=^https:]) and pseudo-classes (ex.: :hover)
  • elements (ex.: div) and pseudo-elements (ex.: ::before)

To compare the specificity of two combined selectors, compare the number of occurences of single selectors of each of the specificity groups above.

Example: compare #nav ul li a:hover to #nav ul li.active a::after

  • count the number of id selectors: there is one for each (#nav)
  • count the number of class selectors: there is one for each (:hover and .active)
  • count the number of element selectors: there are 3 (ul li a) for the first and 4 for the second (ul li a ::after), thus the second combined selector is more specific.

A good article about css selector specificity.

iOS 7 status bar overlapping UI

Write the following code inside AppDelegate.m in didFinishLaunchingWithOptions event (exactly before its last line of code "return YES;" ) :

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) 
{
    [application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}

I'll wait for your feedback! :)

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

I did this:

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>AutoDealer</title>
        <style>
        .container{
            width: 860px;
            height: 1074px;
            margin-right: auto;
            margin-left: auto;
            border: 1px solid red;

        }
        .nav{

        }
        .wrapper{
            display: block;
            overflow: hidden;
            border: 1px solid green;
        }
       .otherWrapper{
            display: block;
            overflow: hidden;
            border: 1px solid green;
            float:left;
        }
    .left{
        width: 399px;
        float: left;
        background-color: pink;
    }
            .bottom{
        clear: both;
        width: 399px;
        background-color: yellow;



    }
    .right{
        height:350px;
        width: 449px;
        overflow: hidden;
        background-color: blue;
        overflow: hidden;
        float:right;
    }

    </style>
</head>
<body>
    <div class="container">
        <div class="nav"></div>
        <div class="wrapper">
        <div class="otherWrapper">
            <div class="left">
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
            </div>
             <div class="bottom">
                <p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
             </div>

             <div class="right">
                <p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
             </div>
        </div>
    </div>
</body>

So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.

iOS 7 status bar back to iOS 6 default style in iPhone app?

Updates on 19th Sep 2013:

fixed scaling bugs by adding self.window.bounds = CGRectMake(0, 20, self.window.frame.size.width, self.window.frame.size.height);

corrected typos in the NSNotificationCenter statement


Updates on 12th Sep 2013:

corrected UIViewControllerBasedStatusBarAppearance to NO

added a solution for apps with screen rotation

added an approach to change the background color of the status bar.


There is, apparently, no way to revert the iOS7 status bar back to how it works in iOS6.

However, we can always write some codes and turn the status bar into iOS6-like, and this is the shortest way I can come up with:

  1. Set UIViewControllerBasedStatusBarAppearance to NO in info.plist (To opt out of having view controllers adjust the status bar style so that we can set the status bar style by using the UIApplicationstatusBarStyle method.)

  2. In AppDelegate's application:didFinishLaunchingWithOptions, call

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
        self.window.clipsToBounds =YES;
        self.window.frame =  CGRectMake(0,20,self.window.frame.size.width,self.window.frame.size.height-20);
    
        //Added on 19th Sep 2013
        self.window.bounds = CGRectMake(0, 20, self.window.frame.size.width, self.window.frame.size.height);
    }
    return YES;
    


in order to:

  1. Check if it's iOS 7.

  2. Set status bar's content to be white, as opposed to UIStatusBarStyleDefault.

  3. Avoid subviews whose frames extend beyond the visible bounds from showing up (for views animating into the main view from top).

  4. Create the illusion that the status bar takes up space like how it is in iOS 6 by shifting and resizing the app's window frame.


For apps with screen rotation,

use NSNotificationCenter to detect orientation changes by adding

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidChangeStatusBarOrientation:)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];

in if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) and create a new method in AppDelegate:

- (void)applicationDidChangeStatusBarOrientation:(NSNotification *)notification
{
    int a = [[notification.userInfo objectForKey: UIApplicationStatusBarOrientationUserInfoKey] intValue];
    int w = [[UIScreen mainScreen] bounds].size.width;
    int h = [[UIScreen mainScreen] bounds].size.height;
    switch(a){
        case 4:
            self.window.frame =  CGRectMake(0,20,w,h);
            break;
        case 3:
            self.window.frame =  CGRectMake(-20,0,w-20,h+20);
            break;
        case 2:
            self.window.frame =  CGRectMake(0,-20,w,h);
            break;
        case 1:
           self.window.frame =  CGRectMake(20,0,w-20,h+20);
    }
}

So that when orientation changes, it will trigger a switch statement to detect app's screen orientation (Portrait, Upside Down, Landscape Left, or Landscape Right) and change the app's window frame respectively to create the iOS 6 status bar illusion.


To change the background color of your status bar:

Add

 @property (retain, nonatomic) UIWindow *background;

in AppDelegate.h to make background a property in your class and prevent ARC from deallocating it. (You don't have to do it if you are not using ARC.)

After that you just need to create the UIWindow in if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1):

background = [[UIWindow alloc] initWithFrame: CGRectMake(0, 0, self.window.frame.size.width, 20)];
background.backgroundColor =[UIColor redColor];
[background setHidden:NO];

Don't forget to @synthesize background; after @implementation AppDelegate!

Changing datagridview cell color dynamically

If you want every cell in the grid to have the same background color, you can just do this:

dataGridView1.DefaultCellStyle.BackColor = Color.Green;

What is the id( ) function used for?

I'm a little bit late and i will talk about Python3. To understand what id() is and how it (and Python) works, consider next example:

>>> x=1000
>>> y=1000
>>> id(x)==id(y)
False
>>> id(x)
4312240944
>>> id(y)
4312240912
>>> id(1000)
4312241104
>>> x=1000
>>> id(x)
4312241104
>>> y=1000
>>> id(y)
4312241200

You need to think about everything on the right side as objects. Every time you make assignment - you create new object and that means new id. In the middle you can see a "wild" object which is created only for function - id(1000). So, it's lifetime is only for that line of code. If you check the next line - you see that when we create new variable x, it has the same id as that wild object. Pretty much it works like memory address.

Algorithm to detect overlapping periods

Check this simple method (It is recommended to put This method in your dateUtility

public static bool isOverlapDates(DateTime dtStartA, DateTime dtEndA, DateTime dtStartB, DateTime dtEndB)
        {
            return dtStartA < dtEndB && dtStartB < dtEndA;
        }

Float a div in top right corner without overlapping sibling header

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

html

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

? css

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

?

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

Python Matplotlib figure title overlaps axes label when using twiny

I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:

plt.title(figure_title, y=1.08)

This also works for plt.suptitle(), but not (yet) for plt.xlabel(), etc.

Stop absolutely positioned div from overlapping text

If you are working with elements of unknown size, and you want to use position: absolute on them or their siblings, you're inevitably going to have to deal with overlap. By setting absolute position you're removing the element from the document flow, but the behaviour you want is that your element should be be pushed around by its siblings so as not to overlap...ie it should flow! You're seeking two totally contradictory things.

You should rethink your layout.

Perhaps what you want is that the .btn element should be absolutely positioned with respect to one of its preceding siblings, rather than against their common parent? In that case, you should set position: relative on the element you'd like to position the button against, and then make the button a child of that element. Now you can use absolute positioning and control overlap.

Debugging "Element is not clickable at point" error

It's funny, all the time I spent looking at the various responses, no one had tried the obvious, which of course, I hadn't either. If your page has the same id used multiple times, as mine did, ("newButton",) and the one you want is not the first one found, then you will in all likelihood get this error. The easiest thing to do (C#):

var testIt = driver.FindElements(By.Id("newButton"));

Note it's FindElements, not FindElement.

And then test to see how many results came back from the retrieval. If it's the second one, you can then use:

testit[1].Click();

Or get whomever reused ids to fix them.

twitter bootstrap navbar fixed top overlapping site

I put this before the yield container:

<div id="fix-for-navbar-fixed-top-spacing" style="height: 42px;">&nbsp;</div>

I like this approach because it documents the hack needed to get it work, plus it also works for the mobile nav.

EDIT - this works much better:

@media (min-width: 980px) {
  body {
    padding-top: 60px;
    padding-bottom: 42px;
  }
}

Rotate axis text in python matplotlib

Many "correct" answers here but I'll add one more since I think some details are left out of several. The OP asked for 90 degree rotation but I'll change to 45 degrees because when you use an angle that isn't zero or 90, you should change the horizontal alignment as well; otherwise your labels will be off-center and a bit misleading (and I'm guessing many people who come here want to rotate axes to something other than 90).

Easiest / Least Code

Option 1

plt.xticks(rotation=45, ha='right')

As mentioned previously, that may not be desirable if you'd rather take the Object Oriented approach.

Option 2

Another fast way (it's intended for date objects but seems to work on any label; doubt this is recommended though):

fig.autofmt_xdate(rotation=45)

fig you would usually get from:

  • fig = plt.figure()
  • fig, ax = plt.subplots()
  • fig = ax.figure

Object-Oriented / Dealing directly with ax

Option 3a

If you have the list of labels:

labels = ['One', 'Two', 'Three']
ax.set_xticklabels(labels, rotation=45, ha='right')

Option 3b

If you want to get the list of labels from the current plot:

# Unfortunately you need to draw your figure first to assign the labels,
# otherwise get_xticklabels() will return empty strings.
plt.draw()
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')

Option 4

Similar to above, but loop through manually instead.

for label in ax.get_xticklabels():
  label.set_rotation(45)
  label.set_ha('right')

Option 5

We still use pyplot (as plt) here but it's object-oriented because we're changing the property of a specific ax object.

plt.setp(ax.get_xticklabels(), rotation=45, ha='right')

Option 6

This option is simple, but AFAIK you can't set label horizontal align this way so another option might be better if your angle is not 90.

ax.tick_params(axis='x', labelrotation=45)

Edit: There's discussion of this exact "bug" and a fix is potentially slated for v3.2.0: https://github.com/matplotlib/matplotlib/issues/13774

How to place a div on the right side with absolute position

I'm assuming that your container element is probably position:relative;. This is will mean that the dialog box will be positioned accordingly to the container, not the page.

Can you change the markup to this?

<html>
<body>
    <!-- Need to place this div at the top right of the page-->
        <div class="ajax-message">
            <div class="row">
                <div class="span9">
                    <div class="alert">
                        <a class="close icon icon-remove"></a>
                        <div class="message-content">
                            Some message goes here
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <div class="container">
        <!-- Page contents starts here. These are dynamic-->
        <div class="row">
            <div class="span12 inner-col">
                <h2>Documents</h2>
            </div>
        </div>
    </div>
</body>
</html>

With the dialog box outside the main container then you can use absolute positioning relative to the page.

Target a css class inside another css class

Not certain what the HTML looks like (that would help with answers). If it's

<div class="testimonials content">stuff</div>

then simply remove the space in your css. A la...

.testimonials.content { css here }

UPDATE:

Okay, after seeing HTML see if this works...

.testimonials .wrapper .content { css here }

or just

.testimonials .wrapper { css here }

or

.desc-container .wrapper { css here }

all 3 should work.

Inserting into Oracle and retrieving the generated sequence ID

Expanding a bit on the answers from @Guru and @Ronnis, you can hide the sequence and make it look more like an auto-increment using a trigger, and have a procedure that does the insert for you and returns the generated ID as an out parameter.

create table batch(batchid number,
    batchname varchar2(30),
    batchtype char(1),
    source char(1),
    intarea number)
/

create sequence batch_seq start with 1
/

create trigger batch_bi
before insert on batch
for each row
begin
    select batch_seq.nextval into :new.batchid from dual;
end;
/

create procedure insert_batch(v_batchname batch.batchname%TYPE,
    v_batchtype batch.batchtype%TYPE,
    v_source batch.source%TYPE,
    v_intarea batch.intarea%TYPE,
    v_batchid out batch.batchid%TYPE)
as
begin
    insert into batch(batchname, batchtype, source, intarea)
    values(v_batchname, v_batchtype, v_source, v_intarea)
    returning batchid into v_batchid;
end;
/

You can then call the procedure instead of doing a plain insert, e.g. from an anoymous block:

declare
    l_batchid batch.batchid%TYPE;
begin
    insert_batch(v_batchname => 'Batch 1',
        v_batchtype => 'A',
        v_source => 'Z',
        v_intarea => 1,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);

    insert_batch(v_batchname => 'Batch 99',
        v_batchtype => 'B',
        v_source => 'Y',
        v_intarea => 9,
        v_batchid => l_batchid);
    dbms_output.put_line('Generated id: ' || l_batchid);
end;
/

Generated id: 1
Generated id: 2

You can make the call without an explicit anonymous block, e.g. from SQL*Plus:

variable l_batchid number;
exec insert_batch('Batch 21', 'C', 'X', 7, :l_batchid);

... and use the bind variable :l_batchid to refer to the generated value afterwards:

print l_batchid;
insert into some_table values(:l_batch_id, ...);

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

For adding a RelativeLayout attribute whose value is true or false use 0 for false and RelativeLayout.TRUE for true:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) button.getLayoutParams()
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE)

It doesn't matter whether or not the attribute was already added, you still use addRule(verb, subject) to enable/disable it. However, post-API 17 you can use removeRule(verb) which is just a shortcut for addRule(verb, 0).

memcpy() vs memmove()

As already pointed out in other answers, memmove is more sophisticated than memcpy such that it accounts for memory overlaps. The result of memmove is defined as if the src was copied into a buffer and then buffer copied into dst. This does NOT mean that the actual implementation uses any buffer, but probably does some pointer arithmetic.

Placing/Overlapping(z-index) a view above another view in android

You can't use a LinearLayout for this, but you can use a FrameLayout. In a FrameLayout, the z-index is defined by the order in which the items are added, for example:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/my_drawable"
        android:scaleType="fitCenter"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:padding="5dp"
        android:text="My Label"
        />
</FrameLayout>

In this instance, the TextView would be drawn on top of the ImageView, along the bottom center of the image.

How to set a transparent background of JPanel?

As Thrasgod correctly showed in his answer, the best way is to use the paintComponent, but also if the case is to have a semi transparent JPanel (or any other component, really) and have something not transparent inside. You have to also override the paintChildren method and set the alfa value to 1. In my case I extended the JPanel like that:

public class TransparentJPanel extends JPanel {

private float panelAlfa;
private float childrenAlfa;

public TransparentJPanel(float panelAlfa, float childrenAlfa) {
    this.panelAlfa = panelAlfa;
    this.childrenAlfa = childrenAlfa;
}

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(getBackground());
    g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, panelAlfa));
    super.paintComponent(g2d);

}

@Override
protected void paintChildren(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(getBackground());
    g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_ATOP, childrenAlfa));
  
    super.paintChildren(g); 
}
 //getter and setter
}

And in my project I only need to instantiate Jpanel jp = new TransparentJPanel(0.3f, 1.0f);, if I want only the Jpanel transparent. You could, also, mess with the JPanel shape using g2d.fillRoundRect and g2d.drawRoundRect, but it's not in the scope of this question.

Are 64 bit programs bigger and faster than 32 bit versions?

Any applications that require CPU usage such as transcoding, display performance and media rendering, whether it be audio or visual, will certainly require (at this point) and benefit from using 64 bit versus 32 bit due to the CPU's ability to deal with the sheer amount of data being thrown at it. It's not so much a question of address space as it is the way the data is being dealt with. A 64 bit processor, given 64 bit code, is going to perform better, especially with mathematically difficult things like transcoding and VoIP data - in fact, any sort of 'math' applications should benefit by the usage of 64 bit CPUs and operating systems. Prove me wrong.

Overlapping elements in CSS

Use CSS grid and set all the grid items to be in the same cell.

.layered {
  display: grid;
}

.layered > * {
  grid-column-start: 1;
  grid-row-start: 1;
}

Adding the layered class to an element causes all it's children to be layered on top of each other.

if the layers are not the same size you can set the justify-items and align-items properties to set the horizontal and vertical alignment respectively.


Demo:

JsFiddle

_x000D_
_x000D_
.layered {
  display: grid;

  /* Set horizontal alignment of items in, case they have a different width. */
  /* justify-items: start | end | center | stretch (default); */
  justify-items: start;

  /* Set vertical alignment of items, in case they have a different height. */
  /* align-items: start | end | center | stretch (default); */
  align-items: start;
}

.layered > * {
  grid-column-start: 1;
  grid-row-start: 1;
}


/* for demonstration purposes only */
.layered > * {
  outline: 1px solid red;
  background-color: rgba(255, 255, 255, 0.4)
}
_x000D_
<div class="layered">
  <img src="https://via.placeholder.com/250x100?text=first" />
  <p>
    2
  </p>
  <div>
    <p>
      Third layer
    </p>
    <p>
      Third layer continued
    </p>
    <p>
      Third layer continued
    </p>
    <p>
      Third layer continued
    </p>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Sound effects in JavaScript / HTML5

I ran into this while programming a musicbox card generator. Started with different libraries but everytime there was a glitch somehow. The lag on normal audio implementation was bad, no multiple plays... eventually ended up using lowlag library + soundmanager:

http://lowlag.alienbill.com/ and http://www.schillmania.com/projects/soundmanager2/

You can check out the implementation here: http://musicbox.grit.it/

I generated wav + ogg files for multi browser plays. This musicbox player works responsive on ipad, iphone, Nexus, mac, pc,... works for me.

Overlapping Views in Android

The simples way arround is to put -40dp margin at the buttom of the top imageview

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

A simple solution that i use, works from IE8+

Give min-height:100% on html so that if content is less then still page takes full view-port height and footer sticks at bottom of page. When content increases the footer shifts down with content and keep sticking to bottom.

JS fiddle working Demo: http://jsfiddle.net/3L3h64qo/2/

Css

html{
  position:relative; 
  min-height: 100%;
}
/*Normalize html and body elements,this style is just good to have*/
html,body{
  margin:0;
  padding:0;
}
.pageContentWrapper{
  margin-bottom:100px;/* Height of footer*/
} 
.footer{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height:100px;
    background:#ccc;
}

Html

   <html>
    <body>
        <div class="pageContentWrapper">
            <!-- All the page content goes here-->
        </div>
        <div class="footer">
        </div>
    </body>
    </html>

How do I position one image on top of another in HTML?

Here's code that may give you ideas:

<style>
.containerdiv { float: left; position: relative; } 
.cornerimage { position: absolute; top: 0; right: 0; } 
</style>

<div class="containerdiv">
    <img border="0" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt=""">
    <img class="cornerimage" border="0" src="http://www.gravatar.com/avatar/" alt="">
<div>

JSFiddle

I suspect that Espo's solution may be inconvenient because it requires you to position both images absolutely. You may want the first one to position itself in the flow.

Usually, there is a natural way to do that is CSS. You put position: relative on the container element, and then absolutely position children inside it. Unfortunately, you cannot put one image inside another. That's why I needed container div. Notice that I made it a float to make it autofit to its contents. Making it display: inline-block should theoretically work as well, but browser support is poor there.

EDIT: I deleted size attributes from the images to illustrate my point better. If you want the container image to have its default sizes and you don't know the size beforehand, you cannot use the background trick. If you do, it is a better way to go.

size of uint8, uint16 and uint32?

uint8, uint16, uint32, and uint64 are probably Microsoft-specific types.

As of the 1999 standard, C supports standard typedefs with similar meanings, defined in <stdint.h>: uint8_t, uint16_t, uint32_t, and uint64_t. I'll assume that the Microsoft-specific types are defined similarly. Microsoft does support <stdint.h>, at least as of Visual Studio 2010, but older code may use uint8 et al.

The predefined types char, short, int et al have sizes that vary from one C implementation to another. The C standard has certain minimum requirements (char is at least 8 bits, short and int are at least 16, long is at least 32, and each type in that list is at least as wide as the previous type), but permits some flexibility. For example, I've seen systems where int is 16, 32, or 64 bits.

char is almost always exactly 8 bits, but it's permitted to be wider. And plain char may be either signed or unsigned.

uint8_t is required to be an unsigned integer type that's exactly 8 bits wide. It's likely to be a typedef for unsigned char, though it might be a typedef for plain char if plain char happens to be unsigned. If there is no predefined 8-bit unsigned type, then uint8_t will not be defined at all.

Similarly, each uintN_t type is an unsigned type that's exactly N bits wide.

In addition, <stdint.h> defines corresponding signed intN_t types, as well as int_fastN_t and int_leastN_t types that are at least the specified width.

The [u]intN_t types are guaranteed to have no padding bits, so the size of each is exactly N bits. The signed intN_t types are required to use a 2's-complement representation.

Although uint32_t might be the same as unsigned int, for example, you shouldn't assume that. Use unsigned int when you need an unsigned integer type that's at least 16 bits wide, and that's the "natural" size for the current system. Use uint32_t when you need an unsigned integer type that's exactly 32 bits wide.

(And no, uint64 or uint64_t is not the same as double; double is a floating-point type.)

Cache an HTTP 'Get' service response in AngularJS?

In Angular 8 we can do like this:

import { Injectable } from '@angular/core';
import { YourModel} from '../models/<yourModel>.model';
import { UserService } from './user.service';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class GlobalDataService {

  private me: <YourModel>;

  private meObservable: Observable<User>;

  constructor(private yourModalService: <yourModalService>, private http: HttpClient) {

  }

  ngOnInit() {

  }


  getYourModel(): Observable<YourModel> {

    if (this.me) {
      return of(this.me);
    } else if (this.meObservable) {
      return this.meObservable;
    }
    else {
      this.meObservable = this.yourModalService.getCall<yourModel>() // Your http call
      .pipe(
        map(data => {
          this.me = data;
          return data;
        })
      );
      return this.meObservable;
    }
  }
}

You can call it like this:

this.globalDataService.getYourModel().subscribe(yourModel => {


});

The above code will cache the result of remote API at first call so that it can be used on further requests to that method.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I couldn't find an off-the-shelf module that added this function, so I wrote one:

In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:

Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String

Substring_Index = delims

start = 0
test = ""

For i = 1 To intCount
    oldstart = start + 1
    start = InStr(oldstart, strWord, strDelim)
    Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i

End Function

Save the module as module1 (the default). You can now use statements like:

SELECT Substring_Index([fieldname],",",2) FROM table

How can I call controller/view helper methods from the console in Ruby on Rails?

Inside any controller action or view, you can invoke the console by calling the console method.

For example, in a controller:

class PostsController < ApplicationController
  def new
    console
    @post = Post.new
  end
end

Or in a view:

<% console %>

<h2>New Post</h2>

This will render a console inside your view. You don't need to care about the location of the console call; it won't be rendered on the spot of its invocation but next to your HTML content.

See: http://guides.rubyonrails.org/debugging_rails_applications.html

Get Hard disk serial Number

I have used the following method in a project and it's working successfully.

private string identifier(string wmiClass, string wmiProperty)
//Return a hardware identifier
{
    string result = "";
    System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
    System.Management.ManagementObjectCollection moc = mc.GetInstances();
    foreach (System.Management.ManagementObject mo in moc)
    {
        //Only get the first one
        if (result == "")
        {
            try
            {
                result = mo[wmiProperty].ToString();
                break;
            }
            catch
            {
            }
        }
    }
    return result;
}

you can call the above method as mentioned below,

string modelNo = identifier("Win32_DiskDrive", "Model");
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer");
string signature = identifier("Win32_DiskDrive", "Signature");
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads");

If you need a unique identifier, use a combination of these IDs.

Java - remove last known item from ArrayList

First error: You're casting a ClientThread as a String for some reason.

Second error: You're not calling remove on your List.

Is is homework? If so, you might want to use the tag.

Split an NSString to access one particular piece

Objective-c:

NSString *day = [@"10/04/2011" componentsSeparatedByString:@"/"][0];

Swift:

var day: String = "10/04/2011".componentsSeparatedByString("/")[0]

How to set initial value and auto increment in MySQL?

For this you have to set AUTO_INCREMENT value

ALTER TABLE tablename AUTO_INCREMENT = <INITIAL_VALUE>

Example

ALTER TABLE tablename AUTO_INCREMENT = 101

The executable was signed with invalid entitlements

I have found that "get-task-allow" needs to be checked for Development builds but unchecked for Distribution builds. The easiest way to accomplish this (AFAIK) is to have two entitlements files in your project: Entitlements.plist and EntitlementsDebug.plist - and to reference the proper one in the build project settings for the various configurations in your project.

Format a JavaScript string using placeholders and an object of substitutions?

const stringInject = (str = '', obj = {}) => {
  let newStr = str;
  Object.keys(obj).forEach((key) => {
    let placeHolder = `#${key}#`;
    if(newStr.includes(placeHolder)) {
      newStr = newStr.replace(placeHolder, obj[key] || " ");
    }
  });
  return newStr;
}
Input: stringInject("Hi #name#, How are you?", {name: "Ram"});
Output: "Hi Ram, How are you?"

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

You can use myDict.has_key(keyname) as well to validate if the key exists.

Edit based on the comments -

This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

Passing a Bundle on startActivity()?

Write this is the activity you are in:

Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);

In the NextActivity.java

Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));

This works for me, you can try it.

Source:https://www.c-sharpcorner.com/article/how-to-send-the-data-one-activity-to-another-activity-in-android-application/

jQuery selector for id starts with specific text

Use jquery starts with attribute selector

$('[id^=editDialog]')

Alternative solution - 1 (highly recommended)

A cleaner solution is to add a common class to each of the divs & use

$('.commonClass').

But you can use the first one if html markup is not in your hands & cannot change it for some reason.

Alternative solution - 2 (not recommended if n is a large number) (as per @Mihai Stancu's suggestion)

$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')

Note: If there are 2 or 3 selectors and if the list doesn't change, this is probably a viable solution but it is not extensible because we have to update the selectors when there is a new ID in town.

What does "request for member '*******' in something not a structure or union" mean?

It also happens if you're trying to access an instance when you have a pointer, and vice versa:

struct foo
{
  int x, y, z;
};

struct foo a, *b = &a;

b.x = 12;  /* This will generate the error, should be b->x or (*b).x */

As pointed out in a comment, this can be made excruciating if someone goes and typedefs a pointer, i.e. includes the * in a typedef, like so:

typedef struct foo* Foo;

Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:

Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;

Note how the above looks as if it should be written a_foo.field, but that would fail since Foo is a pointer to struct. I strongly recommend against typedef:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.

React Hooks useState() with Object

I leave you a utility function to inmutably update objects

/**
 * Inmutable update object
 * @param  {Object} oldObject     Object to update
 * @param  {Object} updatedValues Object with new values
 * @return {Object}               New Object with updated values
 */
export const updateObject = (oldObject, updatedValues) => {
  return {
    ...oldObject,
    ...updatedValues
  };
};

So you can use it like this

const MyComponent = props => {

  const [orderForm, setOrderForm] = useState({
    specialities: {
      elementType: "select",
      elementConfig: {
        options: [],
        label: "Specialities"
      },
      touched: false
    }
  });


// I want to update the options list, to fill a select element

  // ---------- Update with fetched elements ---------- //

  const updateSpecialitiesData = data => {
    // Inmutably update elementConfig object. i.e label field is not modified
    const updatedOptions = updateObject(
      orderForm[formElementKey]["elementConfig"],
      {
        options: data
      }
    );
    // Inmutably update the relevant element.
    const updatedFormElement = updateObject(orderForm[formElementKey], {
      touched: true,
      elementConfig: updatedOptions
    });
    // Inmutably update the relevant element in the state.
    const orderFormUpdated = updateObject(orderForm, {
      [formElementKey]: updatedFormElement
    });
    setOrderForm(orderFormUpdated);
  };

  useEffect(() => {
      // some code to fetch data
      updateSpecialitiesData.current("specialities",fetchedData);
  }, [updateSpecialitiesData]);

// More component code
}

If not you have more utilities here : https://es.reactjs.org/docs/update.html

What's the easiest way to escape HTML in Python?

cgi.escape is fine. It escapes:

  • < to &lt;
  • > to &gt;
  • & to &amp;

That is enough for all HTML.

EDIT: If you have non-ascii chars you also want to escape, for inclusion in another encoded document that uses a different encoding, like Craig says, just use:

data.encode('ascii', 'xmlcharrefreplace')

Don't forget to decode data to unicode first, using whatever encoding it was encoded.

However in my experience that kind of encoding is useless if you just work with unicode all the time from start. Just encode at the end to the encoding specified in the document header (utf-8 for maximum compatibility).

Example:

>>> cgi.escape(u'<a>bá</a>').encode('ascii', 'xmlcharrefreplace')
'&lt;a&gt;b&#225;&lt;/a&gt;

Also worth of note (thanks Greg) is the extra quote parameter cgi.escape takes. With it set to True, cgi.escape also escapes double quote chars (") so you can use the resulting value in a XML/HTML attribute.

EDIT: Note that cgi.escape has been deprecated in Python 3.2 in favor of html.escape, which does the same except that quote defaults to True.

How can I decrypt a password hash in PHP?

The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.

if(password_verify($upass, $userRow['user_pass'])){
     //code for redirecting to login screen }

where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.

Basic text editor in command prompt?

There is one built into windows 7 in which you can open by clicking the windows and r keys at the same time and then typing edit.com.

I hope this helped

Python Function to test ping

Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":

import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

This will work on Windows, OS X, and Linux

You can also use sys:

import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

Run chrome in fullscreen mode on Windows

You can also add --disable-session-crashed-bubble to eliminate the errors that come up after a crash or improper shutdown.

Select query to remove non-numeric characters

CREATE FUNCTION FN_RemoveNonNumeric (@Input NVARCHAR(512))
RETURNS NVARCHAR(512)
AS
BEGIN
DECLARE @Trimmed NVARCHAR(512)

SELECT @Trimmed = @Input

WHILE PATINDEX('%[^0-9]%', @Trimmed) > 0
    SELECT @Trimmed = REPLACE(@Trimmed, SUBSTRING(@Trimmed, PATINDEX('%[^0-9]%', @Trimmed), 1), '')

RETURN @Trimmed
END

GO

SELECT dbo.FN_RemoveNonNumeric('ABCDE# 123')

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

What does "var" mean in C#?

It means that the type of the local being declared will be inferred by the compiler based upon its first assignment:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints

var has only two uses:

  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };

You cannot use var as the type of anything but locals. So you cannot use the keyword var to declare field/property/parameter/return types.

NameError: global name 'unicode' is not defined - in Python 3

You can use the six library to support both Python 2 and 3:

import six
if isinstance(value, six.string_types):
    handle_string(value)

iPhone App Icons - Exact Radius?

The answer from dbarnard has the formula to calculate the correct radius, but since you were looking for the templates, all the masks and overlays can be found in this directory:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk/System/Library/PrivateFrameworks/MobileIcons.framework

(path is for recent versions of XCode. For older version it will probably be inside /Developer/).

As others have noted, you should NOT mask them yourself, but you can use these to check how your icons will look once masked.

(credits for this finding goes to Neven Mrgan IIRC)

How to round up a number in Javascript?

parseInt always rounds down soo.....

_x000D_
_x000D_
console.log(parseInt(5.8)+1);
_x000D_
_x000D_
_x000D_

do parseInt()+1

Why is my asynchronous function returning Promise { <pending> } instead of a value?

Your Promise is pending, complete it by

userToken.then(function(result){
console.log(result)
})

after your remaining code. All this code does is that .then() completes your promise & captures the end result in result variable & print result in console. Keep in mind, you cannot store the result in global variable. Hope that explanation might help you.

Key error when selecting columns in pandas dataframe after read_csv

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Function for 'does matrix contain value X?'

If you need to check whether the elements of one vector are in another, the best solution is ismember as mentioned in the other answers.

ismember([15 17],primes(20))

However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf

It gives a very practical example:

[tf, loc]=ismember(0.3, 0:0.1:1) % returns false 
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true

Though the default tolerance should normally be sufficient, it gives you more flexibility

ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true

laravel 5.3 new Auth::routes()

This worked for me with Laravel 5.6.

In the file web.php, just replace:

Auth::routes();

By:

//Auth::routes();
// Authentication Routes...
Route::get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('admin/login', 'Auth\LoginController@login');
Route::post('admin/logout', 'Auth\LoginController@logout')->name('logout');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

And remove the Register link in the two files below:

welcome.blade.php
layouts/app.blade.php

Gradle: Could not determine java version from '11.0.2'

I ran into a similar issue. I deleted these:

  • libraries and caches from the .idea folder ( YourApp > .idea > .. ) AND
  • contents of the build folder.

    then rebuild.

* DON'T FORGET TO BACKUP YOUR PROJECT FIRST *

Read response body in JAX-RS client from a post request

Try this:

String output = response.getEntity(String.class);

EDIT

Thanks to @Martin Spamer to mention that it will work for Jersey 1.x jars only. For Jersey 2.x use

String output = response.readEntity(String.class);

How to append contents of multiple files into one file

If the original file contains non-printable characters, they will be lost when using the cat command. Using 'cat -v', the non-printables will be converted to visible character strings, but the output file would still not contain the actual non-printables characters in the original file. With a small number of files, an alternative might be to open the first file in an editor (e.g. vim) that handles non-printing characters. Then maneuver to the bottom of the file and enter ":r second_file_name". That will pull in the second file, including non-printing characters. The same could be done for additional files. When all files have been read in, enter ":w". The end result is that the first file will now contain what it did originally, plus the content of the files that were read in.

Telnet is not recognized as internal or external command

  1. Open "Start" (Windows Button)
  2. Search for "Turn Windows features On or Off"
  3. Check "Telnet client" and check "Telnet server".

Is there a better way to refresh WebView?

Yes for some reason WebView.reload() causes a crash if it failed to load before (something to do with the way it handles history). This is the code I use to refresh my webview. I store the current url in self.url

# 1: Pause timeout and page loading

self.timeout.pause()
sleep(1)

# 2: Check for internet connection (Really lazy way)

while self.page().networkAccessManager().networkAccessible() == QNetworkAccessManager.NotAccessible: sleep(2)

# 3:Try again

if self.url == self.page().mainFrame().url():
    self.page().action(QWebPage.Reload)
    self.timeout.resume(60)

else:
    self.page().action(QWebPage.Stop)
    self.page().mainFrame().load(self.url)
    self.timeout.resume(30)

return False

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

If it's reasonable to alter the original Map data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null key entries, if possible, before calling Jackson. That said...


To suppress serializing Map entries with null values:

Before Jackson 2.9

you can still make use of WRITE_NULL_MAP_VALUES, but note that it's moved to SerializationFeature:

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

Since Jackson 2.9

The WRITE_NULL_MAP_VALUES is deprecated, you can use the below equivalent:

mapper.setDefaultPropertyInclusion(
   JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))

To suppress serializing properties with null values, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To handle null Map keys, some custom serialization is necessary, as best I understand.

A simple approach to serialize null keys as empty strings (including complete examples of the two previously mentioned configurations):

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    Map<String, Foo> foos = new HashMap<String, Foo>();
    foos.put("foo1", new Foo("foo1"));
    foos.put("foo2", new Foo(null));
    foos.put("foo3", null);
    foos.put(null, new Foo("foo4"));

    // System.out.println(new ObjectMapper().writeValueAsString(foos));
    // Exception: Null key for a Map not allowed in JSON (use a converting NullKeySerializer?)

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());
    System.out.println(mapper.writeValueAsString(foos));
    // output: 
    // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}
  }
}

class MyNullKeySerializer extends JsonSerializer<Object>
{
  @Override
  public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) 
      throws IOException, JsonProcessingException
  {
    jsonGenerator.writeFieldName("");
  }
}

class Foo
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

To suppress serializing Map entries with null keys, further custom serialization processing would be necessary.

Maximum length of the textual representation of an IPv6 address?

On Linux, see constant INET6_ADDRSTRLEN (include <arpa/inet.h>, see man inet_ntop). On my system (header "in.h"):

#define INET6_ADDRSTRLEN 46

The last character is for terminating NULL, as I belive, so the max length is 45, as other answers.

Where can I find "make" program for Mac OS X Lion?

Have you installed Xcode and the developer tools? I think make, along with gcc and friends, is installed with that and not before. Xcode 4.1 for Lion is free.

How to add header to a dataset in R?

You can also solve this problem by creating an array of values and assigning that array:

newheaders <- c("a", "b", "c", ... "x")
colnames(data) <- newheaders

How to select first child with jQuery?

Try with: $('.onediv').eq(0)

demo jsBin

From the demo: Other examples of selectors and methods targeting the first LI unside an UL:

.eq() Method: $('li').eq(0)
:eq() selector: $('li:eq(0)')
.first() Method $('li').first()
:first selector: $('li:first')
:first-child selector: $('li:first-child')
:lt() selector:$('li:lt(1)')
:nth-child() selector:$('li:nth-child(1)')

jQ + JS:

Array.slice() Method: $('li').slice(0,1)

you can also use [i] to get the JS HTMLelement index out of the jQuery el. (array) collection like eg:

$('li')[0]

now that you have the JS element representation you have to use JS native methods eg:

$('li')[0].className = 'active'; // Adds class "active" to the first LI in the DOM

or you can (don't - it's bad design) wrap it back into a jQuery object

$( $('li')[0] ).addClass('active'); // Don't. Use .eq() instead

Python function overloading

Python does support "method overloading" as you present it. In fact, what you just describe is trivial to implement in Python, in so many different ways, but I would go with:

class Character(object):
    # your character __init__ and other methods go here

    def add_bullet(self, sprite=default, start=default, 
                 direction=default, speed=default, accel=default, 
                  curve=default):
        # do stuff with your arguments

In the above code, default is a plausible default value for those arguments, or None. You can then call the method with only the arguments you are interested in, and Python will use the default values.

You could also do something like this:

class Character(object):
    # your character __init__ and other methods go here

    def add_bullet(self, **kwargs):
        # here you can unpack kwargs as (key, values) and
        # do stuff with them, and use some global dictionary
        # to provide default values and ensure that ``key``
        # is a valid argument...

        # do stuff with your arguments

Another alternative is to directly hook the desired function directly to the class or instance:

def some_implementation(self, arg1, arg2, arg3):
  # implementation
my_class.add_bullet = some_implementation_of_add_bullet

Yet another way is to use an abstract factory pattern:

class Character(object):
   def __init__(self, bfactory, *args, **kwargs):
       self.bfactory = bfactory
   def add_bullet(self):
       sprite = self.bfactory.sprite()
       speed = self.bfactory.speed()
       # do stuff with your sprite and speed

class pretty_and_fast_factory(object):
    def sprite(self):
       return pretty_sprite
    def speed(self):
       return 10000000000.0

my_character = Character(pretty_and_fast_factory(), a1, a2, kw1=v1, kw2=v2)
my_character.add_bullet() # uses pretty_and_fast_factory

# now, if you have another factory called "ugly_and_slow_factory" 
# you can change it at runtime in python by issuing
my_character.bfactory = ugly_and_slow_factory()

# In the last example you can see abstract factory and "method
# overloading" (as you call it) in action 

How do I display images from Google Drive on a website?

I don't know of a better way but you can datamine the page with php. For instance if you go to google and share a folder then go to that folder it will look something like

https://drive.google.com/folderview?id=0B8TT0olkjsdkfji9jekbFF4LWc&usp=sharing

^^^ not a real link

What you are looking for is the individual images inside the source code of this page

then using php get the source code with

<? $f = fopen ("http://www.example.com/f", r);
echo $f;
?>

now $f has the source and you can use other php commands to seperate only the URLS with the images you want. It will take a bit of work but highly doable.

once you have these image links showing the way you want just build them into a div or table structure to display on a gallery maybe even add a greybox element for effect

How many times does each value appear in a column?

I second Dave's idea. I'm not always fond of pivot tables, but in this case they are pretty straightforward to use.

Here are my results:

Enter image description here

It was so simple to create it that I have even recorded a macro in case you need to do this with VBA:

Sub Macro2()
'
' Macro2 Macro
'

'
    Range("Table1[[#All],[DATA]]").Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Table1", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
        :="Sheet3!R3C7", TableName:="PivotTable4", DefaultVersion:= _
        xlPivotTableVersion14
    Sheets("Sheet3").Select
    Cells(3, 7).Select
    With ActiveSheet.PivotTables("PivotTable4").PivotFields("DATA")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables( _
        "PivotTable4").PivotFields("DATA"), "Count of DATA", xlCount
End Sub

Does swift have a trim method on String?

**Swift 5**

extension String {

    func trimAllSpace() -> String {
         return components(separatedBy: .whitespacesAndNewlines).joined()
    }
    
    func trimSpace() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

**Use:**
let result = " abc ".trimAllSpace()
// result == "abc"
let ex = " abc cd  ".trimSpace()
// ex == "abc cd"

How to find the kth largest element in an unsorted array of length n in O(n)?

This is an implementation in Javascript.

If you release the constraint that you cannot modify the array, you can prevent the use of extra memory using two indexes to identify the "current partition" (in classic quicksort style - http://www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/).

function kthMax(a, k){
    var size = a.length;

    var pivot = a[ parseInt(Math.random()*size) ]; //Another choice could have been (size / 2) 

    //Create an array with all element lower than the pivot and an array with all element higher than the pivot
    var i, lowerArray = [], upperArray = [];
    for (i = 0; i  < size; i++){
        var current = a[i];

        if (current < pivot) {
            lowerArray.push(current);
        } else if (current > pivot) {
            upperArray.push(current);
        }
    }

    //Which one should I continue with?
    if(k <= upperArray.length) {
        //Upper
        return kthMax(upperArray, k);
    } else {
        var newK = k - (size - lowerArray.length);

        if (newK > 0) {
            ///Lower
            return kthMax(lowerArray, newK);
        } else {
            //None ... it's the current pivot!
            return pivot;
        }   
    }
}  

If you want to test how it perform, you can use this variation:

    function kthMax (a, k, logging) {
         var comparisonCount = 0; //Number of comparison that the algorithm uses
         var memoryCount = 0;     //Number of integers in memory that the algorithm uses
         var _log = logging;

         if(k < 0 || k >= a.length) {
            if (_log) console.log ("k is out of range"); 
            return false;
         }      

         function _kthmax(a, k){
             var size = a.length;
             var pivot = a[parseInt(Math.random()*size)];
             if(_log) console.log("Inputs:", a,  "size="+size, "k="+k, "pivot="+pivot);

             // This should never happen. Just a nice check in this exercise
             // if you are playing with the code to avoid never ending recursion            
             if(typeof pivot === "undefined") {
                 if (_log) console.log ("Ops..."); 
                 return false;
             }

             var i, lowerArray = [], upperArray = [];
             for (i = 0; i  < size; i++){
                 var current = a[i];
                 if (current < pivot) {
                     comparisonCount += 1;
                     memoryCount++;
                     lowerArray.push(current);
                 } else if (current > pivot) {
                     comparisonCount += 2;
                     memoryCount++;
                     upperArray.push(current);
                 }
             }
             if(_log) console.log("Pivoting:",lowerArray, "*"+pivot+"*", upperArray);

             if(k <= upperArray.length) {
                 comparisonCount += 1;
                 return _kthmax(upperArray, k);
             } else if (k > size - lowerArray.length) {
                 comparisonCount += 2;
                 return _kthmax(lowerArray, k - (size - lowerArray.length));
             } else {
                 comparisonCount += 2;
                 return pivot;
             }
     /* 
      * BTW, this is the logic for kthMin if we want to implement that... ;-)
      * 

             if(k <= lowerArray.length) {
                 return kthMin(lowerArray, k);
             } else if (k > size - upperArray.length) {
                 return kthMin(upperArray, k - (size - upperArray.length));
             } else 
                 return pivot;
     */            
         }

         var result = _kthmax(a, k);
         return {result: result, iterations: comparisonCount, memory: memoryCount};
     }

The rest of the code is just to create some playground:

    function getRandomArray (n){
        var ar = [];
        for (var i = 0, l = n; i < l; i++) {
            ar.push(Math.round(Math.random() * l))
        }

        return ar;
    }

    //Create a random array of 50 numbers
    var ar = getRandomArray (50);   

Now, run you tests a few time. Because of the Math.random() it will produce every time different results:

    kthMax(ar, 2, true);
    kthMax(ar, 2);
    kthMax(ar, 2);
    kthMax(ar, 2);
    kthMax(ar, 2);
    kthMax(ar, 2);
    kthMax(ar, 34, true);
    kthMax(ar, 34);
    kthMax(ar, 34);
    kthMax(ar, 34);
    kthMax(ar, 34);
    kthMax(ar, 34);

If you test it a few times you can see even empirically that the number of iterations is, on average, O(n) ~= constant * n and the value of k does not affect the algorithm.

List of Java processes

jps -lV

is most useful. Prints just pid and qualified main class name:

2472 com.intellij.idea.Main
11111 sun.tools.jps.Jps
9030 play.server.Server
2752 org.jetbrains.idea.maven.server.RemoteMavenServer

How to sort a list/tuple of lists/tuples by the element at a given index?

@Stephen 's answer is to the point! Here is an example for better visualization,

Shout out for the Ready Player One fans! =)

>>> gunters = [('2044-04-05', 'parzival'), ('2044-04-07', 'aech'), ('2044-04-06', 'art3mis')]
>>> gunters.sort(key=lambda tup: tup[0])
>>> print gunters
[('2044-04-05', 'parzival'), ('2044-04-06', 'art3mis'), ('2044-04-07', 'aech')]

key is a function that will be called to transform the collection's items for comparison.. like compareTo method in Java.

The parameter passed to key must be something that is callable. Here, the use of lambda creates an anonymous function (which is a callable).
The syntax of lambda is the word lambda followed by a iterable name then a single block of code.

Below example, we are sorting a list of tuple that holds the info abt time of certain event and actor name.

We are sorting this list by time of event occurrence - which is the 0th element of a tuple.

Note - s.sort([cmp[, key[, reverse]]]) sorts the items of s in place

What's the difference between Apache's Mesos and Google's Kubernetes

Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include:

  • pods — a way to group containers together
  • replication controllers — a way to handle the lifecycle of containers
  • labels — a way to find and query containers, and
  • services — a set of containers performing a common function.

So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily.

With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere.

Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state).

When asked, I tend to say:

  1. Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc).

  2. If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps.

  3. Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.

Playing m3u8 Files with HTML Video Tag

Might be a little late with the answer but you need to supply the MIME type attribute in the video tag: type="application/x-mpegURL". The video tag I use for a 16:9 stream looks like this.

<video width="352" height="198" controls>
    <source src="playlist.m3u8" type="application/x-mpegURL">
</video>

Python: can't assign to literal

The left hand side of the = operator needs to be a variable. What you're doing here is telling python: "You know the number one? Set it to the inputted string.". 1 is a literal number, not a variable. 1 is always 1, you can't "set" it to something else.

A variable is like a box in which you can store a value. 1 is a value that can be stored in the variable. The input call returns a string, another value that can be stored in a variable.

Instead, use lists:

import random

namelist = []
namelist.append(input("Please enter name 1:"))  #Stored in namelist[0]
namelist.append(input('Please enter name 2:'))  #Stored in namelist[1]
namelist.append(input('Please enter name 3:'))  #Stored in namelist[2]
namelist.append(input('Please enter name 4:'))  #Stored in namelist[3]
namelist.append(input('Please enter name 5:'))  #Stored in namelist[4]

nameindex = random.randint(0, 5)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Using a for loop, you can cut down even more:

import random

namecount = 5
namelist=[]
for i in range(0, namecount):
  namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]

nameindex = random.randint(0, namecount)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Relative paths based on file location instead of current working directory

@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.

This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:


Linux / GNU readlink solution:

If your script needs to run on Linux only or you know that GNU readlink is in the $PATH, use readlink -f, which conveniently resolves a symlink to its ultimate target:

 scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")

Note that GNU readlink has 3 related options for resolving a symlink to its ultimate target's full path: -f (--canonicalize), -e (--canonicalize-existing), and -m (--canonicalize-missing) - see man readlink.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f here, because it is the most well-known one.


Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):

If your script must run on any platform that:

  • has a readlink utility, but lacks the -f option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.

    • macOS uses an older version of the BSD implementation of readlink; note that recent versions of FreeBSD/PC-BSD do support -f.
  • does not even have readlink, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).

The following solution, inspired by https://stackoverflow.com/a/1116890/45375, defines helper shell function, rreadlink(), which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink's -e option, which is similar to the -f option, except that the ultimate target must exist.

Note: The function is a bash function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh), see here.

  • If readlink is available, it is used (without options) - true on most modern platforms.

  • Otherwise, the output from ls -l is parsed, which is the only POSIX-compliant way to determine a symlink's target.
    Caveat: this will break if a filename or path contains the literal substring -> - which is unlikely, however.
    (Note that platforms that lack readlink may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find utility supporting the %l format char. with its -printf primary; in the interest of brevity the function does NOT try to detect such cases.)

  • An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink; on other platforms (assuming they have bash), follow the manual installation instructions.

If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.

#!/usr/bin/env bash

# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...

  local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH= 

  # Since we'll be using `command` below for a predictable execution
  # environment, we make sure that it has its original meaning.
  { \unalias command; \unset -f command; } &>/dev/null

  while :; do # Resolve potential symlinks until the ultimate target is found.
      [[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
      command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
      fname=$(command basename -- "$target") # Extract filename.
      [[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
      if [[ -L $fname ]]; then
        # Extract [next] target path, which is defined
        # relative to the symlink's own directory.
        if [[ -n $readlinkexe ]]; then # Use `readlink`.
          target=$("$readlinkexe" -- "$fname")
        else # `readlink` utility not available.
          # Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant 
          # way to determine a symlink's target. Hypothetically, this can break with
          # filenames containig literal ' -> ' and embedded newlines.
          target=$(command ls -l -- "$fname")
          target=${target#* -> }
        fi
        continue # Resolve [next] symlink target.
      fi
      break # Ultimate target reached.
  done
  targetDir=$(command pwd -P) # Get canonical dir. path
  # Output the ultimate target's canonical path.
  # Note that we manually resolve paths ending in /. and /.. to make sure we
  # have a normalized path.
  if [[ $fname == '.' ]]; then
    command printf '%s\n' "${targetDir%/}"
  elif  [[ $fname == '..' ]]; then
    # Caveat: something like /var/.. will resolve to /private (assuming
    # /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
    command printf '%s\n' "$(command dirname -- "${targetDir}")"
  else
    command printf '%s\n' "${targetDir%/}/$fname"
  fi
)

# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")

Binding Button click to a method

Some more explanations to the solution Rachel already gave:

"WPF Apps With The Model-View-ViewModel Design Pattern"

by Josh Smith

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Python: How would you save a simple settings/config file?

Save and load a dictionary. You will have arbitrary keys, values and arbitrary number of key, values pairs.

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

SQL Server Express CREATE DATABASE permission denied in database 'master'

What login are you connecting to SQL Server as? You need to connect with a login that has sufficient privileges to create a database. Network Service is probably not good enough, unless you go into SQL Server and add them as a login with sufficient rights.

In Tensorflow, get the names of all the Tensors in a graph

This worked for me:

for n in tf.get_default_graph().as_graph_def().node:
    print('\n',n)

Script for rebuilding and reindexing the fragmented index?

The real answer, in 2016 and 2017, is: Use Ola Hallengren's scripts:

https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

That is all any of us need to know or bother with, at this point in our mutual evolution.

How to get first 5 characters from string

An alternative way to get only one character.

$str = 'abcdefghij';
echo $str{5};

I would particularly not use this, but for the purpose of education. We can use that to answer the question:

$newString = '';
for ($i = 0; $i < 5; $i++) {
    $newString .= $str{$i};
}
echo $newString;

For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4

More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access

No Spring WebApplicationInitializer types detected on classpath

I faced this problem and finally resolved. Please make sure that your web.xml and Servlet.xml file should present in web/inf folder.

Also Please add spring jars into Web Deployment assembly in project properties

We might missed out this when setting up the project from beginning.

LaTeX table too wide. How to make it fit?

You have to take whole columns under resizebox. This code worked for me

\begin{table}[htbp]
\caption{Sample Table.}\label{tab1}
\resizebox{\columnwidth}{!}{\begin{tabular}{|l|l|l|l|l|}
\hline
URL &  First Time Visit & Last Time Visit & URL Counts & Value\\
\hline
https://web.facebook.com/ & 1521241972 & 1522351859 & 177 & 56640\\
http://localhost/phpmyadmin/ & 1518413861 & 1522075694 & 24 & 39312\\
https://mail.google.com/mail/u/ & 1516596003 & 1522352010 & 36 & 33264\\
https://github.com/shawon100& 1517215489 & 1522352266 & 37 & 27528\\
https://www.youtube.com/ & 1517229227 & 1521978502 & 24 & 14792\\
\hline
\end{tabular}}
\end{table}

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

What is DOM Event delegation?

dom event delegation is something different from the computer science definition.

It refers to handling bubbling events from many elements, like table cells, from a parent object, like the table. It can keep the code simpler, especially when adding or removing elements, and saves some memory.

How to add items into a numpy array

Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.

That said, It's often unavoidable and the functions that do this are:

for 2-D arrays:

for 3-D arrays (the above plus):

for N-D arrays:

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

Two ways:

  1. Have a bean implement ApplicationListener<ContextClosedEvent>. onApplicationEvent() will get called before the context and all the beans are destroyed.

  2. Have a bean implement Lifecycle or SmartLifecycle. stop() will get called before the context and all the beans are destroyed.

Either way you can shut down the task stuff before the bean destroying mechanism takes place.

Eg:

@Component
public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> {
    @Autowired ThreadPoolTaskExecutor executor;
    @Autowired ThreadPoolTaskScheduler scheduler;

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        scheduler.shutdown();
        executor.shutdown();
    }       
}

(Edit: Fixed method signature)

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

here is my initial git commands (possibly, this action takes place in C:/Documents and Settings/your_username/):

mkdir ~/Hello-World
# Creates a directory for your project called "Hello-World" in your user directory
cd ~/Hello-World
# Changes the current working directory to your newly created directory
touch blabla.html
# create a file, named blabla.html
git init
# Sets up the necessary Git files
git add blabla.html
# Stages your blabla.html file, adding it to the list of files to be committed
git commit -m 'first committttt'
# Commits your files, adding the message 
git remote add origin https://github.com/username/Hello-World.git
# Creates a remote named "origin" pointing at your GitHub repository
git push -u origin master
# Sends your commits in the "master" branch to GitHub

How do I set up HttpContent for my HttpClient PostAsync second parameter?

    public async Task<ActionResult> Index()
    {
        apiTable table = new apiTable();
        table.Name = "Asma Nadeem";
        table.Roll = "6655";

        string str = "";
        string str2 = "";

        HttpClient client = new HttpClient();

        string json = JsonConvert.SerializeObject(table);

        StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);

        str = "" + response.Content + " : " + response.StatusCode;

        if (response.IsSuccessStatusCode)
        {       
            str2 = "Data Posted";
        }

        return View();
    }

Dynamically add item to jQuery Select2 control that uses AJAX

This provided a simple solution: Set data in Select2 after insert with AJAX

$("#select2").select2('data', {id: newID, text: newText});      

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

How to convert String to Date value in SAS?

Formats like

date9. 

or

mmddyy10. 

are not valid for input command while converting text to a sas date. You can use

Date = input( cdate , ANYDTDTE11.);

or

Date = input( cdate , ANYDTDTE10.); 

for conversion.

Opacity CSS not working in IE8

You need to set Opacity first for standards-compliant browsers, then the various versions of IE. See Example:

but this opacity code not work in ie8

.slidedownTrigger
{
    cursor: pointer;
    opacity: .75; /* Standards Compliant Browsers */
    filter: alpha(opacity=75); /* IE 7 and Earlier */
    /* Next 2 lines IE8 */
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
    filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=75);
}

Note that I eliminated -moz as Firefox is a Standards Compliant browser and that line is no longer necessary. Also, -khtml is depreciated, so I eliminated that style as well.

Furthermore, IE's filters will not validate to w3c standards, so if you want your page to validate, separate your standards stylesheet from your IE stylesheet by using an if IE statement like below:

<!--[if IE]>
<link rel="stylesheet" type="text/css"  href="http://www.mysite.com/css/ie.css" />
<![endif]-->

If you separate the ie quirks, your site will validate just fine.

How can I check for an empty/undefined/null string in JavaScript?

It's a good idea too to check that you are not trying to pass an undefined term.

function TestMe() {
  if((typeof str != 'undefined') && str) {
    alert(str);
  }
 };

TestMe();

var str = 'hello';

TestMe();

I usually run into the case where I want to do something when a string attribute for an object instance is not empty. Which is fine, except that attribute is not always present.

"Javac" doesn't work correctly on Windows 10

Maybe a bit late, but i had same problem.

Click on "Move up" button for Java path and move it at top.

It fixed problem for me

dotnet ef not found in .NET Core 3

Global tools can be installed in the default directory or in a specific location. The default directories are:

  • Linux/macOS ---> $HOME/.dotnet/tools

  • Windows ---> %USERPROFILE%\.dotnet\tools

If you're trying to run a global tool, check that the PATH environment variable on your machine contains the path where you installed the global tool and that the executable is in that path.

Troubleshoot .NET Core tool usage issues

SQL Server default character encoding

The default character encoding for a SQL Server database is iso_1, which is ISO 8859-1. Note that the character encoding depends on the data type of a column. You can get an idea of what character encodings are used for the columns in a database as well as the collations using this SQL:

select data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name, count(*) count
from information_schema.columns
group by data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name;

If it's using the default, the character_set_name should be iso_1 for the char and varchar data types. Since nchar and nvarchar store Unicode data in UCS-2 format, the character_set_name for those data types is UNICODE.

How do I fix this "TypeError: 'str' object is not callable" error?

You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.

python int( ) function

import random
import time
import sys
while True:
    x=random.randint(1,100)
    print('''Guess my number--it's from 1 to 100.''')
    z=0
    while True:
        z=z+1
        xx=int(str(sys.stdin.readline()))
        if xx > x:
            print("Too High!")
        elif xx < x:
            print("Too Low!")
        elif xx==x:
            print("You Win!! You used %s guesses!"%(z))
            print()
            break
        else:
            break

in this, I first string the number str(), which converts it into an inoperable number. Then, I int() integerize it, to make it an operable number. I just tested your problem on my IDLE GUI, and it said that 49.8 < 50.

How to set DateTime to null

This should work:

if (!string.IsNullOrWhiteSpace(dateTimeEnd))
    eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
    eventCustom.DateTimeEnd = null;

Note that this will throw an exception if the string is not in the correct format.

AngularJs: Reload page

On Angular 1.5 - after trying some of the above solutions wanting to reload only the data with no full page refresh, I had problems with loading the data properly. I noticed though, that when I go to another route and then I return back to the current, everything works fine, but when I want to only reload the current route using $route.reload(), then some of the code is not executed properly. Then I tried to redirect to the current route in the following way:

$scope.someFuncName = function () {
    //go to another route
    $location.path('/another-route');
};

and in the module config, add another when:

.config(['$routeProvider', function($routeProvider) {
     $routeProvider.when('/first-page', {
         templateUrl: '/first-template',
         controller: 'SomeCtrl'
     }).when('/another-route', {//this is the new "when"
         redirectTo: '/first-page'
     });
}])

and it works just fine for me. It does not refresh the whole page, but only causes the current controller and template to reload. I know it's a bit hacky, but that was the only solution I found.

Indirectly referenced from required .class file

I was getting this error:

The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files

Doing the following fixed it for me:

Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK

How can I add a new column and data to a datatable that already contains data?

Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";

How can I parse a time string containing milliseconds in it with python?

To give the code that nstehr's answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to merge a transparent png image with another image using PIL

Image.paste does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.

Pillow 2.0 contains an alpha_composite function that does this.

background = Image.open("test1.png")
foreground = Image.open("test2.png")

Image.alpha_composite(background, foreground).save("test3.png")

EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA') if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).

invalid use of incomplete type

Not exactly what you were asking, but you can make action a template member function:

template<typename Subclass>
class A {
    public:
        //Why doesn't it like this?
        template<class V> void action(V var) {
                (static_cast<Subclass*>(this))->do_action();
        }
};

class B : public A<B> {
    public:
        typedef int mytype;

        B() {}

        void do_action(mytype var) {
                // Do stuff
        }
};

int main(int argc, char** argv) {
    B myInstance;
    return 0;
}

How can I convert a comma-separated string to an array?

Note that the following:

var a = "";
var x = new Array();
x = a.split(",");
alert(x.length);

will alert 1

PHPmailer sending HTML CODE

all you need to do is just add $mail->IsHTML(true); to the code it works fine..

Port 80 is being used by SYSTEM (PID 4), what is that?

This can be very easily fixed by following these five steps:

  1. Open services
  2. Right click on World Wide Web Publishing Service
  3. Click STOP

To prevent this issue in future :

  1. Go to Properties
  2. Change Startup type to Manual

Viola u are good to go !

Get top n records for each group of grouped results

Snuffin solution seems quite slow to execute when you've got plenty of rows and Mark Byers/Rick James and Bluefeet solutions doesn't work on my environnement (MySQL 5.6) because order by is applied after execution of select, so here is a variant of Marc Byers/Rick James solutions to fix this issue (with an extra imbricated select):

select person, groupname, age
from
(
    select person, groupname, age,
    (@rn:=if(@prev = groupname, @rn +1, 1)) as rownumb,
    @prev:= groupname 
    from 
    (
        select person, groupname, age
        from persons 
        order by groupname ,  age desc, person
    )   as sortedlist
    JOIN (select @prev:=NULL, @rn :=0) as vars
) as groupedlist 
where rownumb<=2
order by groupname ,  age desc, person;

I tried similar query on a table having 5 millions rows and it returns result in less than 3 seconds

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

Change name of folder when cloning from GitHub?

You can do this.

git clone https://github.com/sferik/sign-in-with-twitter.git signin

refer the manual here

nginx error connect to php5-fpm.sock failed (13: Permission denied)

If you have declarations

pid = /run/php-fpm.pid

and

listen = /run/php-fpm.pid

in different configuration files, then root will owner of this file.

Button Listener for button in fragment in android

While you are declaring onclick in XML then you must declair method and pass View v as parameter and make the method public...

Ex:
//in xml
android:onClick="onButtonClicked"


// in java file
public void onButtonClicked(View v)
{
//your code here
}

In which case do you use the JPA @JoinTable annotation?

It's the only solution to map a ManyToMany association : you need a join table between the two entities tables to map the association.

It's also used for OneToMany (usually unidirectional) associations when you don't want to add a foreign key in the table of the many side and thus keep it independent of the one side.

Search for @JoinTable in the hibernate documentation for explanations and examples.

How do I concatenate text in a query in sql server?

If you are using SQL Server 2005 or greater, depending on the size of the data in the Notes field, you may want to consider casting to nvarchar(max) instead of casting to a specific length which could result in string truncation.

Select Cast(notes as nvarchar(max)) + 'SomeText' From NotesTable a

AngularJS ng-click to go to another page (with Ionic framework)

If you simply want to go to another page, then what you might need is a link that looks like a button with a href like so:

<a href="/#/somepage.html" class="button">Back to Listings</a>

Hope this helps.

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

How to open a PDF file in an <iframe>?

Using an iframe to "render" a PDF will not work on all browsers; it depends on how the browser handles PDF files. Some browsers (such as Firefox and Chrome) have a built-in PDF rendered which allows them to display the PDF inline where as some older browsers (perhaps older versions of IE attempt to download the file instead).

Instead, I recommend checking out PDFObject which is a Javascript library to embed PDFs in HTML files. It handles browser compatibility pretty well and will most likely work on IE8.

In your HTML, you could set up a div to display the PDFs:

<div id="pdfRenderer"></div>

Then, you can have Javascript code to embed a PDF in that div:

var pdf = new PDFObject({
  url: "https://something.com/HTC_One_XL_User_Guide.pdf",
  id: "pdfRendered",
  pdfOpenParams: {
    view: "FitH"
  }
}).embed("pdfRenderer");

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

filter items in a python dictionary where keys contain a specific string

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

Importing project into Netbeans

Try copying the src and web folder in different folder location and create New project with existing sources in Netbeans. This should work. Or remove the nbproject folder as well before importing.

What is in your .vimrc?

The results of years of my meddling with vim are all here.

Hash function that produces short hashes?

You need to hash the contents to come up with a digest. There are many hashes available but 10-characters is pretty small for the result set. Way back, people used CRC-32, which produces a 33-bit hash (basically 4 characters plus one bit). There is also CRC-64 which produces a 65-bit hash. MD5, which produces a 128-bit hash (16 bytes/characters) is considered broken for cryptographic purposes because two messages can be found which have the same hash. It should go without saying that any time you create a 16-byte digest out of an arbitrary length message you're going to end up with duplicates. The shorter the digest, the greater the risk of collisions.

However, your concern that the hash not be similar for two consecutive messages (whether integers or not) should be true with all hashes. Even a single bit change in the original message should produce a vastly different resulting digest.

So, using something like CRC-64 (and base-64'ing the result) should get you in the neighborhood you're looking for.

How can I make window.showmodaldialog work in chrome 37?

I put the following javascript in the page header and it seems to work. It detects when the browser does not support showModalDialog and attaches a custom method that uses window.open, parses the dialog specs (height, width, scroll, etc.), centers on opener and sets focus back to the window (if focus is lost). Also, it uses the URL as the window name so that a new window is not opened each time. If you are passing window args to the modal you will need to write some additional code to fix that. The popup is not modal but at least you don't have to change a lot of code. Might need some work for your circumstances.

<script type="text/javascript">
  // fix for deprecated method in Chrome 37
  if (!window.showModalDialog) {
     window.showModalDialog = function (arg1, arg2, arg3) {

        var w;
        var h;
        var resizable = "no";
        var scroll = "no";
        var status = "no";

        // get the modal specs
        var mdattrs = arg3.split(";");
        for (i = 0; i < mdattrs.length; i++) {
           var mdattr = mdattrs[i].split(":");

           var n = mdattr[0];
           var v = mdattr[1];
           if (n) { n = n.trim().toLowerCase(); }
           if (v) { v = v.trim().toLowerCase(); }

           if (n == "dialogheight") {
              h = v.replace("px", "");
           } else if (n == "dialogwidth") {
              w = v.replace("px", "");
           } else if (n == "resizable") {
              resizable = v;
           } else if (n == "scroll") {
              scroll = v;
           } else if (n == "status") {
              status = v;
           }
        }

        var left = window.screenX + (window.outerWidth / 2) - (w / 2);
        var top = window.screenY + (window.outerHeight / 2) - (h / 2);
        var targetWin = window.open(arg1, arg1, 'toolbar=no, location=no, directories=no, status=' + status + ', menubar=no, scrollbars=' + scroll + ', resizable=' + resizable + ', copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
        targetWin.focus();
     };
  }
</script>

Setting active profile and config location from command line in spring boot

you can use the following command line:

java -jar -Dspring.profiles.active=[yourProfileName] target/[yourJar].jar

Reload activity in Android

i have same problem

import android.support.v4.content.IntentCompat;

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);

this code work for me . Android api 17

Converting dict to OrderedDict

Most of the time we go for OrderedDict when we required a custom order not a generic one like ASC etc.

Here is the proposed solution:

import collections
ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship


new_dict = collections.OrderedDict()
new_dict["NAME"]=ship["NAME"]
new_dict["HP"]=ship["HP"]
new_dict["BLASTERS"]=ship["BLASTERS"]
new_dict["THRUSTERS"]=ship["THRUSTERS"]
new_dict["PRICE"]=ship["PRICE"]


print new_dict

This will be output:

OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
OrderedDict([('NAME', 'Albatross'), ('HP', 50), ('BLASTERS', 13), ('THRUSTERS', 18), ('PRICE', 250)])

Note: The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.(official doc)

How to use a App.config file in WPF applications?

This also works

WpfApplication1.Properties.Settings.Default["appsetting"].ToString()

append multiple values for one key in a dictionary

d = {} 

# import list of year,value pairs

for year,value in mylist:
    try:
        d[year].append(value)
    except KeyError:
        d[year] = [value]

The Python way - it is easier to receive forgiveness than ask permission!

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

AngularJS + JQuery : How to get dynamic content working in angularjs

Another Solution in Case You Don't Have Control Over Dynamic Content

This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).

Wrap up Your Content

Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.

<div class="selector">
    <grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>

Use Angular Injector

You can use the following code to get a reference to $compile if you don't have one.

$(".selector").each(function () {
    var content = $(this);
    angular.element(document).injector().invoke(function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    });
});

Summary

The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.

One Caveat of the previous code

If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.

Here is the way to remedy it:

Replace the prevous code snippet with the following overload.

...
angular.element(document).injector().invoke(
[
    "$compile", function($compile) {
        var scope = angular.element(content).scope();
        $compile(content)(scope);
    }
]);
...

This caused a lot of grief for me before I pieced it together.

No module named serial

Serial is not included with Python. It is a package that you'll need to install separately.

Since you have pip installed you can install serial from the command line with:

pip install pyserial

Or, you can use a Windows installer from here. It looks like you're using Python 3 so click the installer for Python 3.

Then you should be able to import serial as you tried before.

Issue pushing new code in Github

This error occurs when you push the data from your local directory to your remote git repository by following git command: git push -u origin master

As local directory and git remote directory's files conflicted.

Solution :

After committing all files to staging follow below steps.

  1. Fetch the files from the remote repository as its conflict with the local working directory.

    • git pull <remoter-url> <branch-name>
  2. Commit the changes again.

    • git add -A
    • git commit -m ‘<comment>'
  3. After committed merge files with both directory you can use

    • git push -u origin master

This will fix the issue. Thanks.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

  1. Download gecko driver from the seleniumhq website (Now it is on GitHub and you can download it from Here) .
    1. You will have a zip (or tar.gz) so extract it.
    2. After extraction you will have geckodriver.exe file (appropriate executable in linux).
    3. Create Folder in C: named SeleniumGecko (Or appropriate)
    4. Copy and Paste geckodriver.exe to SeleniumGecko
    5. Set the path for gecko driver as below

.

System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

Truncate a string straight JavaScript

_x000D_
_x000D_
var pa = document.getElementsByTagName('p')[0].innerHTML;_x000D_
var rpa = document.getElementsByTagName('p')[0];_x000D_
// console.log(pa.slice(0, 30));_x000D_
var newPa = pa.slice(0, 29).concat('...');_x000D_
rpa.textContent = newPa;_x000D_
console.log(newPa)
_x000D_
<p>_x000D_
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to open Console window in Eclipse?

The "trim stack" is a vertical icon bar that should appear, if it isn't there already, on one side of the main window. Back when this answer was originally written, it was down the left hand side (of which I had a screen shot that unfortunately was uploaded to some image paste bin place and not Stack Overflow, then linked, and has since been lost). Not being much of an eclipse user currently I don't know if this is still the case.

It contains icons for each sub-window that is minimized, so if none of them are minimized, there is no trim stack. Try minimizing the Package Explorer/Navigator window and you should see it appear. You can then click the "Restore" icon (the overlapping squares at the top) in the trim stack to get the window back.

BUT -- and it's not consistent -- sometimes with Eclipse Juno when the window with the Console, etc, is minimized and there is no trim stack, the trim stack doesn't appear and using "Show View" does nothing. The way around that I've found is to minimize some other window, then the trim stack appears and the Console icon (blue & white monitor square) appears. Click that and the Console, etc. appears in a pop-up. Click the Restore icon in that pop-up and it will become part of the main window again.

Changing the current working directory in Java?

Use FileSystemView

private FileSystemView fileSystemView;
fileSystemView = FileSystemView.getFileSystemView();
currentDirectory = new File(".");
//listing currentDirectory
File[] filesAndDirs = fileSystemView.getFiles(currentDirectory, false);
fileList = new ArrayList<File>();
dirList = new ArrayList<File>();
for (File file : filesAndDirs) {
if (file.isDirectory())
    dirList.add(file);
else
    fileList.add(file);
}
Collections.sort(dirList);
if (!fileSystemView.isFileSystemRoot(currentDirectory))
    dirList.add(0, new File(".."));
Collections.sort(fileList);
//change
currentDirectory = fileSystemView.getParentDirectory(currentDirectory);

MySQL - force not to use cache for testing speed of query

You can also run the follow command to reset the query cache.

RESET QUERY CACHE

How to find the extension of a file in C#?

private string GetExtension(string attachment_name)
{
    var index_point = attachment_name.IndexOf(".") + 1;
    return attachment_name.Substring(index_point);
}

How to print something to the console in Xcode?

You can also use breakpoints. Assuming the value you want is defined within the scope of your breakpoint you have 3 options:

print it in console doing:

po some_paramter

Bare in mind in objective-c for properties you can't use self.

po _someProperty
po self.someProperty // would not work

po stands for print object.


Or can just use Xcode 'Variable Views' . See the image enter image description here

I highly recommend seeing Debugging with Xcode from Apple


Or just hover over within your code. Like the image below.

enter image description here

How to find memory leak in a C++ code/project?

You can use the tool Valgrind to detect memory leaks.

Also, to find the leak in a particular function, use exit(0) at the end of the function and then run it with Valgrind

`$` valgrind ./your_CPP_program 

How to run bootRun with spring profile via gradle task

In your build.gradle file simply use the following snippet

bootRun {
  args = ["--spring.profiles.active=${project.properties['profile'] ?: 'prod'}"]
}

And then run following command to use dev profile:

./gradlew bootRun -Pprofile=dev

Does a finally block always get executed in Java?

That's actually true in any language...finally will always execute before a return statement, no matter where that return is in the method body. If that wasn't the case, the finally block wouldn't have much meaning.

How to replace ${} placeholders in a text file?

I found this thread while wondering the same thing. It inspired me to this (careful with the backticks)

$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world

Git error when trying to push -- pre-receive hook declined

In my case I got this error because a branch with the same name already existed. Deleting this branch off of the git server will fix this.

gnuplot plotting multiple line graphs

In addition to the answers above the command below will also work. I post it because it makes more sense to me. In each case it is 'using x-value-column: y-value-column'

plot 'ls.dat' using 1:2, 'ls.dat' using 1:3, 'ls.dat' using 1:4 

note that the command above assumes that you have a file named ls.dat with tab separated columns of data where column 1 is x, column 2 is y1, column 3 is y2 and column 4 is y3.

How do I set a checkbox in razor view?

If we set "true" in model, It'll always true. But we want to set option value for my checkbox we can use this. Important in here is The name of checkbox "AllowRating", It's must name of var in model if not when we post the value not pass in Database. form of it:

@Html.CheckBox("NameOfVarInModel", true) ;

for you!

@Html.CheckBox("AllowRating", true) ;

Make an Android button change background on click through XML

public void methodOnClick(View view){

Button.setBackgroundResource(R.drawable.nameImage);

}

i recommend use button inside LinearLayout for adjust to size of Linear.

Matching special characters and letters in regex

Add them to the allowed characters, but you'll need to escape some of them, such as -]/\

var pattern = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/

That way you can remove any individual character you want to disallow.

Also, you want to include the start and end of string placemarkers ^ and $

Update:

As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._

/^[\w&.\-]+$/

[\w] is the same as [a-zA-Z0-9_]

Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:

/^[\w&.\-]*$/

BeanFactory vs ApplicationContext

ApplicationContext is a big brother of BeanFactory and this would all thing that BeanFactory are provide plus many other things.

In addition to standard org.springframework.beans.factory.BeanFactory lifecycle capabilities, ApplicationContext implementations detect and invoke ApplicationContextAware beans as well as ResourceLoaderAware, ApplicationEventPublisherAware and MessageSourceAware beans.

<ng-container> vs <template>

Imo use cases for ng-container are simple replacements for which a custom template/component would be overkill. In the API doc they mention the following

use a ng-container to group multiple root nodes

and I guess that's what it is all about: grouping stuff.

Be aware that the ng-container directive falls away instead of a template where its directive wraps the actual content.

jquery animate .css

You can actually still use ".css" and apply css transitions to the div being affected. So continue using ".css" and add the below styles to your stylesheet for "#hfont1". Since ".css" allows for a lot more properties than ".animate", this is always my preferred method.

#hfont1 {
    -webkit-transition: width 0.4s;
    transition: width 0.4s;
}

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is window.onload event.

Below is a simple script that I created to run a counter. The counter then stops after 10 iterations

window.onload=function()
{
    var counter = 0;
    var interval1 = setInterval(function()
    { 
        document.getElementById("div1").textContent=counter;
        counter++; 
        if(counter==10)
        {
            clearInterval(interval1);
        }
    },1000);

}

How do I float a div to the center?

if you are using width and height, you should try margin-right: 45%;... it is 100% working for me.. so i can take it to anywhere with percentage!

PHP + MySQL transactions examples

<?php

// trans.php
function begin(){
    mysql_query("BEGIN");
}

function commit(){
    mysql_query("COMMIT");
}

function rollback(){
    mysql_query("ROLLBACK");
}

mysql_connect("localhost","Dude1", "SuperSecret") or die(mysql_error());

mysql_select_db("bedrock") or die(mysql_error());

$query = "INSERT INTO employee (ssn,name,phone) values ('123-45-6789','Matt','1-800-555-1212')";

begin(); // transaction begins

$result = mysql_query($query);

if(!$result){
    rollback(); // transaction rolls back
    echo "transaction rolled back";
    exit;
}else{
    commit(); // transaction is committed
    echo "Database transaction was successful";
}

?>

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

I guess the best way to do this is like this :

  1. Store all your changes in a separate branch.
  2. Then do a hard reset on the local master.
  3. Then merge back your changes from the locally created branch
  4. Then commit and push your changes.

That how I resolve mine, whenever it happens.

Include jQuery in the JavaScript Console

Per this answer:

fetch('https://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => eval(r))

For some reason I have to execute it twice to get the new '$' (which I have to do with the other methods as well), but it works.

This is the equivalent if your browser isn't so modern:

fetch('http://code.jquery.com/jquery-latest.min.js').then(function(r){return r.text()}).then(function(r){eval(r)})

How to save an image locally using Python whose URL address I already know?

import urllib
resource = urllib.urlopen("http://www.digimouth.com/news/media/2011/09/google-logo.jpg")
output = open("file01.jpg","wb")
output.write(resource.read())
output.close()

file01.jpg will contain your image.

Command not found after npm install in zsh

I think the problem is more about the ZSH completion.

You need to add this line in your .zshrc:

zstyle ':completion:*' rehash true

If you have Oh-my-zsh, a PR has been made, you can integrate it until it is pulled: https://github.com/robbyrussell/oh-my-zsh/issues/3440

Removing the remembered login and password list in SQL Server Management Studio

There is a really simple way to do this using a more recent version of SQL Server Management Studio (I'm using 18.4)

  1. Open the "Connect to Server" dialog
  2. Click the "Server Name" dropdown so it opens
  3. Press the down arrow on your keyboard to highlight a server name
  4. Press delete on your keyboard

Login gone! No messing around with dlls or bin files.

jQuery & CSS - Remove/Add display:none

jQuery provides you with:

$(".news").hide();
$(".news").show();

You can then easily show and hide the element(s).

Why is the use of alloca() not considered good practice?

One pitfall with alloca is that longjmp rewinds it.

That is to say, if you save a context with setjmp, then alloca some memory, then longjmp to the context, you may lose the alloca memory. The stack pointer is back where it was and so the memory is no longer reserved; if you call a function or do another alloca, you will clobber the original alloca.

To clarify, what I'm specifically referring to here is a situation whereby longjmp does not return out of the function where the alloca took place! Rather, a function saves context with setjmp; then allocates memory with alloca and finally a longjmp takes place to that context. That function's alloca memory is not all freed; just all the memory that it allocated since the setjmp. Of course, I'm speaking about an observed behavior; no such requirement is documented of any alloca that I know.

The focus in the documentation is usually on the concept that alloca memory is associated with a function activation, not with any block; that multiple invocations of alloca just grab more stack memory which is all released when the function terminates. Not so; the memory is actually associated with the procedure context. When the context is restored with longjmp, so is the prior alloca state. It's a consequence of the stack pointer register itself being used for allocation, and also (necessarily) saved and restored in the jmp_buf.

Incidentally, this, if it works that way, provides a plausible mechanism for deliberately freeing memory that was allocated with alloca.

I have run into this as the root cause of a bug.

How to use absolute path in twig functions

From Symfony2 documentation: Absolute URLs for assets were introduced in Symfony 2.5.

If you need absolute URLs for assets, you can set the third argument (or the absolute argument) to true:

Example:

<img src="{{ asset('images/logo.png', absolute=true) }}" alt="Symfony!" />

Remove the legend on a matplotlib figure

If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df2 = pd.DataFrame(np.random.randn(10, 5))
df2.plot(legend=None)
plt.show()

What's the whole point of "localhost", hosts and ports at all?

Localhost generally refers to the machine you're looking at. On most machines localhost resolves to the IP address 127.0.0.1 which is the loopback address.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Python strptime() and timezones?

Ran into this exact problem.

What I ended up doing:

# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'

# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)

# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))

# set timezone
import pendulum
tz = pendulum.timezone('utc')

dt_tz = datetime(*dt_vals,tzinfo=tz)

JQuery - Call the jquery button click event based on name property

You can use normal CSS selectors to select an element by name using jquery. Like this:

Button Code
<button type="button" name="mybutton">Click Me!</button>

Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

In my case, it was that the app had defaulted to a Wearable target device.

I removed the reference to Wearable in my Manifest, and the problem was solved.

<uses-library android:name="com.google.android.wearable" android:required="true" />

Two column div layout with fluid left and fixed right column

Here's a solution (and it has some quirks, but let me know if you notice them and that they're a concern):

<div>
    <div style="width:200px;float:left;display:inline-block;">
        Hello world
    </div>
    <div style="margin-left:200px;">
        Hello world
    </div>
</div>

In an array of objects, fastest way to find the index of an object whose attributes match a search

array.forEach(function (elem, i) {  // iterate over all elements of array
    indexes[elem.id] = i;           // take the found id as index for the
});                                 // indexes array and assign i

the result is a look up list for the id. with the given id we get the index of the record.

Insert multiple lines into a file after specified pattern using shell script

You can use awk for inserting output of some command in the middle of input.txt.
The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.

awk 'NR==FNR {a[NR]=$0;next}
    {print}
    /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
    <(printf "%s\n" line{1..4}) input.txt

Adding a directory to PATH in Ubuntu

Actually I would advocate .profile if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc is fine, though.

How to round an image with Glide library?

Roman Samoylenko's answer was correct except the function has changed. The correct answer is

Glide.with(context)
                .load(yourImage)
                .apply(RequestOptions.circleCropTransform())
                .into(imageView);

jQuery - get all divs inside a div with class ".container"

To set the class when clicking on a div immediately within the .container element, you could use:

<script>
$('.container>div').click(function () {
        $(this).addClass('whatever')
    });
</script>

Is there a way to create and run javascript in Chrome?

You should write in file:

<script>
     //write your JavaScript code here
</script>

save it with .html extension and open with browser.

For example:

// this is test.html
<script>
   alert("Hello");
   var a = 5;
   function incr(arg){
       arg++;
       return arg;
   }       
   alert(a);
</script>

Insert node at a certain position in a linked list C++

Node* insert_node_at_nth_pos(Node *head, int data, int position)
{   
    /* current node */
    Node* cur = head;

    /* initialize new node to be inserted at given position */
    Node* nth = new Node;
    nth->data = data;
    nth->next = NULL;

    if(position == 0){
        /* insert new node at head */
        head = nth;
        head->next = cur;
        return head;
    }else{
        /* traverse list */
        int count = 0;            
        Node* pre = new Node;

        while(count != position){
            if(count == (position - 1)){
                pre = cur;
            }
            cur = cur->next;            
            count++;
        }

        /* insert new node here */
        pre->next = nth;
        nth->next = cur;

        return head;
    }    
}

In Node.js, how do I turn a string to a json?

use the JSON function >

JSON.parse(theString)

How to compile a c++ program in Linux?

As the other answers say, use g++ instead of gcc.

Or use make: make hi

I can't install python-ldap

To install python-ldap successfully with pip, following development libraries are needed (package names taken from ubuntu environment):

sudo apt-get install -y python-dev libldap2-dev libsasl2-dev libssl-dev

How to trim white space from all elements in array?

Another java 8 lambda option :

String[] array2 = Arrays.stream(array).map(String::trim).toArray(String[]::new);

And the ugly but optimized version without new array creation

Arrays.stream(array).map(String::trim).toArray(unused -> array);

Original "array" is modified.

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

How can I get date in application run by node.js?

_x000D_
_x000D_
    var datetime = new Date();_x000D_
    console.log(datetime.toISOString().slice(0,10));
_x000D_
_x000D_
_x000D_

Where value in column containing comma delimited values

select *
from YourTable
where ','+replace(col, ' ', '')+',' like '%,Cat,%'

Actionbar notification count icon (badge) like Google has

Ok, for @AndrewS solution to work with v7 appCompat library:

<menu 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/saved_badge"
        someNamespace:showAsAction="always"
        android:icon="@drawable/shape_notification" />

</menu>

.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.main, menu);

    MenuItem item = menu.findItem(R.id.saved_badge);
    MenuItemCompat.setActionView(item, R.layout.feed_update_count);
    View view = MenuItemCompat.getActionView(item);
    notifCount = (Button)view.findViewById(R.id.notif_count);
    notifCount.setText(String.valueOf(mNotifCount));
}

private void setNotifCount(int count){
    mNotifCount = count;
    supportInvalidateOptionsMenu();
}

The rest of the code is the same.

How to set Spring profile from system variable?

My solution is to set the environment variable as spring.profiles.active=development. So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows

application.properties
system properties
environment variable

Unknown URL content://downloads/my_downloads

The exception is caused by disabled Download Manager. And there is no way to activate/deactivate Download Manager directly, since it's system application and we don't have access to it.

Only alternative way is redirect user to settings of Download Manager Application.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

} catch ( ActivityNotFoundException e ) {
     e.printStackTrace();

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

This problem cost me one whole day. I finally downgraded the firebase-ui library version from 2.0.0 to 1.2.0 and added the following code inside Project level build.gradle file:

allprojects {
    repositories {
        jcenter()

        // Add the following code to your project level build.gradle
        maven {
            url 'https://maven.fabric.io/public'
        }
    }
}

Use CSS3 transitions with gradient backgrounds

Partial workaround for gradient transition is to use inset box shadow - you can transition either the box shadow itself, or the background color - e.g. if you create inset box shadow of the same color as background and than use transition on background color, it creates illusion that plain background is changing to radial gradient

.button SPAN {
    padding: 10px 30px; 
    border: 1px solid ##009CC5;

    -moz-box-shadow: inset 0 0 20px 1px #00a7d1;
    -webkit-box-shadow: inset 0 0 20px 1px#00a7d1;
    box-shadow: inset 0 0 20px 1px #00a7d1; 

    background-color: #00a7d1;
    -webkit-transition: background-color 0.5s linear;
    -moz-transition: background-color 0.5s linear;
    -o-transition: background-color 0.5s linear;
    transition: background-color 0.5s linear;
}

.button SPAN:hover {
    background-color: #00c5f7; 
}

Android refresh current activity

It should start again and delete all the instances of previous current activity.

No, it shouldn't.

It should update its data in place (e.g., requery() the Cursor). Then there will be no "instances of previous current activity" to worry about.

Css Move element from left to right animated

It's because you aren't giving the un-hovered state a right attribute.

right isn't set so it's trying to go from nothing to 0px. Obviously because it has nothing to go to, it just 'warps' over.

If you give the unhovered state a right:90%;, it will transition how you like.

Just as a side note, if you still want it to be on the very left of the page, you can use the calc css function.

Example:

right: calc(100% - 100px)
                     ^ width of div

You don't have to use left then.

Also, you can't transition using left or right auto and will give the same 'warp' effect.

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
    background:red;_x000D_
    transition:2s;_x000D_
    -webkit-transition:2s;_x000D_
    -moz-transition:2s;_x000D_
    position:absolute;_x000D_
    right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
  right:0;_x000D_
}
_x000D_
<p>_x000D_
  <b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
_x000D_
_x000D_

CanIUse says that the calc() function only works on IE10+

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

What does "where T : class, new()" mean?

It's called a 'constraint' on the generic parameter T. It means that T must be a reference type (a class) and that it must have a public default constructor.

how to use jQuery ajax calls with node.js

Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

This is my Client Side code.

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});

This is my Server side Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

Is there a way to get version from package.json in nodejs code?

If using rollup, the rollup-plugin-replace plugin can be used to add the version without exposing package.json to the client.

// rollup.config.js

import pkg from './package.json';
import { terser } from "rollup-plugin-terser";
import resolve from 'rollup-plugin-node-resolve';
import commonJS from 'rollup-plugin-commonjs'
import replace from 'rollup-plugin-replace';

export default {
  plugins: [
    replace({
      exclude: 'node_modules/**',
      'MY_PACKAGE_JSON_VERSION': pkg.version, // will replace 'MY_PACKAGE_JSON_VERSION' with package.json version throughout source code
    }),
  ]
};

Then, in the source code, anywhere where you want to have the package.json version, you would use the string 'MY_PACKAGE_JSON_VERSION'.

// src/index.js
export const packageVersion = 'MY_PACKAGE_JSON_VERSION' // replaced with actual version number in rollup.config.js

Sprintf equivalent in Java

You can do a printf to anything that is an OutputStream with a PrintStream. Somehow like this, printing into a string stream:

PrintStream ps = new PrintStream(baos);
ps.printf("there is a %s from %d %s", "hello", 3, "friends");
System.out.println(baos.toString());
baos.reset(); //need reset to write new string
ps.printf("there is a %s from %d %s", "flip", 5, "haters");
System.out.println(baos.toString());
baos.reset();

The string stream can be created like this ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();

How to increase MySQL connections(max_connections)?

If you need to increase MySQL Connections without MySQL restart do like below

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 100   |
+-----------------+-------+
1 row in set (0.00 sec)

mysql> SET GLOBAL max_connections = 150;
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 150   |
+-----------------+-------+
1 row in set (0.00 sec)

These settings will change at MySQL Restart.


For permanent changes add below line in my.cnf and restart MySQL

max_connections = 150

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

Is your MySQL server version 5.5.3 or greater?

The utf8mb4, utf16, and utf32 character sets were added in MySQL 5.5.3.

http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-sets.html

Is it possible to set a timeout for an SQL query on Microsoft SQL server?

It sounds like more of an architectual issue, and any timeout/disconnect you can do would be more or less a band-aid. This has to be solved on SQL server side, by the way of read-only replica, transaction log shipping (to give you a read-only server to connect to), replication and such. Basically you give the DMZ sql server that heavy read can go to without killing stuff. This is very common. A well-designed SQL system won't be taken down by DDoS - that'd be like a car that dies if you step on the gas.

That said, if you are at the liberty to change the code, you could guesstimate if the query is too heavy and you could either reject or return only X rows in your stored procedure. If you are mated to some reporting tool and such and can't control the SELECT it generates, you could point it to a view and then do the safety valve in the view.

Also, if up-to-the-minute freshness isn't critical and you could compromise on that, like monthly sales data, then compiling a physical table of complex joins by job to avoid complex joins might do the trick - that way everything would be sub-second per query.

It entirely depends on what you are doing, but there is always a solution. Sometimes it takes extra coding to optimize it, sometimes it takes extra money to get you the secondary read-only DB, sometimes it needs time and attention in index tuning.

So it entirely depends, but I'd start with "what can I compromise? what can I change?" and go from there.

Background color not showing in print preview

FOR THOSE USING BOOTSTRAP.CSS, this is the fix!

I have tried all the solutions and they weren't working... until I discovered that bootstrap.css had a super annoying @media print that resets all your colors, background-colors, shadows, etc...

@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}

So either remove this section from bootstrap.css (or bootstrap.min.css)

Or override these values in the css of the page you want to print in your own @media print

@media print {
  body { 
    -webkit-print-color-adjust: exact; 
  }
  .customClass{
     //customCss + !important;
  }
  //more of your custom css
}

How to find out if you're using HTTPS without $_SERVER['HTTPS']

I know this answer is late, but I combined a bunch of answers and made a simple function that works for all use cases.

Try this:

function is_ssl(){
if(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO']=="https"){ return true; }
elseif(isset($_SERVER['HTTPS'])){ return true; }
elseif($_SERVER['SERVER_PORT'] == 443){ return true; }
else{ return false; }
}

Then just use if, for example:

if(is_ssl()){
// WHAT TO DO IF IT IS SSL / HTTPS
}else{
// WHAT TO DO IF IT IS NOT SSL / HTTPS
}

This code works with Cloudflare, shared hosting providers, etc.

Enjoy.

Activity has leaked window that was originally added

Try below code , it will work any time you will dismiss the progress dialogue and it will see whether its instance is available or not.

try {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Is there any way to do HTTP PUT in python

You can use requests.request

import requests

url = "https://www.example/com/some/url/"
payload="{\"param1\": 1, \"param1\": 2}"
headers = {
  'Authorization': '....',
  'Content-Type': 'application/json'
}

response = requests.request("PUT", url, headers=headers, data=payload)

print(response.text)

Angular is automatically adding 'ng-invalid' class on 'required' fields

Since the inputs are empty and therefore invalid when instantiated, Angular correctly adds the ng-invalid class.

A CSS rule you might try:

input.ng-dirty.ng-invalid {
  color: red
}

Which basically states when the field has had something entered into it at some point since the page loaded and wasn't reset to pristine by $scope.formName.setPristine(true) and something wasn't yet entered and it's invalid then the text turns red.

Other useful classes for Angular forms (see input for future reference )

ng-valid-maxlength - when ng-maxlength passes
ng-valid-minlength - when ng-minlength passes
ng-valid-pattern - when ng-pattern passes
ng-dirty - when the form has had something entered since the form loaded
ng-pristine - when the form input has had nothing inserted since loaded (or it was reset via setPristine(true) on the form)
ng-invalid - when any validation fails (required, minlength, custom ones, etc)

Likewise there is also ng-invalid-<name> for all these patterns and any custom ones created.

How to get full width in body element

You should set body and html to position:fixed;, and then set right:, left:, top:, and bottom: to 0;. That way, even if content overflows it will not extend past the limits of the viewport.

For example:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

JS Fiddle Example

Caveat: Using this method, if the user makes their window smaller, content will be cut off.

How do I stretch a background image to cover the entire HTML element?

image{

background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  padding: 0 3em 0 3em; 
margin: -1.5em -0.5em -0.5em -1em; 
  width: absolute;
  max-width: 100%; 

What is the most efficient string concatenation method in python?

''.join(sequenceofstrings) is what usually works best -- simplest and fastest.

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

How do I make a fully statically linked .exe with Visual Studio Express 2005?

I've had this same dependency problem and I also know that you can include the VS 8.0 DLLs (release only! not debug!---and your program has to be release, too) in a folder of the appropriate name, in the parent folder with your .exe:

How to: Deploy using XCopy (MSDN)

Also note that things are guaranteed to go awry if you need to have C++ and C code in the same statically linked .exe because you will get linker conflicts that can only be resolved by ignoring the correct libXXX.lib and then linking dynamically (DLLs).

Lastly, with a different toolset (VC++ 6.0) things "just work", since Windows 2000 and above have the correct DLLs installed.

Why does Date.parse give incorrect results?

There is some method to the madness. As a general rule, if a browser can interpret a date as an ISO-8601, it will. "2005-07-08" falls into this camp, and so it is parsed as UTC. "Jul 8, 2005" cannot, and so it is parsed in the local time.

See JavaScript and Dates, What a Mess! for more.

How can I create a keystore?

I was crazy looking how to generate a .keystore using in the shell a single line command, so I could run it from another application. This is the way:

echo y | keytool -genkeypair -dname "cn=Mark Jones, ou=JavaSoft, o=Sun, c=US" -alias business -keypass kpi135 -keystore /working/android.keystore -storepass ab987c -validity 20000
  • dname is a unique identifier for the application in the .keystore

    • cn the full name of the person or organization that generates the .keystore
    • ou Organizational Unit that creates the project, its a subdivision of the Organization that creates it. Ex. android.google.com
    • o Organization owner of the whole project. Its a higher scope than ou. Ex.: google.com
    • c The country short code. Ex: For United States is "US"
  • alias Identifier of the app as an single entity inside the .keystore (it can have many)

  • keypass Password for protecting that specific alias.
  • keystore Path where the .keystore file shall be created (the standard extension is actually .ks)
  • storepass Password for protecting the whole .keystore content.
  • validity Amout of days the app will be valid with this .keystore

It worked really well for me, it doesnt ask for anything else in the console, just creates the file. For more information see keytool - Key and Certificate Management Tool.

Why is an OPTIONS request sent and can I disable it?

One solution I have used in the past - lets say your site is on mydomain.com, and you need to make an ajax request to foreigndomain.com

Configure an IIS rewrite from your domain to the foreign domain - e.g.

<rewrite>
  <rules>
    <rule name="ForeignRewrite" stopProcessing="true">
        <match url="^api/v1/(.*)$" />
        <action type="Rewrite" url="https://foreigndomain.com/{R:1}" />
    </rule>
  </rules>
</rewrite>

on your mydomain.com site - you can then make a same origin request, and there's no need for any options request :)

ssh: The authenticity of host 'hostname' can't be established

Add these to your /etc/ssh/ssh_config

Host *
UserKnownHostsFile=/dev/null
StrictHostKeyChecking=no

How to call base.base.method()?

This is a bad programming practice, and not allowed in C#. It's a bad programming practice because

  • The details of the grandbase are implementation details of the base; you shouldn't be relying on them. The base class is providing an abstraction overtop of the grandbase; you should be using that abstraction, not building a bypass to avoid it.

  • To illustrate a specific example of the previous point: if allowed, this pattern would be yet another way of making code susceptible to brittle-base-class failures. Suppose C derives from B which derives from A. Code in C uses base.base to call a method of A. Then the author of B realizes that they have put too much gear in class B, and a better approach is to make intermediate class B2 that derives from A, and B derives from B2. After that change, code in C is calling a method in B2, not in A, because C's author made an assumption that the implementation details of B, namely, that its direct base class is A, would never change. Many design decisions in C# are to mitigate the likelihood of various kinds of brittle base failures; the decision to make base.base illegal entirely prevents this particular flavour of that failure pattern.

  • You derived from your base because you like what it does and want to reuse and extend it. If you don't like what it does and want to work around it rather than work with it, then why did you derive from it in the first place? Derive from the grandbase yourself if that's the functionality you want to use and extend.

  • The base might require certain invariants for security or semantic consistency purposes that are maintained by the details of how the base uses the methods of the grandbase. Allowing a derived class of the base to skip the code that maintains those invariants could put the base into an inconsistent, corrupted state.

SQL how to check that two tables has exactly the same data?

You can find differences of 2 tables using combination of insert all and full outer join in Oracle. In sql you can extract the differences via full outer join but it seems that insert all/first doesnt exist in sql! Hence, you have to use following query instead:

select * from A
full outer join B on
A.pk=B.pk
where A.field1!=B.field1
or A.field2!=B.field2 or A.field3!=B.field3 or A.field4!=B.field4 
--and A.Date==Date1

Although using 'OR' in where clause is not recommended and it usually yields in lower performance, you can still use above query if your tables are not massive. If there is any result for the above query, it is exactly the differences of 2 tables based on comparison of fields 1,2,3,4. For improving the query performance, you can filter it by date as well(check the commented part)

explicit casting from super class to subclass

Elaborating the answer given by Michael Berry.

Dog d = (Dog)Animal; //Compiles but fails at runtime

Here you are saying to the compiler "Trust me. I know d is really referring to a Dog object" although it's not. Remember compiler is forced to trust us when we do a downcast.

The compiler only knows about the declared reference type. The JVM at runtime knows what the object really is.

So when the JVM at the runtime figures out that the Dog d is actually referring to an Animal and not a Dog object it says. Hey... you lied to the compiler and throws a big fat ClassCastException.

So if you are downcasting you should use instanceof test to avoid screwing up.

if (animal instanceof Dog) { Dog dog = (Dog) animal; }

Now a question comes to our mind. Why the hell compiler is allowing the downcast when eventually it is going to throw a java.lang.ClassCastException?

The answer is that all the compiler can do is verify that the two types are in the same inheritance tree, so depending on whatever code might have come before the downcast, it's possible that animal is of type dog.

The compiler must allow things that might possible work at runtime.

Consider the following code snipet:

public static void main(String[] args) 
{   
    Dog d = getMeAnAnimal();// ERROR: Type mismatch: cannot convert Animal to Dog
    Dog d = (Dog)getMeAnAnimal(); // Downcast works fine. No ClassCastException :)
    d.eat();

}

private static Animal getMeAnAnimal()
{
    Animal animal = new Dog();
    return animal;
}

However, if the compiler is sure that the cast would not possible work, compilation will fail. I.E. If you try to cast objects in different inheritance hierarchies

String s = (String)d; // ERROR : cannot cast for Dog to String

Unlike downcasting, upcasting works implicitly because when you upcast you are implicitly restricting the number of method you can invoke, as opposite to downcasting, which implies that later on, you might want to invoke a more specific method.

Dog d = new Dog(); Animal animal1 = d; // Works fine with no explicit cast Animal animal2 = (Animal) d; // Works fine with n explicit cast

Both of the above upcast will work fine without any exception because a Dog IS-A Animal, anithing an Animal can do, a dog can do. But it's not true vica-versa.

Invalid application of sizeof to incomplete type with a struct

It means the file containing main doesn't have access to the player structure definition (i.e. doesn't know what it looks like).

Try including it in header.h or make a constructor-like function that allocates it if it's to be an opaque object.

EDIT

If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:

struct player *
init_player(...)
{
    struct player *p = calloc(1, sizeof *p);

    /* ... */
    return p;
}

However if the implementation shouldn't be hidden - i.e. main should legally say p->canPlay = 1 it would be better to put the definition of the structure in header.h.

How to increase the vertical split window size in Vim

I am using numbers to resize by mapping the following in .vimrc

nmap 7 :res +2<CR> " increase pane by 2 
nmap 8 :res -2<CR> " decrease pane by 2
nmap 9 :vertical res +2<CR> " vertical increase pane by 2
nmap 0 :vertical res -2<CR> " vertical decrease pane by 2