Programs & Examples On #Atomic values

Anything related to atomic values, i.e. values on which accesses and updates are guaranteed to happen atomically, that is without being interrupted by another thread of execution.

What is the role of "Flatten" in Keras?

short read:

Flattening a tensor means to remove all of the dimensions except for one. This is exactly what the Flatten layer do.

long read:

If we take the original model (with the Flatten layer) created in consideration we can get the following model summary:

Layer (type)                 Output Shape              Param #   
=================================================================
D16 (Dense)                  (None, 3, 16)             48        
_________________________________________________________________
A (Activation)               (None, 3, 16)             0         
_________________________________________________________________
F (Flatten)                  (None, 48)                0         
_________________________________________________________________
D4 (Dense)                   (None, 4)                 196       
=================================================================
Total params: 244
Trainable params: 244
Non-trainable params: 0

For this summary the next image will hopefully provide little more sense on the input and output sizes for each layer.

The output shape for the Flatten layer as you can read is (None, 48). Here is the tip. You should read it (1, 48) or (2, 48) or ... or (16, 48) ... or (32, 48), ...

In fact, None on that position means any batch size. For the inputs to recall, the first dimension means the batch size and the second means the number of input features.

The role of the Flatten layer in Keras is super simple:

A flatten operation on a tensor reshapes the tensor to have the shape that is equal to the number of elements contained in tensor non including the batch dimension.

enter image description here


Note: I used the model.summary() method to provide the output shape and parameter details.

Regular Expression for password validation

There seems to be a lot of confusion here. The answers I see so far don't correctly enforce the 1+ number/1+ lowercase/1+ uppercase rule, meaning that passwords like abc123, 123XYZ, or AB*&^# would still be accepted. Preventing all-lowercase, all-caps, or all-digits is not enough; you have to enforce the presence of at least one of each.

Try the following:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$

If you also want to require at least one special character (which is probably a good idea), try this:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$

The .{8,15} can be made more restrictive if you wish (for example, you could change it to \S{8,15} to disallow whitespace), but remember that doing so will reduce the strength of your password scheme.

I've tested this pattern and it works as expected. Tested on ReFiddle here: http://refiddle.com/110


Edit: One small note, the easiest way to do this is with 3 separate regexes and the string's Length property. It's also easier to read and maintain, so do it that way if you have the option. If this is for validation rules in markup, though, you're probably stuck with a single regex.

How to implement HorizontalScrollView like Gallery?

I implemented something similar with Horizontal Variable ListView The only drawback is, it works only with Android 2.3 and later.

Using this library is as simple as implementing a ListView with a corresponding Adapter. The library also provides an example

Check date with todays date

Android already has a dedicated class for this. Check DateUtils.isToday(long when)

How to hide the bar at the top of "youtube" even when mouse hovers over it?

You can try this it has worked for me.

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="//www.youtube.com/embed/PEwac2WZ7rU?rel=0?version=3&autoplay=1&controls=0&&showinfo=0&loop=1"></iframe>
</div>

Responsive embed using Bootstap

Allow browsers to determine video or slideshow dimensions based on the width of their containing block by creating an intrinsic ratio that will properly scale on any device.

Style youtube video:

  • Select a youtube video, click on Share and then Embed.
  • Select the embed code and copy it.
  • Start modifying after the verison=3 www.youtube.com/embed/VIDEOID?rel=0?version=3
  • Be sure to add a '&' between each item.
  • For autoplay: add "autoplay=1"
  • For loop: add "loop=1"
  • Hide the controls: add "controls=0"

For more information please visit this link https://developers.google.com/youtube/player_parameters#autoplay

Thanks
BanyanTheme

Run a PHP file in a cron job using CPanel

This works fine and also sends email:

/usr/bin/php /home/xxYourUserNamexx/public_html/xxYourFolderxx/xxcronfile.php

The following two commands also work fine but do not send email:

/usr/bin/php -f /home/Same As Above

php -f /home/Same As Above

Make the first character Uppercase in CSS

I would recommend that you use the following code in CSS:

    text-transform:uppercase; 

Make sure you put it in your class.

What does "|=" mean? (pipe equal operator)

It's a shortening for this:

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

And | is a bit-wise OR.

Deleting an element from an array in PHP

if you want to remove a specific object of an array by reference of that object you can do following:

unset($array[array_search($object,$array)]);

Example:

<?php
class Foo
{
    public $id;
    public $name;
}

$foo1 = new Foo();
$foo1->id = 1;
$foo1->name = 'Name1';

$foo2 = new Foo();
$foo2->id = 2;
$foo2->name = 'Name2';

$foo3 = new Foo();
$foo3->id = 3;
$foo3->name = 'Name3';


$array = array($foo1,$foo2,$foo3);
unset($array[array_search($foo2,$array)]);

echo '<pre>';
var_dump($array);
echo '</pre>';
?>

Result:

array(2) {
[0]=>
    object(Foo)#1 (2) {
        ["id"]=>
        int(1)
        ["name"]=>
        string(5) "Name1"
    }
[2]=>
    object(Foo)#3 (2) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(5) "Name3"
    }
}

Note that if the object occures several times it will only be removed the first occurence!

How to set the width of a RaisedButton in Flutter?

Wrap RaisedButton inside Container and give width to Container Widget.

e.g

 Container(
 width : 200,
 child : RaisedButton(
         child :YourWidget ,
         onPressed(){}
      ),
    )

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Cannot open new Jupyter Notebook [Permission Denied]

  • List item
  • List item

this problem of not able to open jupyter notebook is like Corona virus.I came across several complaints-including my own.I use windows 10.

Atlast after struggling for 3 days i came across this wonderful foolproof solution:-

1.The jupyter folder is created at path:- C:\Users\deviv_000\AppData\Roaming\jupyter your name will replace->deviv_000

2.Go to cmd and write : cd C:\Users\deviv_000\AppData\Roaming\jupyter this will take cmd to that folder.

3.Now create manually a file as untitled.ipynb in jupyter folder.

4.Come back to cmd and write: jupyter trust untitled.ipynb

5.After cmd performs this operation now write:-
jupyter notebook

SUCCESS!!- your notebook will appear in the next tab.I used chrome.

Regards

I want to exception handle 'list index out of range.'

Handling the exception is the way to go:

try:
    gotdata = dlist[1]
except IndexError:
    gotdata = 'null'

Of course you could also check the len() of dlist; but handling the exception is more intuitive.

Redirect on select option in select box

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value=""></option>
    <option value="http://google.com">Google</option>
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Javascript | Set all values of an array

Use a for loop and set each one in turn.

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Workaround:

Window -> Preferences -> Java -> Installed JREs, select a different JRE

maybe this JDK edition is not suitable:

enter image description here


So try this one instead:

enter image description here

Problem solved!

How to convert a double to long without casting?

(new Double(d)).longValue() internally just does a cast, so there's no reason to create a Double object.

Changing button color programmatically

I have finally found a working code - try this:

document.getElementById("button").style.background='#000000';

libstdc++-6.dll not found

Simply removing libstdc++-6.dll.a \ libstdc++.dll.a from the mingw directory fixes this.

I tried using the flag -static-libstdc++ but this did not work for me. I found the solution in: http://ghc.haskell.org/trac/ghc/ticket/4468#

Script to Change Row Color when a cell changes text

user2532030's answer is the correct and most simple answer.

I just want to add, that in the case, where the value of the determining cell is not suitable for a RegEx-match, I found the following syntax to work the same, only with numerical values, relations et.c.:

[Custom formula is]
=$B$2:$B = "Complete"
Range: A2:Z1000

If column 2 of any row (row 2 in script, but the leading $ means, this could be any row) textually equals "Complete", do X for the Range of the entire sheet (excluding header row (i.e. starting from A2 instead of A1)).

But obviously, this method allows also for numerical operations (even though this does not apply for op's question), like:

=$B$2:$B > $C$2:$C

So, do stuff, if the value of col B in any row is higher than col C value.

One last thing: Most likely, this applies only to me, but I was stupid enough to repeatedly forget to choose Custom formula is in the drop-down, leaving it at Text contains. Obviously, this won't float...

How Best to Compare Two Collections in Java and Act on Them?

I have created an approximation of what I think you are looking for just using the Collections Framework in Java. Frankly, I think it is probably overkill as @Mike Deck points out. For such a small set of items to compare and process I think arrays would be a better choice from a procedural standpoint but here is my pseudo-coded (because I'm lazy) solution. I have an assumption that the Foo class is comparable based on it's unique id and not all of the data in it's contents:

Collection<Foo> oldSet = ...;
Collection<Foo> newSet = ...;

private Collection difference(Collection a, Collection b) {
    Collection result = a.clone();
    result.removeAll(b)
    return result;
}

private Collection intersection(Collection a, Collection b) {
    Collection result = a.clone();
    result.retainAll(b)
    return result;
}

public doWork() {
    // if foo is in(*) oldSet but not newSet, call doRemove(foo)
    Collection removed = difference(oldSet, newSet);
    if (!removed.isEmpty()) {
        loop removed {
            Foo foo = removedIter.next();
            doRemove(foo);
        }
    }
    //else if foo is not in oldSet but in newSet, call doAdd(foo)
    Collection added = difference(newSet, oldSet);
    if (!added.isEmpty()) {
        loop added  {
            Foo foo = addedIter.next();
            doAdd(foo);
        }
    }

    // else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)
    Collection matched = intersection(oldSet, newSet);
    Comparator comp = new Comparator() {
        int compare(Object o1, Object o2) {
            Foo f1, f2;
            if (o1 instanceof Foo) f1 = (Foo)o1;
            if (o2 instanceof Foo) f2 = (Foo)o2;
            return f1.activated == f2.activated ? f1.startdate.compareTo(f2.startdate) == 0 ? ... : f1.startdate.compareTo(f2.startdate) : f1.activated ? 1 : 0;
        }

        boolean equals(Object o) {
             // equal to this Comparator..not used
        }
    }
    loop matched {
        Foo foo = matchedIter.next();
        Foo oldFoo = oldSet.get(foo);
        Foo newFoo = newSet.get(foo);
        if (comp.compareTo(oldFoo, newFoo ) != 0) {
            doUpdate(oldFoo, newFoo);
        } else {
            //else if !foo.activated && foo.startDate >= now, call doStart(foo)
            if (!foo.activated && foo.startDate >= now) doStart(foo);

            // else if foo.activated && foo.endDate <= now, call doEnd(foo)
            if (foo.activated && foo.endDate <= now) doEnd(foo);
        }
    }
}

As far as your questions: If I convert oldSet and newSet into HashMap (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? I think that you would probably make the code more readable by using a Map BUT...you would probably use more memory and time during the conversion.

Would iterating the two sets and perform the appropriate operation be more efficient and concise? Yes, this would be the best of both worlds especially if you followed @Mike Sharek 's advice of Rolling your own List with the specialized methods or following something like the Visitor Design pattern to run through your collection and process each item.

How do I serialize a C# anonymous type to a JSON string?

The fastest way I found was this:

var obj = new {Id = thing.Id, Name = thing.Name, Age = 30};
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(obj);

Namespace: System.Web.Script.Serialization.JavaScriptSerializer

Why can't I use background image and color together?

Make half of the image transparent so the background colour is seen through it.

Else simply add another div taking up 50% up the container div and float it either left or right. Then apply either the image or the colour to it.

jquery function val() is not equivalent to "$(this).value="?

One thing you can do is this:

$(this)[0].value = "Something";

This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

How can I give eclipse more memory than 512M?

I've had a lot of problems trying to get Eclipse to accept as much memory as I'd like it to be able to use (between 2 and 4 gigs for example).

Open eclipse.ini in the Eclipse installation directory. You should be able to change the memory sizes after -vmargs up to 1024 without a problem up to some maximum value that's dependent on your system. Here's that section on my Linux box:

-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=512m
-Xms512m
-Xmx1024m

And here's that section on my Windows box:

-vmargs
-Xms256m
-Xmx1024m

But, I've failed at setting it higher than 1024 megs. If anybody knows how to make that work, I'd love to know.

EDIT: 32bit version of juno seems to not accept more than Xmx1024m where the 64 bit version accept 2048.

EDIT: Nick's post contains some great links that explain two different things:

  • The problem is largely dependent on your system and the amount of contiguous free memory available, and
  • By using javaw.exe (on Windows), you may be able to get a larger allocated block of memory.

I have 8 gigs of Ram and can't set -Xmx to more than 1024 megs of ram, even when a minimal amount of programs are loaded and both windows/linux report between 4 and 5 gigs of free ram.

"document.getElementByClass is not a function"

The getElementByClass does not exists, probably you want to use getElementsByClassName. However you can use alternative approach (used in angular/vue/react... templates)

_x000D_
_x000D_
function stop(ta) {_x000D_
  console.log(ta.value) // document['player'].stopMusicExt(ta.value);_x000D_
  ta.value='';_x000D_
}
_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
_x000D_
_x000D_
_x000D_

Is there a "between" function in C#?

No, but you can write your own:

public static bool Between(this int num, int lower, int upper, bool inclusive = false)
{
    return inclusive
        ? lower <= num && num <= upper
        : lower < num && num < upper;
}

How to cancel a pull request on github?

I wanted to comment, but since my reputation won't qualify for commenting, it had to be an answer. Github will actually let you not only cancel a pull request, but also delete it by simply deleting the fork you are trying to push. Hope this may help some others googling this.

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

Install IPA with iTunes 11

for iTunes 12 and above (Yosemite) double click on IPA then browse your iOS device, on applist you will see the app, click the install on item.

How do you do exponentiation in C?

int power(int x,int y){
 int r=1;
 do{
  r*=r;
  if(y%2)
   r*=x;
 }while(y>>=1);
 return r;
};

(iterative)

int power(int x,int y){
 return y?(y%2?x:1)*power(x*x,y>>1):1;
};

(if it has to be recursive)

imo, the algorithm should definitely be O(logn)

Add new value to an existing array in JavaScript

Array is a JavaScript native object, why don't you just try to use the API of it? Knowing API on its own will save you time when you will switch to pure JavaScript or another framework.

There are number of different possibilities, so, use the one which mostly targets your needs.

Creating array with values:

var array = ["value1", "value2", "value3"];

Adding values to the end

var array = [];
array.push("value1");
array.push("value2");
array.push("value3");

Adding values to the begin:

var array = [];
array.unshift("value1");
array.unshift("value2");
array.unshift("value3");

Adding values at some index:

var array = [];
array[index] = "value1";

or by using splice

array.splice(index, 0, "value1", "value2", "value3");

Choose one you need.

How to Free Inode Usage?

If you are very unlucky you have used about 100% of all inodes and can't create the scipt. You can check this with df -ih.

Then this bash command may help you:

sudo find . -xdev -type f | cut -d "/" -f 2 | sort | uniq -c | sort -n

And yes, this will take time, but you can locate the directory with the most files.

How do I setup the InternetExplorerDriver so it works

WebDriverManager allows to automate the management of the binary drivers (e.g. chromedriver, geckodriver, etc.) required by Selenium WebDriver.

Link: https://github.com/bonigarcia/webdrivermanager

you can use something link this: WebDriverManager.iedriver().setup();

add the following dependency for Maven:

<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>x.x.x</version>
    <scope>test</scope>
</dependency> 

or see: https://www.toolsqa.com/selenium-webdriver/webdrivermanager/

How to hide scrollbar in Firefox?

This is what I needed to disable scrollbars while preserving scroll in Firefox, Chrome and Edge in :

          @-moz-document url-prefix() { /* Disable scrollbar Firefox */
            html{
              scrollbar-width: none;
            }
          }
          body {
            margin: 0; /* remove default margin */
            scrollbar-width: none; /* Also needed to disable scrollbar Firefox */
            -ms-overflow-style: none;  /* Disable scrollbar IE 10+ */
            overflow-y: scroll;
          }
          body::-webkit-scrollbar {
            width: 0px;
            background: transparent; /* Disable scrollbar Chrome/Safari/Webkit */
          }

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

PHP - remove <img> tag from string

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}

How to initialize static variables

I use a combination of Tjeerd Visser's and porneL's answer.

class Something
{
    private static $foo;

    private static getFoo()
    {
        if ($foo === null)
            $foo = [[ complicated initializer ]]
        return $foo;
    }

    public static bar()
    {
        [[ do something with self::getFoo() ]]
    }
}

But an even better solution is to do away with the static methods and use the Singleton pattern. Then you just do the complicated initialization in the constructor. Or make it a "service" and use DI to inject it into any class that needs it.

Python Pandas counting and summing specific conditions

You didn't mention the fancy indexing capabilities of dataframes, e.g.:

>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class    3
value    6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3

You could replace df["class"]==1by another condition.

Type Checking: typeof, GetType, or is?

It depends on what I'm doing. If I need a bool value (say, to determine if I'll cast to an int), I'll use is. If I actually need the type for some reason (say, to pass to some other method) I'll use GetType().

how to make twitter bootstrap submenu to open on the left side?

If you are using bootstrap v4 there is a new way to do that.

You should use .dropdown-menu-right on the .dropdown-menu element.

<div class="btn-group">
  <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Right-aligned menu
  </button>
  <div class="dropdown-menu dropdown-menu-right">
    <button class="dropdown-item" type="button">Action</button>
    <button class="dropdown-item" type="button">Another action</button>
    <button class="dropdown-item" type="button">Something else here</button>
  </div>
</div>

Link to code: https://getbootstrap.com/docs/4.0/components/dropdowns/#menu-items

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

First is you have to understand the difference between MyISAM and InnoDB Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:

 ALTER TABLE t1 ENGINE=MyISAM;

How much does it cost to develop an iPhone application?

I'm one of the developers for Twitterrific and to be honest, I can't tell you how many hours have gone into the product. I can tell you everyone who upvoted the estimate of 160 hours for development and 40 hours for design is fricken' high. (I'd use another phrase, but this is my first post on Stack Overflow, so I'm being good.)

Twitterrific has had 4 major releases beginning with the iOS 1.0 (Jailbreak.) That's a lot of code, much of which is in the bit bucket (we refactor a lot with each major release.)

One thing that would be interesting to look at is the amount of time that we had to work on the iPad version. Apple set a product release date that gave us 60 days to do the development. (That was later extended by a week.)

We started the iPad development from scratch, but a lot of our underlying code (mostly models) was re-used. The development was done by two experienced iOS developers. One of them has even written a book: http://appdevmanual.com :-)

With such a short schedule, we worked some pretty long hours. Let's be conservative and say it's 10 hours per day for 6 days a week. That 60 hours for 9 weeks gives us 540 hours. With two developers, that's pretty close to 1,100 hours. Our rate for clients is $150 per hour giving $165,000 just for new code. Remember also that we were reusing a bunch existing code: I'm going to lowball the value of that code at $35,000 giving a total development cost of $200,000.

Anyone who's done serious iPhone development can tell you there's a lot of design work involved with any project. We had two designers working on that aspect of the product. They worked their asses off dealing with completely new interaction mechanics. Don't forget they didn't have any hardware to touch, either (LOTS of printouts!) Combined they spent at least 25 hours per week on the project. So 225 hours at $150/hr is about $34,000.

There are also other costs that many developer neglect to take into account: project management, testing, equipment. Again, if we lowball that figure at $16,000 we're at $250,000. This number falls in line with Jonathan Wight's (@schwa) $50-150K estimate with the 22 day Obama app.

Take another hit, dude.

Now if you want to build backend services for your app, that number's going to go up even more. Everyone seems surprised that Instagram chewed through $500K in venture funding to build a new frontend and backend. I'm not.

Compute mean and standard deviation by group for multiple variables in a data.frame

There is a helpful function in the psych package.

You should try the following implementation:

psych::describeBy(data$dependentvariable, group = data$groupingvariable)

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

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

Drop-in solution as a category on UILabel (this assumes your UILabel uses an attributed string with some NSLinkAttributeName attributes in it):

@implementation UILabel (Support)

- (BOOL)openTappedLinkAtLocation:(CGPoint)location {
  CGSize labelSize = self.bounds.size;

  NSTextContainer* textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
  textContainer.lineFragmentPadding = 0.0;
  textContainer.lineBreakMode = self.lineBreakMode;
  textContainer.maximumNumberOfLines = self.numberOfLines;
  textContainer.size = labelSize;

  NSLayoutManager* layoutManager = [[NSLayoutManager alloc] init];
  [layoutManager addTextContainer:textContainer];

  NSTextStorage* textStorage = [[NSTextStorage alloc] initWithAttributedString:self.attributedText];
  [textStorage addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, textStorage.length)];
  [textStorage addLayoutManager:layoutManager];

  CGRect textBoundingBox = [layoutManager usedRectForTextContainer:textContainer];
  CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                            (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
  CGPoint locationOfTouchInTextContainer = CGPointMake(location.x - textContainerOffset.x, location.y - textContainerOffset.y);
  NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInTextContainer inTextContainer:textContainer fractionOfDistanceBetweenInsertionPoints:nullptr];
  if (indexOfCharacter >= 0) {
    NSURL* url = [textStorage attribute:NSLinkAttributeName atIndex:indexOfCharacter effectiveRange:nullptr];
    if (url) {
      [[UIApplication sharedApplication] openURL:url];
      return YES;
    }
  }
  return NO;
}

@end

What does the "+=" operator do in Java?

As many people have already pointed out, it's the XOR operator. Many people have also already pointed out that if you want exponentiation then you need to use Math.pow.

But I think it's also useful to note that ^ is just one of a family of operators that are collectively known as bitwise operators:

Operator    Name         Example     Result  Description
a & b       and          3 & 5       1       1 if both bits are 1.
a | b       or           3 | 5       7       1 if either bit is 1.
a ^ b       xor          3 ^ 5       6       1 if both bits are different.
~a          not          ~3          -4      Inverts the bits.
n << p      left shift   3 << 2      12      Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p      right shift  5 >> 2      1       Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p     right shift  -4 >>> 28   15      Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.

From here.

These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.

Disable copy constructor

You can make the copy constructor private and provide no implementation:

private:
    SymbolIndexer(const SymbolIndexer&);

Or in C++11, explicitly forbid it:

SymbolIndexer(const SymbolIndexer&) = delete;

How to get value by class name in JavaScript or jquery?

Without jQuery:

textContent:

var text = document.querySelector('.someClassname').textContent;

Markup:

var text = document.querySelector('.someClassname').innerHTML;

Markup including the matched element:

var text = document.querySelector('.someClassname').outerHTML;

though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.

Static methods - How to call a method from another method?

If these don't depend on the class or instance, then just make them a function.

As this would seem like the obvious solution. Unless of course you think it's going to need to be overwritten, subclassed, etc. If so, then the previous answers are the best bet. Fingers crossed I won't get marked down for merely offering an alternative solution that may or may not fit someone’s needs ;).

As the correct answer will depend on the use case of the code in question ;)

What is Turing Complete?

As Waylon Flinn said:

Turing Complete means that it is at least as powerful as a Turing Machine.

I believe this is incorrect, a system is Turing complete if it's exactly as powerful as the Turing Machine, i.e. every computation done by the machine can be done by the system, but also every computation done by the system can be done by the Turing machine.

java.lang.ClassNotFoundException: HttpServletRequest

Thanks guys. All above failed except this that deleted all content from the file C:\Users\debasish\workspace\.metadata\.plugins\org.eclipse.wst.server.core then creating server again.

But delete server first before deleting those file contents.

What is ADT? (Abstract Data Type)

ADT is a data type in which collection of data and operation works on that data . It focuses on more the concept than implementation.. It's up to you which language you use to make it visible on the earth Example: Stack is an ADT while the Array is not Stack is ADT because we can implement it by many languages, Python c c++ java and many more , while Array is built in data type

Dynamic classname inside ngClass in angular 2

Here's an example of something I'm doing for multiple classes with multiple conditions:

[ngClass]="[variableInComponent || !anotherVariableInComponent ? classes.icon.large : classes.icon.small, editing ? classes.icon.editing : '']"

where:
classes is an object containing strings of various classnames. e.g. class.icon.large = "app__icon--large"

It's dynamic! Updates as the conditions update.

How do I run a single test using Jest?

With the latest Jest version, you can use one of the following to only run one test, and the same for a test suite.

it.only('test 1', () => {})

test.only('test 1', () => {})

fit('test 1', () => {})

jest 'test 1' may work too if the test name is unique.

Convert a string to integer with decimal in Python

round(float("123.789"))

will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual int. Like this:

int(float("123.789"))

But, again, actual 'type' is usually not that important.

How do I call paint event?

I think you can also call Refresh().

Unix: How to delete files listed in a file

Assuming that the list of files is in the file 1.txt, then do:

xargs rm -r <1.txt

The -r option causes recursion into any directories named in 1.txt.

If any files are read-only, use the -f option to force the deletion:

xargs rm -rf <1.txt

Be cautious with input to any tool that does programmatic deletions. Make certain that the files named in the input file are really to be deleted. Be especially careful about seemingly simple typos. For example, if you enter a space between a file and its suffix, it will appear to be two separate file names:

file .txt

is actually two separate files: file and .txt.

This may not seem so dangerous, but if the typo is something like this:

myoldfiles *

Then instead of deleting all files that begin with myoldfiles, you'll end up deleting myoldfiles and all non-dot-files and directories in the current directory. Probably not what you wanted.

How to access full source of old commit in BitBucket?

I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well.

When you're browsing your code the URL is something like:

https://bitbucket.org/user/repo/src/

and by adding a commit hash at the end like this:

https://bitbucket.org/user/repo/src/a0328cb

You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.

How can I pass arguments to anonymous functions in JavaScript?

The delegates:

function displayMessage(message, f)
{
    f(message); // execute function "f" with variable "message"
}

function alerter(message)
{
    alert(message);
}

function writer(message)
{
    document.write(message);
}

Running the displayMessage function:

function runDelegate()
{
    displayMessage("Hello World!", alerter); // alert message

    displayMessage("Hello World!", writer); // write message to DOM
}

Convert base-2 binary number string to int

You use the built-in int function, and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2)
255

Here is documentation for python2, and for python3.

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

jquery find element by specific class when element has multiple classes

you are looking for http://api.jquery.com/hasClass/

<div id="mydiv" class="foo bar"></div>

$('#mydiv').hasClass('foo') //returns ture

How can I select the first day of a month in SQL?

Try executing the following query:

SELECT DATE_ADD(DATE_ADD(LAST_DAY(CURRENT_DATE-INTERVAL 1 DAY),INTERVAL 1 DAY),INTERVAL -1 MONTH)

Differences between SP initiated SSO and IDP initiated SSO

In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.

Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html

TypeError: unsupported operand type(s) for /: 'str' and 'str'

I would have written:

percent = 100
while True:
     try:
        pyc = int(input('enter pyc :'))
        tpy = int(input('enter tpy:'))
        percent = (pyc / tpy) * percent
        break
     except ZeroDivisionError as detail:
        print 'Handling run-time error:', detail

Java - How to create new Entry (key, value)

Why Map.Entry? I guess something like a key-value pair is fit for the case.

Use java.util.AbstractMap.SimpleImmutableEntry or java.util.AbstractMap.SimpleEntry

Error: Cannot invoke an expression whose type lacks a call signature

I think what you want is:

abstract class Component {
  public deps: any = {};
  public props: any = {};

  public makePropSetter<T>(prop: string): (val: T) => T {
    return function(val) {
      this.props[prop] = val
      return val
    }
  }
}

class Post extends Component {
  public toggleBody: (val: boolean) => boolean;

  constructor () {
    super()
    this.toggleBody = this.makePropSetter<boolean>('showFullBody')
  }

  showMore (): boolean {
    return this.toggleBody(true)
  }

  showLess (): boolean {
    return this.toggleBody(false)
  }
}

The important change is in setProp (i.e., makePropSetter in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.

The <T> on makePropSetter allows you to lock that function in to a specific type. The <boolean> in the subclass's constructor is actually optional. Since you're assigning to toggleBody, and that already has the type fully specified, the TS compiler will be able to work it out on its own.

Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody respect that same signature.

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

python: how to identify if a variable is an array or a scalar

To answer the question in the title, a direct way to tell if a variable is a scalar is to try to convert it to a float. If you get TypeError, it's not.

N = [1, 2, 3]
try:
    float(N)
except TypeError:
    print('it is not a scalar')
else:
    print('it is a scalar')

All combinations of a list of lists

from itertools import product 
list_vals = [['Brand Acronym:CBIQ', 'Brand Acronym :KMEFIC'],['Brand Country:DXB','Brand Country:BH']]
list(product(*list_vals))

Output:

[('Brand Acronym:CBIQ', 'Brand Country :DXB'),
('Brand Acronym:CBIQ', 'Brand Country:BH'),
('Brand Acronym :KMEFIC', 'Brand Country :DXB'),
('Brand Acronym :KMEFIC', 'Brand Country:BH')]

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Extracting Path from OpenFileDialog path/filename

how about this:

string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");

How to check if an element of a list is a list (in Python)?

Use isinstance:

if isinstance(e, list):

If you want to check that an object is a list or a tuple, pass several classes to isinstance:

if isinstance(e, (list, tuple)):

Rounding to 2 decimal places in SQL

Try using the COLUMN command with the FORMAT option for that:

COLUMN COLUMN_NAME FORMAT 99.99
SELECT COLUMN_NAME FROM ....

Test class with a new() call in it with Mockito

In situations where the class under test can be modified and when it's desirable to avoid byte code manipulation, to keep things fast or to minimise third party dependencies, here is my take on the use of a factory to extract the new operation.

public class TestedClass {

    interface PojoFactory { Pojo getNewPojo(); }

    private final PojoFactory factory;

    /** For use in production - nothing needs to change. */
    public TestedClass() {
        this.factory = new PojoFactory() {
            @Override
            public Pojo getNewPojo() {
                return new Pojo();
            }
        };
    }

    /** For use in testing - provide a pojo factory. */
    public TestedClass(PojoFactory factory) {
        this.factory = factory;
    }

    public void doSomething() {
        Pojo pojo = this.factory.getNewPojo();
        anythingCouldHappen(pojo);
    }
}

With this in place, your testing, asserts and verify calls on the Pojo object are easy:

public  void testSomething() {
    Pojo testPojo = new Pojo();
    TestedClass target = new TestedClass(new TestedClass.PojoFactory() {
                @Override
                public Pojo getNewPojo() {
                    return testPojo;
                }
            });
    target.doSomething();
    assertThat(testPojo.isLifeStillBeautiful(), is(true));
}

The only downside to this approach potentially arises if TestClass has multiple constructors which you'd have to duplicate with the extra parameter.

For SOLID reasons you'd probably want to put the PojoFactory interface onto the Pojo class instead, and the production factory as well.

public class Pojo {

    interface PojoFactory { Pojo getNewPojo(); }

    public static final PojoFactory productionFactory = 
        new PojoFactory() {
            @Override 
            public Pojo getNewPojo() {
                return new Pojo();
            }
        };

Binding objects defined in code-behind

Just a little more clarification: A property without 'get','set' won't be able to be bound

I'm facing the case just like the asker's case. And I must have the following things in order for the bind to work properly:

//(1) Declare a property with 'get','set' in code behind
public partial class my_class:Window {
  public String My_Property { get; set; }
  ...

//(2) Initialise the property in constructor of code behind
public partial class my_class:Window {
  ...
  public my_class() {
     My_Property = "my-string-value";
     InitializeComponent();
  }

//(3) Set data context in window xaml and specify a binding
<Window ...
DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <TextBlock Text="{Binding My_Property}"/>
</Window>

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Http Get using Android HttpURLConnection

Simple and Efficient Solution : use Volley

 StringRequest stringRequest = new StringRequest(Request.Method.GET, finalUrl ,
           new Response.Listener<String>() {
                    @Override
                    public void onResponse(String){
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            HashMap<String, Object> responseHashMap = new HashMap<>(Utility.toMap(jsonObject)) ;
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("api", error.getMessage().toString());
            }
        });

        RequestQueue queue = Volley.newRequestQueue(context) ;
        queue.add(stringRequest) ;

Initializing a struct to 0

I also thought this would work but it's misleading:

myStruct _m1 = {0};

When I tried this:

myStruct _m1 = {0xff};

Only the 1st byte was set to 0xff, the remaining ones were set to 0. So I wouldn't get into the habit of using this.

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

Page unload event in asp.net

Refer to the ASP.NET page lifecycle to help find the right event to override. It really depends what you want to do. But yes, there is an unload event.

    protected override void OnUnload(EventArgs e)
    {
        base.OnUnload(e);

        // your code
    }

But just remember (from the above link): During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

Manually raising (throwing) an exception in Python

Just to note: there are times when you DO want to handle generic exceptions. If you're processing a bunch of files and logging your errors, you might want to catch any error that occurs for a file, log it, and continue processing the rest of the files. In that case, a

try:
    foo() 
except Exception as e:
    print(str(e)) # Print out handled error

block is a good way to do it. You'll still want to raise specific exceptions so you know what they mean, though.

Why should text files end with a newline?

It's very late here but I just faced one bug in file processing and that came because the files were not ending with empty newline. We were processing text files with sed and sed was omitting the last line from output which was causing invalid json structure and sending rest of the process to fail state.

All we were doing was:

There is one sample file say: foo.txt with some json content inside it.

[{
    someProp: value
},
{
    someProp: value
}] <-- No newline here

The file was created in widows machine and window scripts were processing that file using PowerShell commands. All good.

When we processed same file using sed command sed 's|value|newValue|g' foo.txt > foo.txt.tmp

The newly generated file was

[{
    someProp: value
},
{
    someProp: value

and boom, it failed the rest of the processes because of the invalid JSON.

So it's always a good practice to end your file with empty new line.

How to set focus to a button widget programmatically?

Yeah it's possible.

Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();

or in XML

<Button ...><requestFocus /></Button>

Important Note: The button widget needs to be focusable and focusableInTouchMode. Most widgets are focusable but not focusableInTouchMode by default. So make sure to either set it in code

myBtn.setFocusableInTouchMode(true);

or in XML

android:focusableInTouchMode="true"

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I have the same problem and the solution was uncheck the "use ports 80 and 443" on skype advanced configuration!

Auto increment in MongoDB to store sequence of Unique User ID

I had a similar issue, namely I was interested in generating unique numbers, which can be used as identifiers, but doesn't have to. I came up with the following solution. First to initialize the collection:

fun create(mongo: MongoTemplate) {
        mongo.db.getCollection("sequence")
                .insertOne(Document(mapOf("_id" to "globalCounter", "sequenceValue" to 0L)))
    }

An then a service that return unique (and ascending) numbers:

@Service
class IdCounter(val mongoTemplate: MongoTemplate) {

    companion object {
        const val collection = "sequence"
    }

    private val idField = "_id"
    private val idValue = "globalCounter"
    private val sequence = "sequenceValue"

    fun nextValue(): Long {
        val filter = Document(mapOf(idField to idValue))
        val update = Document("\$inc", Document(mapOf(sequence to 1)))
        val updated: Document = mongoTemplate.db.getCollection(collection).findOneAndUpdate(filter, update)!!
        return updated[sequence] as Long
    }
}

I believe that id doesn't have the weaknesses related to concurrent environment that some of the other solutions may suffer from.

Which Android IDE is better - Android Studio or Eclipse?

The use of IDE is your personal preference. But personally if I had to choose, Eclipse is a widely known, trusted and certainly offers more features then Android Studio. Android Studio is a little new right now. May be it's upcoming versions keep up to Eclipse level soon.

Inserting Data into Hive Table

It's a limitation of hive.

1.You cannot update data after it is inserted

2.There is no "insert into table values ... " statement

3.You can only load data using bulk load

4.There is not "delete from " command

5.You can only do bulk delete

But you still want to insert record from hive console than you can do select from statck. refer this

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where d.id in (
    select a.id from docs_documents a
    left join docx_document b on b.id = a.document_id
    where b.id is null
        and floor(sysdate - a.create_date) > 120
 );

How do I detect unsigned integer multiply overflow?

To perform an unsigned multiplication without overflowing in a portable way the following can be used:

... /* begin multiplication */
unsigned multiplicand, multiplier, product, productHalf;
int zeroesMultiplicand, zeroesMultiplier;
zeroesMultiplicand = number_of_leading_zeroes( multiplicand );
zeroesMultiplier   = number_of_leading_zeroes( multiplier );
if( zeroesMultiplicand + zeroesMultiplier <= 30 ) goto overflow;
productHalf = multiplicand * ( c >> 1 );
if( (int)productHalf < 0 ) goto overflow;
product = productHalf * 2;
if( multiplier & 1 ){
   product += multiplicand;
   if( product < multiplicand ) goto overflow;
}
..../* continue code here where "product" is the correct product */
....
overflow: /* put overflow handling code here */

int number_of_leading_zeroes( unsigned value ){
   int ctZeroes;
   if( value == 0 ) return 32;
   ctZeroes = 1;
   if( ( value >> 16 ) == 0 ){ ctZeroes += 16; value = value << 16; }
   if( ( value >> 24 ) == 0 ){ ctZeroes +=  8; value = value <<  8; }
   if( ( value >> 28 ) == 0 ){ ctZeroes +=  4; value = value <<  4; }
   if( ( value >> 30 ) == 0 ){ ctZeroes +=  2; value = value <<  2; }
   ctZeroes -= x >> 31;
   return ctZeroes;
}

Lists in ConfigParser

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

CSS Font "Helvetica Neue"

It's a default font on Macs, but rare on PCs. Since it's not technically web-safe, some people may have it and some people may not. If you want to use a font like that, without using @font-face, you may want to write it out several different ways because it might not work the same for everyone.

I like using a font stack that touches on all bases like this:

font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", 
  Helvetica, Arial, "Lucida Grande", sans-serif;

This recommended font-family stack is further described in this CSS-Tricks snippet Better Helvetica which uses a font-weight: 300; as well.

Creating an empty bitmap and drawing though canvas in Android

Do not use Bitmap.Config.ARGB_8888

Instead use int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps. Or better yet, try avoiding usage of ARGB option itself.

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

You've already listed the most notable solutions for embedding Chromium (CEF, Chrome Frame, Awesomium). There aren't any more projects that matter.

There is still the Berkelium project (see Berkelium Sharp and Berkelium Managed), but it emebeds an old version of Chromium.

CEF is your best bet - it's fully open source and frequently updated. It's the only option that allows you to embed the latest version of Chromium. Now that Per Lundberg is actively working on porting CEF 3 to CefSharp, this is the best option for the future. There is also Xilium.CefGlue, but this one provides a low level API for CEF, it binds to the C API of CEF. CefSharp on the other hand binds to the C++ API of CEF.

Adobe is not the only major player using CEF, see other notable applications using CEF on the CEF wikipedia page.

Updating Chrome Frame is pointless since the project has been retired.

How to display the value of the bar on each bar with pyplot.barh()?

I was trying to do this with stacked plot bars. The code that worked for me was.

# Code to plot. Notice the variable ax.
ax = df.groupby('target').count().T.plot.bar(stacked=True, figsize=(10, 6))
ax.legend(bbox_to_anchor=(1.1, 1.05))

# Loop to add on each bar a tag in position
for rect in ax.patches:
    height = rect.get_height()
    ypos = rect.get_y() + height/2
    ax.text(rect.get_x() + rect.get_width()/2., ypos,
            '%d' % int(height), ha='center', va='bottom')

How do I select an element that has a certain class?

It should be this way:

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

How to stop tracking and ignore changes to a file in Git?

git rm --fileName

git ls-files to make sure that the file is removed or untracked

git commit -m "UntrackChanges"

git push

Bind service to activity in Android

First of all, 2 thing that we need to understand

Client

  • it make request to specific server

    bindService(new 
        Intent("com.android.vending.billing.InAppBillingService.BIND"),
            mServiceConn, Context.BIND_AUTO_CREATE);`
    

here mServiceConn is instance of ServiceConnection class(inbuilt) it is actually interface that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.

Server

  • It handle the request of client and make replica of it's own which is private to client only who send request and this replica of server runs on different thread.

Now at client side, how to access all the method of server?

  • server send response with IBind Object.so IBind object is our handler which access all the method of service by using (.) operator.

    MyService myService;
    public ServiceConnection myConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
            Log.d("ServiceConnection","connected");
            myService = binder;
        }
        //binder comes from server to communicate with method's of 
    
        public void onServiceDisconnected(ComponentName className) {
            Log.d("ServiceConnection","disconnected");
            myService = null;
        }
    }
    

now how to call method which lies in service

myservice.serviceMethod();

here myService is object and serviceMethode is method in service. And by this way communication is established between client and server.

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

All of these answers miss the point that doing an Ajax call with async:false will cause the browser to hang until the Ajax request completes. Using a flow control library will solve this problem without hanging up the browser. Here is an example with Frame.js:

beforecreate: function(node,targetNode,type,to) {

    Frame(function(next)){

        jQuery.get('http://example.com/catalog/create/', next);
    });

    Frame(function(next, response)){

        alert(response);
        next();
    });

    Frame.init();
}

centos: Another MySQL daemon already running with the same unix socket

TL;DR:

Run this as root and you'll be all set:

rm $(grep socket /etc/my.cnf | cut -d= -f2)  && service mysqld start

Longer version:

You can find the location of MySQL's socket file by manually poking around in /etc/my.conf, or just by using

grep socket /etc/my.cnf | cut -d= -f2

It is likely to be /var/lib/mysql/mysql.sock. Then (as root, of course, or with sudo prepended) remove that file:

rm /var/lib/mysql/mysql.sock

Then start the MySQL daemon:

service mysqld start

Removing mysqld will not address the problem at all. The problem is that CentOS & RedHat do not clean up the sock file after a crash, so you have to do it yourself. Avoiding powering off your system is (of course) also advised, but sometimes you can't avoid it, so this procedure will solve the problem.

How to download image using requests

Here is a more user-friendly answer that still uses streaming.

Just define these functions and call getImage(). It will use the same file name as the url and write to the current directory by default, but both can be changed.

import requests
from StringIO import StringIO
from PIL import Image

def createFilename(url, name, folder):
    dotSplit = url.split('.')
    if name == None:
        # use the same as the url
        slashSplit = dotSplit[-2].split('/')
        name = slashSplit[-1]
    ext = dotSplit[-1]
    file = '{}{}.{}'.format(folder, name, ext)
    return file

def getImage(url, name=None, folder='./'):
    file = createFilename(url, name, folder)
    with open(file, 'wb') as f:
        r = requests.get(url, stream=True)
        for block in r.iter_content(1024):
            if not block:
                break
            f.write(block)

def getImageFast(url, name=None, folder='./'):
    file = createFilename(url, name, folder)
    r = requests.get(url)
    i = Image.open(StringIO(r.content))
    i.save(file)

if __name__ == '__main__':
    # Uses Less Memory
    getImage('http://www.example.com/image.jpg')
    # Faster
    getImageFast('http://www.example.com/image.jpg')

The request guts of getImage() are based on the answer here and the guts of getImageFast() are based on the answer above.

Folder structure for a Node.js project

More example from my project architecture you can see here:

+-- Dockerfile
+-- README.md
+-- config
¦   +-- production.json
+-- package.json
+-- schema
¦   +-- create-db.sh
¦   +-- db.sql
+-- scripts
¦   +-- deploy-production.sh 
+-- src
¦   +-- app -> Containes API routes
¦   +-- db -> DB Models (ORM)
¦   +-- server.js -> the Server initlializer.
+-- test

Basically, the logical app separated to DB and APP folders inside the SRC dir.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

Just try this line:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

after:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

How to get item's position in a list?

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
try:
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor
  pass

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

Is there an exponent operator in C#?

There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.

It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.


You asked:

Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

Math.Pow supports double parameters so there is no need for you to write your own.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.

You should pass your connection object in as a dependency, eg

function getPosts(mysqli $con) {
    // etc

I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

getPosts($con);

Hadoop: «ERROR : JAVA_HOME is not set»

Copy this export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk to hadoop-env.sh file.

JAVA_HOME is the location where java binaries are present.

c# open file with default application and parameters

this should be close!

public static void OpenWithDefaultProgram(string path)
{
    Process fileopener = new Process();
    fileopener.StartInfo.FileName = "explorer";
    fileopener.StartInfo.Arguments = "\"" + path + "\"";
    fileopener.Start();
}

What is the iBeacon Bluetooth Profile

Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:

02 01 1a 1a ff 4C 00

Is part of the advertising data format specification [1]

  02 # length of following AD structure
  01 # <<Flags>> AD Structure [2]
  1a # read as b00011010. 
     # In this case, LE General Discoverable,
     # and simultaneous BR/EDR but this may vary by device!

  1a # length of following AD structure
  FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header

Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.

References:

  1. Core Bluetooth Spec v4, Vol 3, Part C, 11
  2. Vol 3, Part C, 18.1
  3. Vol 3, Part C, 18.11
  4. https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
  5. Vol 3, Part C, 18.2

Facebook share button and custom text

You have several options:

  1. Use the standard FB Share button and set text via Open Graph API and meta tags on your page.
  2. Instead of Share, use FB.ui's stream.publish method, which let's you control the URL, title, caption, description and thumbnail at run-time.
  3. Or use http://www.facebook.com/sharer.php with appropriate parameters.

Java method to swap primitives

I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:

int swap(int a, int b) {  // usage: y = swap(x, x=y);
   return a;
}

y = swap(x, x=y);

It relies on the fact that x will pass into swap before y is assigned to x, then x is returned and assigned to y.

You can make it generic and swap any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

c = swap(a, a=b, b=c)

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

Spark java.lang.OutOfMemoryError: Java heap space

I suffered from this issue a lot when using dynamic resource allocation. I had thought it would utilize my cluster resources to best fit the application.

But the truth is the dynamic resource allocation doesn't set the driver memory and keeps it to its default value, which is 1G.

I resolved this issue by setting spark.driver.memory to a number that suits my driver's memory (for 32GB ram I set it to 18G).

You can set it using spark submit command as follows:

spark-submit --conf spark.driver.memory=18g

Very important note, this property will not be taken into consideration if you set it from code, according to Spark Documentation - Dynamically Loading Spark Properties:

Spark properties mainly can be divided into two kinds: one is related to deploy, like “spark.driver.memory”, “spark.executor.instances”, this kind of properties may not be affected when setting programmatically through SparkConf in runtime, or the behavior is depending on which cluster manager and deploy mode you choose, so it would be suggested to set through configuration file or spark-submit command line options; another is mainly related to Spark runtime control, like “spark.task.maxFailures”, this kind of properties can be set in either way.

How to set full calendar to a specific start date when it's initialized for the 1st time?

For v5 please use initialDate instead of defaultDate. Simply renamed option

eg

var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
     ...
     initialDate: '2020-09-02',
     ...
});

What is the difference between char * const and const char *?

I remember from Czech book about C: read the declaration that you start with the variable and go left. So for

char * const a;

you can read as: "a is variable of type constant pointer to char",

char const * a;

you can read as: "a is a pointer to constant variable of type char. I hope this helps.

Bonus:

const char * const a;

You will read as a is constant pointer to constant variable of type char.

How to determine one year from now in Javascript

This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.

new Date(new Date().setFullYear(new Date().getFullYear() + 1))

How to configure log4j to only keep log files for the last seven days?

log2j now has support to delete old logs.

Take a look at DefaultRolloverStrategy tag and at a snippet below.

It

  • creates up to 10 archives on the same day,

  • will parse the ${baseDir} directory that you define under the Properties tag at max depth of 2 with log filename matching "app-*.log.gz"

  • delete logs older than 7 days but keep the most recent 5 logs if your most recent 5 logs are older than 7 days.

    <DefaultRolloverStrategy max="10">
      <Delete basePath="${baseDir}" maxDepth="2">
        <IfFileName glob="*/app-*.log.gz">
          <IfLastModified age="7d">
            <IfAny>
              <IfAccumulatedFileCount exceeds="5" />
            </IfAny>
          </IfLastModified>
        </IfFileName>
      </Delete>
    </DefaultRolloverStrategy>
    

A good debug option is if you set:

<Configuration status="trace">

and use testMode Option like this:

        <DefaultRolloverStrategy>
          <Delete basePath="${baseDir}" testMode="true">
            <IfFileName glob="*.log" />
            <IfLastModified age="7d" />
          </Delete>
        </DefaultRolloverStrategy>
        

You can see in console log what files would get deleted without deleting the files right away.

Find where python is installed (if it isn't default dir)

If you are using wiindows OS (I am using windows 10 ) just type

where python   

in command prompt ( cmd )

It will show you the directory where you have installed .

Select values from XML field in SQL Server 2008

Considering that XML data comes from a table 'table' and is stored in a column 'field': use the XML methods, extract values with xml.value(), project nodes with xml.nodes(), use CROSS APPLY to join:

SELECT 
    p.value('(./firstName)[1]', 'VARCHAR(8000)') AS firstName,
    p.value('(./lastName)[1]', 'VARCHAR(8000)') AS lastName
FROM table 
    CROSS APPLY field.nodes('/person') t(p)

You can ditch the nodes() and cross apply if each field contains exactly one element 'person'. If the XML is a variable you select FROM @variable.nodes(...) and you don't need the cross apply.

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

next() is read until the space of the encounter, and the nextLine() is read to the end of the line. Scanner scan = new Scanner(System.in);
String address = scan.next();
s += scan.nextLine();

PHPMailer AddAddress()

foreach ($all_address as $aa) {
    $mail->AddAddress($aa); 
}

Rails: Can't verify CSRF token authenticity when making a POST request

If you're using Devise, please note that

For Rails 5, protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use protect_from_forgery prepend: true.

Documentation

What algorithms compute directions from point A to point B on a map?

This question has been an active area of research in the last years. The main idea is to do a preprocessing on the graph once, to speed up all following queries. With this additional information itineraries can be computed very fast. Still, Dijkstra's Algorithm is the basis for all optimisations.

Arachnid described the usage of bidirectional search and edge pruning based on hierarchical information. These speedup techniques work quite well, but the most recent algorithms outperform these techniques by all means. With current algorithms a shortest paths can be computed in considerable less time than one millisecond on a continental road network. A fast implementation of the unmodified algorithm of Dijkstra needs about 10 seconds.

The article Engineering Fast Route Planning Algorithms gives an overview of the progress of research in that field. See the references of that paper for further information.

The fastest known algorithms do not use information about the hierarchical status of the road in the data, i.e. if it is a highway or a local road. Instead, they compute in a preprocessing step an own hierarchy that optimised to speed up route planning. This precomputation can then be used to prune the search: Far away from start and destination slow roads need not be considered during Dijkstra's Algorithm. The benefits are very good performance and a correctness guarantee for the result.

The first optimised route planning algorithms dealt only with static road networks, that means an edge in the graph has a fixed cost value. This not true in practice, since we want to take dynamic information like traffic jams or vehicle dependent restrictrions into account. Latest algorithms can also deal with such issues, but there are still problems to solve and the research is going on.

If you need the shortest path distances to compute a solution for the TSP, then you are probably interested in matrices that contain all distances between your sources and destinations. For this you could consider Computing Many-to-Many Shortest Paths Using Highway Hierarchies. Note, that this has been improved by newer approaches in the last 2 years.

How to copy a map?

I'd use recursion just in case so you can deep copy the map and avoid bad surprises in case you were to change a map element that is a map itself.

Here's an example in a utils.go:

package utils

func CopyMap(m map[string]interface{}) map[string]interface{} {
    cp := make(map[string]interface{})
    for k, v := range m {
        vm, ok := v.(map[string]interface{})
        if ok {
            cp[k] = CopyMap(vm)
        } else {
            cp[k] = v
        }
    }

    return cp
}

And its test file (i.e. utils_test.go):

package utils

import (
    "testing"

    "github.com/stretchr/testify/require"
)

func TestCopyMap(t *testing.T) {
    m1 := map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }

    m2 := CopyMap(m1)

    m1["a"] = "zzz"
    delete(m1, "b")

    require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
    require.Equal(t, map[string]interface{}{
        "a": "bbb",
        "b": map[string]interface{}{
            "c": 123,
        },
    }, m2)
}

It should easy enough to adapt if you need the map key to be something else instead of a string.

Creating folders inside a GitHub repository without using Git

When creating a file, use slashes to specify the directory. For example:

Name the file:

repositoryname/newfoldername/filename

GitHub will automatically create a folder with the name newfoldername.

Sync data between Android App and webserver

I would suggest using a binary webservice protocol similar to Hessian. It works very well and they do have a android implementation. It might be a little heavy but depends on the application you are building. Hope this helps.

How to display length of filtered ng-repeat data

Here is worked example See on Plunker

  <body ng-controller="MainCtrl">
    <input ng-model="search" type="text">
    <br>
    Showing {{data.length}} Persons; <br>
    Filtered {{counted}}
    <ul>
      <li ng-repeat="person in data | filter:search">
        {{person.name}}
      </li>
    </ul>
  </body>

<script> 
var app = angular.module('angularjs-starter', [])

app.controller('MainCtrl', function($scope, $filter) {
  $scope.data = [
    {
      "name": "Jim", "age" : 21
    }, {
      "name": "Jerry", "age": 26
    }, {
      "name": "Alex",  "age" : 25
    }, {
      "name": "Max", "age": 22
    }
  ];

  $scope.counted = $scope.data.length; 
  $scope.$watch("search", function(query){
    $scope.counted = $filter("filter")($scope.data, query).length;
  });
});

Installing a specific version of angular with angular cli

Use the following command to install and downgrade the specific version.
uninstall cli

npm uninstall -g @angular/cli

clean npm cache

 npm cache clean --force

install cli

npm install -g @angular/cli@_choose_your_version

No internet on Android emulator - why and how to fix?

on OSX, Little Snitch was automatically denying any connection to Eclipse (and the emulator). Allow connections in Little Snitch, you have to go into Little Snitch's rules

Simpler way to check if variable is not equal to multiple string values?

You need to multi value check. Try using the following code :

<?php
    $illstack=array(...............);
    $val=array('uk','bn','in');
    if(count(array_intersect($illstack,$val))===count($val)){ // all of $val is in $illstack}
?>

Phone number formatting an EditText in Android

If you're only interested in international numbers and you'd like to be able to show the flag of the country that matches the country code in the input, I wrote a small library for that:

https://github.com/tfcporciuncula/phonemoji

Here's how it looks:

library demo

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

Look. This is way old, but on the off chance that someone from Google finds this, absolutely the best solution to this - (and it is AWESOME) - is to use ConEmu (or a package that includes and is built on top of ConEmu called cmder) and then either use plink or putty itself to connect to a specific machine, or, even better, set up a development environment as a local VM using Vagrant.

This is the only way I can ever see myself developing from a Windows box again.

I am confident enough to say that every other answer - while not necessarily bad answers - offer garbage solutions compared to this.

Update: As Of 1/8/2020 not all other solutions are garbage - Windows Terminal is getting there and WSL exists.

What is the correct way to do a CSS Wrapper?

<div class="wrapper">test test test</div>

.wrapper{
    width:100px;
    height:100px;
    margin:0 auto;
}

Check working example at http://jsfiddle.net/8wpYV/

How can I get phone serial number (IMEI)

Use below code for IMEI:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String imei= tm.getDeviceId();

Display / print all rows of a tibble (tbl_df)

You could also use

print(tbl_df(df), n=40)

or with the help of the pipe operator

df %>% tbl_df %>% print(n=40)

To print all rows specify tbl_df %>% print(n = Inf)

How to use class from other files in C# with visual studio?

namespace TestCSharp2
{
    **public** class Class2
    {
        int i;
        public void setValue(int i)
        {
            this.i = i;
        }
        public int getValue()
        {
        return this.i;
        }
    }
}

Add the 'Public' declaration before 'class Class2'.

Hibernate vs JPA vs JDO - pros and cons of each?

I've used Hibernate (JPA implementation) and JPOX (JDO implementation) in the same project. JPOX worked ok, but ran into bugs fairly quickly, there where some Java 5 language features it did not support at the time. It had problems playing nice with XA transactions. I was generating the database schema from the JDO objects. It wanted to connect to a database every time which is annoying if your Oracle connection happens not be working.

We then switched to Hibernate. We toyed around with just using pure JPA for awhile, but we needed to use some of the Hibernate specific features to do the mapping. Running the same code on multiple databases is very easy. Hibernate seems to cache objects aggressively or just have strange caching behavior at times. There are a few DDL constructs Hibernate can not handle and so they are defined in an additional file that is run to initialize the database. When I've run into a Hibernate problem there are often many people that have run into the same problem which makes googling for solutions easier. Finally, Hibernate seems to be well designed and reliable.

Some other responders have suggested just using SQL. The real killer use case for object relational mapping is testing and development. The databases that are built to handle large volumes of data are typically expensive and or they are difficult to install. They are difficult to test with. There are plenty of in-memory Java databases that can be used to test with, but are typically useless for production. Being able to use a real, but limited database, will increase development productivity and code reliability.

Where do you include the jQuery library from? Google JSAPI? CDN?

In head:

  (function() {
    var jsapi = document.createElement('script'); jsapi.type = 'text/javascript'; jsapi.async = true;
    jsapi.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.google.com/jsapi?key=YOUR KEY';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('head')[0]).appendChild(jsapi);
  })();

End of Body:

<script type="text/javascript">
google.load("jquery", "version");
</script>

jQuery get the name of a select option

 $(this).attr("name") 

means the name of the select tag not option name.

To get option name

 $("#band_type_choices option:selected").attr('name');

How/when to generate Gradle wrapper files?

As gradle built-in tasks is deprecated in 4.8, try below

wrapper {
   gradleVersion = '2.0' //version required
}

and run

gradle wrapper

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.

How to loop through all the properties of a class?

Use Reflection:

Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}

for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list

Edit: You can also specify a BindingFlags value to type.GetProperties():

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);

That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).

You don't need to specify BindingFlags.GetProperty, you use that when calling type.InvokeMember() to get the value of a property.

How do I wrap text in a pre tag?

This works great to wrap text and maintain white-space within the pre-tag:

pre {
    white-space: pre-wrap;
}

Changing SqlConnection timeout

You can set the timeout value in the connection string, but after you've connected it's read-only. You can read more at http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx

As Anil implies, ConnectionTimeout may not be what you need; it controls how long the ADO driver will wait when establishing a new connection. Your usage seems to indicate a need to wait longer than normal for a particular SQL query to execute, and in that case Anil is exactly right; use CommandTimeout (which is R/W) to change the expected completion time for an individual SqlCommand.

Timing Delays in VBA

Access can always use the Excel procedure as long as the project has the Microsoft Excel XX.X object reference included:

Call Excel.Application.Wait(DateAdd("s",10,Now()))

"fatal: Not a git repository (or any of the parent directories)" from git status

I just got this message and there is a very simple answer before trying the others. At the parent directory, type git init

This will initialize the directory for git. Then git add and git commit should work.

How to test the type of a thrown exception in Jest

Jest has a method, toThrow(error), to test that a function throws when it is called.

So, in your case you should call it so:

expect(t).toThrowError(TypeError);

The documentation.

Do HttpClient and HttpClientHandler have to be disposed between requests?

Dispose() calls the code below, which closes the connections opened by the HttpClient instance. The code was created by decompiling with dotPeek.

HttpClientHandler.cs - Dispose

ServicePointManager.CloseConnectionGroups(this.connectionGroupName);

If you don't call dispose then ServicePointManager.MaxServicePointIdleTime, which runs by a timer, will close the http connections. The default is 100 seconds.

ServicePointManager.cs

internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(ServicePointManager.IdleServicePointTimeoutCallback);
private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100000);

private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
  ServicePoint servicePoint = (ServicePoint) context;
  if (Logging.On)
    Logging.PrintInfo(Logging.Web, SR.GetString("net_log_closed_idle", (object) "ServicePoint", (object) servicePoint.GetHashCode()));
  lock (ServicePointManager.s_ServicePointTable)
    ServicePointManager.s_ServicePointTable.Remove((object) servicePoint.LookupString);
  servicePoint.ReleaseAllConnectionGroups();
}

If you haven't set the idle time to infinite then it appears safe not to call dispose and let the idle connection timer kick-in and close the connections for you, although it would be better for you to call dispose in a using statement if you know you are done with an HttpClient instance and free up the resources faster.

WCF on IIS8; *.svc handler mapping doesn't work

This was a really silly one for me. Adding this here as it's one of the more popular threads on svc 404 issues.

I had in my Project Settings' \ Web \ Project URL, pasted:

http://blah.webservice.local.blahblah.com/Blah.svc

And for some unknown reason (having done this a thousand times) didn't spot straight away that the name of the .svc file was at the end.

DOH!

I had just pasted the address from my WCF test client and hadn't checked it sufficiently. What this did in the background was create an IIS application at the .svc address and I was getting nothing out of IIS. I couldn't work out how I couldn't even hit the .svc file.

Simple fix, obviously, just remove the application in IIS and change the project URL.

After almost 20 years at this, you can still make schoolboy errors / rookie mistakes. Hope this helps someone.

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

The scheme is correct, User.ID must be the primary key of User, Job.ID should be the primary key of Job and Job.UserID should be a foreign key to User.ID. Also, your commands appear to be syntactically correct.

So what could be wrong? I believe you have at least a Job.UserID which doesn't have a pair in User.ID. For instance, if all values of User.ID are: 1,2,3,4,6,7,8 and you have a value of Job.UserID of 5 (which is not among 1,2,3,4,6,7,8, which are the possible values of UserID), you will not be able to create your foreign key constraint. Solution:

delete from Job where UserID in (select distinct User.ID from User);

will delete all jobs with nonexistent users. You might want to migrate these to a copy of this table which will contain archive data.

Searching in a ArrayList with custom objects for certain strings

contains() method just calls equals() on ArrayList elements, so you can overload your class's equals() based on the name class variable. Return true from equals() if name is equal to the matching String. Hope this helps.

Hashing with SHA1 Algorithm in C#

You can "compute the value for the specified byte array" using ComputeHash:

var hash = sha1.ComputeHash(temp);

If you want to analyse the result in string representation, then you will need to format the bytes using the {0:X2} format specifier.

How to allow only a number (digits and decimal point) to be typed in an input?

Use the step tag to set the minimum changeable value to some decimal number:

e.g. step="0.01"

<input type="number" step="0.01" min="0" class="form-control" 
name="form_name" id="your_id" placeholder="Please Input a decimal number" required>

There is some documentation on it here:

http://blog.isotoma.com/2012/03/html5-input-typenumber-and-decimalsfloats-in-chrome/

Spring Boot REST service exception handling

Solution with dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); and @EnableWebMvc @ControllerAdvice worked for me with Spring Boot 1.3.1, while was not working on 1.2.7

How can I replace newlines using PowerShell?

In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

Clarification: small files only folks! Please don't try this on your 40 GB log file :)

How to set a time zone (or a Kind) of a DateTime value?

While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.

Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter

How to build query string with Javascript

You don't actually need a form to do this with Prototype. Just use Object.toQueryString function:

Object.toQueryString({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' })

// -> 'action=ship&order_id=123&fees=f1&fees=f2&label=a%20demo'

Open Form2 from Form1, close Form1 from Form2

This works:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Hide()
    Form2.Show()

Can we write our own iterator in Java?

Sure. An iterator is just an implementation of the java.util.Iterator interface. If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.

Converting a string to a date in a cell

I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5))) where XX is the cell in reference.

I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.

"Keep Me Logged In" - the best approach

I asked one angle of this question here, and the answers will lead you to all the token-based timing-out cookie links you need.

Basically, you do not store the userId in the cookie. You store a one-time token (huge string) which the user uses to pick-up their old login session. Then to make it really secure, you ask for a password for heavy operations (like changing the password itself).

Is there a way to iterate over a dictionary?

The block approach avoids running the lookup algorithm for every key:

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
  NSLog(@"%@ => %@", key, value);
}];

Even though NSDictionary is implemented as a hashtable (which means that the cost of looking up an element is O(1)), lookups still slow down your iteration by a constant factor.

My measurements show that for a dictionary d of numbers ...

NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
  NSNumber* value = @(i);
  dict[value.stringValue] = value;
}

... summing up the numbers with the block approach ...

__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
  sum += value.intValue;
}];

... rather than the loop approach ...

int sum = 0;
for (NSString* key in dict)
  sum += [dict[key] intValue];

... is about 40% faster.

EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.

Pass in an array of Deferreds to $.when()

As a simple alternative, that does not require $.when.apply or an array, you can use the following pattern to generate a single promise for multiple parallel promises:

promise = $.when(promise, anotherPromise);

e.g.

function GetSomeDeferredStuff() {
    // Start with an empty resolved promise (or undefined does the same!)
    var promise;
    var i = 1;
    for (i = 1; i <= 5; i++) {
        var count = i;

        promise = $.when(promise,
        $.ajax({
            type: "POST",
            url: '/echo/html/',
            data: {
                html: "<p>Task #" + count + " complete.",
                delay: count / 2
            },
            success: function (data) {
                $("div").append(data);
            }
        }));
    }
    return promise;
}

$(function () {
    $("a").click(function () {
        var promise = GetSomeDeferredStuff();
        promise.then(function () {
            $("div").append("<p>All done!</p>");
        });
    });
});

Notes:

  • I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
  • The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested inside additional objects). For what you want though it is short and simple.
  • The upside is it requires no array or array management.

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

How to find length of a string array?

Since you haven't initialized car yet so it has no existence in JVM(Java Virtual Machine) so you have to initialize it first.

For instance :

car = new String{"Porsche","Lamborghini"};

Now your code will run fine.

INPUT:

String car [];
car = new String{"Porsche","Lamborghini"};
System.out.println(car.length);

OUTPUT:

2

How to get the fields in an Object via reflection?

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);
    }
}

To learn more about reflection, check the Sun tutorial on the subject.


That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);
        }
    }
}

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

How to make a DIV not wrap?

If I don't want to define a minimal width because I don't know the amount of elements the only thing that worked to me was:

display: inline-block;
white-space: nowrap;

But only in Chrome and Safari :/

Ruby, remove last N characters from a string?

name = "my text"
x.times do name.chop! end

Here in the console:

>name = "Nabucodonosor"
 => "Nabucodonosor" 
> 7.times do name.chop! end
 => 7 
> name
 => "Nabuco" 

How to use both onclick and target="_blank"

Just use window.open():

window.open('Prosjektplan.pdf')

Anyway, what guys are saying on comments is true. You better use <a target="_blank"> instead of click events.

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

AngularJS ng-click stopPropagation

ngClick directive (as well as all other event directives) creates $event variable which is available on same scope. This variable is a reference to JS event object and can be used to call stopPropagation():

<table>
  <tr ng-repeat="user in users" ng-click="showUser(user)">
    <td>{{user.firstname}}</td>
    <td>{{user.lastname}}</td>
    <td>
      <button class="btn" ng-click="deleteUser(user.id, $index); $event.stopPropagation();">
        Delete
      </button>
    </td>              
  </tr>
</table>

PLUNKER

What is a vertical tab?

I have found that the VT char is used in pptx text boxes at the end of each line shown in the box in oder to adjust the text to the size of the box. It seems to be automatically generated by powerpoint (not introduced by the user) in order to move the text to the next line and fix the complete text block to the text box. In the example below, in the position of §:

"This is a text §
inside a text box"

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

For anyone who stumbles across this in the future, this is how you do it:

xl.Range("A1:A1").Style := "Bad"
xl.Range("A1:A1").Style := "Good"
xl.Range("A1:A1").Style := "Neutral"

An easy way to check on things like this is to open excel and record a macro. In this case I recorded a macro where I just formatted the cell to "Bad". Once you've recorded the macro, just go in and edit it and it will essentially give you the code. It will require a little translation on your part, but here is what the macro looks like when I edit it:

 Selection.Style = "Bad"

As you can see, it's pretty easy to make the jump to AHK from what excel provides.

Combine two arrays

Warning! $array1 + $array2 overwrites keys, so my solution (for multidimensional arrays) is to use array_unique()

array_unique(array_merge($a, $b), SORT_REGULAR);

Notice:

5.2.10+ Changed the default value of sort_flags back to SORT_STRING.

5.2.9 Default is SORT_REGULAR.

5.2.8- Default is SORT_STRING

It perfectly works. Hope it helps same.

Java output formatting for Strings

EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though

Why not just generate a whitespace string dynamically to insert into the statement.

So if you want them all to start on the 50th character...

String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);

Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.

What is http multipart request?

I have found an excellent and relatively short explanation here.

A multipart request is a REST request containing several packed REST requests inside its entity.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

Core jQuery doesn't have anything special for touch events, but you can easily build your own using the following events

  • touchstart
  • touchmove
  • touchend
  • touchcancel

For example, the touchmove

document.addEventListener('touchmove', function(e) {
    e.preventDefault();
    var touch = e.touches[0];
    alert(touch.pageX + " - " + touch.pageY);
}, false);

This works in most WebKit based browsers (incl. Android).

Here is some good documentation.

Is it necessary to write HEAD, BODY and HTML tags?

Contrary to @Liza Daly's note about HTML5, that spec is actually quite specific about which tags can be omitted, and when (and the rules are a bit different from HTML 4.01, mostly to clarify where ambiguous elements like comments and whitespace belong)

The relevant reference is http://www.w3.org/TR/2011/WD-html5-20110525/syntax.html#optional-tags, and it says:

  • An html element's start tag may be omitted if the first thing inside the html element is not a comment.

  • An html element's end tag may be omitted if the html element is not immediately followed by a comment.

  • A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

  • A head element's end tag may be omitted if the head element is not immediately followed by a space character or a comment.

  • A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a script or style element.

  • A body element's end tag may be omitted if the body element is not immediately followed by a comment.

So your example is valid HTML5, and would be parsed like this, with the html, head and body tags in their implied positions:

<!DOCTYPE html><HTML><HEAD>     
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Page Title</title>
    <link rel="stylesheet" type="text/css" href="css/reset.css">
    <script src="js/head_script.js"></script></HEAD><BODY><!-- this script will be in head //-->


<div>Some html</div> <!-- here body starts //-->

    <script src="js/body_script.js"></script></BODY></HTML>

Note that the comment "this script will be in head" is actually parsed as part of the body, although the script itself is part of the head. According to the spec, if you want that to be different at all, then the </HEAD> and <BODY> tags may not be omitted. (Although the corresponding <HEAD> and </BODY> tags still can be)

What is the difference between buffer and cache memory in Linux?

Buffer is an area of memory used to temporarily store data while it's being moved from one place to another.

Cache is a temporary storage area used to store frequently accessed data for rapid access. Once the data is stored in the cache, future use can be done by accessing the cached copy rather than re-fetching the original data, so that the average access time is shorter.

Note: buffer and cache can be allocated on disk as well

How to upgrade Git to latest version on macOS?

Without Homebrew

  1. Use the installer from git's website.
  2. Update your ~/.bash_profile file. Notice this command differs from kmikael's answer by what it puts in the file:
    • Other command: export PATH=/usr/local/git/bin:/usr/local/sbin/:[and so on]
    • Below command: export PATH="/usr/local/git/bin:/usr/local/sbin:$PATH"
    • Use whichever one you prefer.

echo 'export PATH="/usr/local/git/bin:/usr/local/sbin:$PATH"' >> ~/.bash_profile

  1. If you're using Xcode, you'll need to add some symbolic links.
    • Example: ln -s /opt/local/bin/git /usr/bin/git
  2. Restart terminal.
    • which git should say the directory in the README.txt file from the dmg.
    • git --version should say the updated version.
    • echo $PATH should start with /usr/local/git/bin:/usr/local/sbin:

Java better way to delete file if exists

  File xx = new File("filename.txt");
    if (xx.exists()) {
       System.gc();//Added this part
       Thread.sleep(2000);////This part gives the Bufferedreaders and the InputStreams time to close Completely
       xx.delete();     
    }

AngularJs ReferenceError: angular is not defined

I ran into this because I made a copy-and-paste of ngBoilerplate into my project on a Mac without Finder showing hidden files. So .bower was not copied with the rest of ngBoilerplate. Thus bower moved resources to bower_components (defult) instead of vendor (as configured) and my app didn't get angular. Probably a corner case, but it might help someone here.

NHibernate.MappingException: No persister for: XYZ

Something obvious, yet quite useful for someone new to NHibernate.

All XML Mapping files should be treated as Embedded Resources rather than the default Content. This option is set by editing the Build Action attribute in the file's properties.

XML files are then embedded into the assembly, and parsed at project startup during NHibernate's configuration phase.

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!

String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.

It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!

String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).


Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.

That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.


Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.

System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

Warning: comparison with string literals results in unspecified behaviour

There is a distinction between 'a' and "a":

  • 'a' means the value of the character a.
  • "a" means the address of the memory location where the string "a" is stored (which will generally be in the data section of your program's memory space). At that memory location, you will have two bytes -- the character 'a' and the null terminator for the string.

Java "user.dir" property - what exactly does it mean?

System.getProperty("user.dir") fetches the directory or path of the workspace for the current project

Git clone particular version of remote repository

Unlike centralized version control systems, Git clones the entire repository, so you don't only get the current remote files, but the whole history. You local repository will include all this.

There might have been tags to mark a particular version at the time. If not, you can create them yourself locally. A good way to do this is to use git log or perhaps more visually with tools like gitk (perhaps gitk --all to see all the branches and tags). If you can spot the commits hashes that were used at the time, you can tag them using git tag <hash> and then check those out in new working copies (for example git checkout -b new_branch_name tag_name or directly with the hash instead of the tag name).

Entity Framework .Remove() vs. .DeleteObject()

If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()

ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

A thing worth noting is that setting .State = EntityState.Deleted does not trigger automatically detected change. (archive)

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

just run the android sdk manager , go to tools then obtions and a new window will apears mark the three checkboxes at the bottom and close it it worked for me

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Do you have access to the command prompt ?

Method 1 : Command Prompt

The specifics of the Java installed on the system can be determined by executing the following command java -version

Method 2 : Folder Structure

In case you do not have access to command prompt then determining the folder where Java.

32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

64 Bit : C:\Program Files\Java\jdk1.6.0_25

However during the installation it is possible that the user might change the installation folder.

Method 3 : Registry

You can also see the version installed in registry editor.

  1. Go to registry editor

  2. Edit -> Find

  3. Search for Java. You will get the registry entries for Java.

  4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

How to convert a factor to integer\numeric without loss of information?

You can use hablar::convert if you have a data frame. The syntax is easy:

Sample df

library(hablar)
library(dplyr)

df <- dplyr::tibble(a = as.factor(c("7", "3")),
                    b = as.factor(c("1.5", "6.3")))

Solution

df %>% 
  convert(num(a, b))

gives you:

# A tibble: 2 x 2
      a     b
  <dbl> <dbl>
1    7.  1.50
2    3.  6.30

Or if you want one column to be integer and one numeric:

df %>% 
  convert(int(a),
          num(b))

results in:

# A tibble: 2 x 2
      a     b
  <int> <dbl>
1     7  1.50
2     3  6.30

I have filtered my Excel data and now I want to number the rows. How do I do that?

Step 1: Highlight the entire column (not including the header) of the column you wish to populate

Step 2: (Using Kutools) On the Insert dropdown, click "Fill Custom List"

Step 3: Click Edit

Step 4: Create your list (For Ex: 1, 2)

Step 5: Choose your new custom list and then click "Fill Range"

DONE!!!

Invalid date in safari

Best way to do it is by using the following format:

new Date(year, month, day, hours, minutes, seconds, milliseconds)
var d = new Date(2018, 11, 24, 10, 33, 30, 0);

This is supported in all browsers and will not give you any issues. Please note that the months are written from 0 to 11.