Programs & Examples On #Cod

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How much should a function trust another function

Such debugging is part of the development process and should not be the issue at runtime.

Methods don't trust other methods. They all trust you. That is the process of developing. Fix all bugs. Then methods don't have to "trust". There should be no doubt.

So, write it as it should be. Do not make methods check wether other methods are working correctly. That should be tested by the developer when they wrote that function. If you suspect a method to be not doing what you want, debug it.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

need to add a class to an element

You probably need something like:

result.className = 'red'; 

In pure JavaScript you should use className to deal with classes. jQuery has an abstraction called addClass for it.

conflicting types for 'outchar'

It's because you haven't declared outchar before you use it. That means that the compiler will assume it's a function returning an int and taking an undefined number of undefined arguments.

You need to add a prototype pf the function before you use it:

void outchar(char);  /* Prototype (declaration) of a function to be called */  int main(void) {     ... }  void outchar(char ch) {     ... } 

Note the declaration of the main function differs from your code as well. It's actually a part of the official C specification, it must return an int and must take either a void argument or an int and a char** argument.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

Method Call Chaining; returning a pointer vs a reference?

It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

How do I get some variable from another class in Java?

The code that you have is correct. To get a variable from another class you need to create an instance of the class if the variable is not static, and just call the explicit method to get access to that variable. If you put get and set method like the above is the same of declaring that variable public.

Put the method setNum private and inside the getNum assign the value that you want, you will have "get" access to the variable in that case

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

this in equals method

You have to look how this is called:

someObject.equals(someOtherObj); 

This invokes the equals method on the instance of someObject. Now, inside that method:

public boolean equals(Object obj) {   if (obj == this) { //is someObject equal to obj, which in this case is someOtherObj?     return true;//If so, these are the same objects, and return true   } 

You can see that this is referring to the instance of the object that equals is called on. Note that equals() is non-static, and so must be called only on objects that have been instantiated.

Note that == is only checking to see if there is referential equality; that is, the reference of this and obj are pointing to the same place in memory. Such references are naturally equal:

Object a = new Object(); Object b = a; //sets the reference to b to point to the same place as a Object c = a; //same with c b.equals(c);//true, because everything is pointing to the same place 

Further note that equals() is generally used to also determine value equality. Thus, even if the object references are pointing to different places, it will check the internals to determine if those objects are the same:

FancyNumber a = new FancyNumber(2);//Internally, I set a field to 2 FancyNumber b = new FancyNumber(2);//Internally, I set a field to 2 a.equals(b);//true, because we define two FancyNumber objects to be equal if their internal field is set to the same thing. 

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

Ruby - ignore "exit" in code

One hackish way to define an exit method in context:

class Bar; def exit; end; end 

This works because exit in the initializer will be resolved as self.exit1. In addition, this approach allows using the object after it has been created, as in: b = B.new.

But really, one shouldn't be doing this: don't have exit (or even puts) there to begin with.

(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)


1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit normally resolves to Object#exit. However, this can be changed by introducing an overridden method as shown - nothing fancy.

String index out of range: 4

You are using the wrong iteration counter, replace inp.charAt(i) with inp.charAt(j).

python variable NameError

Initialize tSize to

tSize = ""  

before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Passing multiple values for same variable in stored procedure

Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.

To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Instantiating a generic type

You cannot do new T() due to type erasure. The default constructor can only be

public Navigation() {     this("", "", null); } 

​ You can create other constructors to provide default values for trigger and description. You need an concrete object of T.

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

When to create variables (memory management)

In your example number is a primitive, so will be stored as a value.

If you want to use a reference then you should use one of the wrapper types (e.g. Integer)

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

Difference between opening a file in binary vs text

The most important difference to be aware of is that with a stream opened in text mode you get newline translation on non-*nix systems (it's also used for network communications, but this isn't supported by the standard library). In *nix newline is just ASCII linefeed, \n, both for internal and external representation of text. In Windows the external representation often uses a carriage return + linefeed pair, "CRLF" (ASCII codes 13 and 10), which is converted to a single \n on input, and conversely on output.


From the C99 standard (the N869 draft document), §7.19.2/2,

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

And in §7.19.3/2

Binary files are not truncated, except as defined in 7.19.5.3. Whether a write on a text stream causes the associated file to be truncated beyond that point is implementation- defined.

About use of fseek, in §7.19.9.2/4:

For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.

About use of ftell, in §17.19.9.4:

The ftell function obtains the current value of the file position indicator for the stream pointed to by stream. For a binary stream, the value is the number of characters from the beginning of the file. For a text stream, its file position indicator contains unspecified information, usable by the fseek function for returning the file position indicator for the stream to its position at the time of the ftell call; the difference between two such return values is not necessarily a meaningful measure of the number of characters written or read.

I think that’s the most important, but there are some more details.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

Intermediate language used in scalac?

The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/

You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.

Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?

Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Removing "http://" from a string

Try this out:

$url = 'http://techcrunch.com/startups/'; $url = str_replace(array('http://', 'https://'), '', $url); 

EDIT:

Or, a simple way to always remove the protocol:

$url = 'https://www.google.com/'; $url = preg_replace('@^.+?\:\/\/@', '', $url); 

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

php & mysql query not echoing in html with tags?

I can spot a few different problems with this. However, in the interest of time, try this chunk of code instead:

<?php require 'db.php'; ?>  <?php if (isset($_POST['search'])) {     $limit = $_POST['limit'];     $country = $_POST['country'];     $state = $_POST['state'];     $city = $_POST['city'];     $data = mysqli_query(         $link,         "SELECT * FROM proxies WHERE country = '{$country}' AND state = '{$state}' AND city = '{$city}' LIMIT {$limit}"     );     while ($assoc = mysqli_fetch_assoc($data)) {         $proxy = $assoc['proxy'];         ?>             <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"                 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">             <html xmlns="http://www.w3.org/1999/xhtml">                 <head>                     <title>Sock5Proxies</title>                     <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />                     <link href="./style.css" rel="stylesheet" type="text/css" />                     <link href="./buttons.css" rel="stylesheet" type="text/css" />                 </head>                 <body>                     <center>                         <h1>Sock5Proxies</h1>                     </center>                     <div id="wrapper">                         <div id="header">                             <ul id="nav">                                 <li class="active"><a href="index.html"><span></span>Home</a></li>                                 <li><a href="leads.html"><span></span>Leads</a></li>                                 <li><a href="payout.php"><span></span>Pay out</a></li>                                 <li><a href="contact.html"><span></span>Contact</a></li>                                 <li><a href="logout.php"><span></span>Logout</a></li>                             </ul>                         </div>                         <div id="content">                             <div id="center">                                 <table cellpadding="0" cellspacing="0" style="width:690px">                                     <thead>                                     <tr>                                         <th width="75" class="first">Proxy</th>                                         <th width="50" class="last">Status</th>                                     </tr>                                     </thead>                                     <tbody>                                     <tr class="rowB">                                         <td class="first"> <?php echo $proxy ?> </td>                                         <td class="last">Check</td>                                     </tr>                                     </tbody>                                 </table>                             </div>                         </div>                         <div id="footer"></div>                         <span id="about">Version 1.0</span>                     </div>                 </body>             </html>         <?php     } } ?> <html> <form action="" method="POST">     <input type="text" name="limit" placeholder="10" /><br>     <input type="text" name="country" placeholder="Country" /><br>     <input type="text" name="state" placeholder="State" /><br>     <input type="text" name="city" placeholder="City" /><br>     <input type="submit" name="search" value="Search" /><br> </form> </html> 

Comparing two joda DateTime instances

DateTime inherits its equals method from AbstractInstant. It is implemented as such

public boolean equals(Object readableInstant) {     // must be to fulfil ReadableInstant contract     if (this == readableInstant) {         return true;     }     if (readableInstant instanceof ReadableInstant == false) {         return false;     }     ReadableInstant otherInstant = (ReadableInstant) readableInstant;     return         getMillis() == otherInstant.getMillis() &&         FieldUtils.equals(getChronology(), otherInstant.getChronology()); } 

Notice the last line comparing chronology. It's possible your instances' chronologies are different.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

If the error is

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

Step1: stop the server

Step2: run commands are npm uninstall node-sass

Step3: check node-sass in package.json if node-sass is available in the file then again run Step2.

Step4: npm install [email protected] <=== run command

Step5: wait until the command successfully runs.

Step6: start-server using npm start

Target class controller does not exist - Laravel 8

in laravel-8 default remove namespace prefix so you can set old way in laravel-7 like:

in RouteServiceProvider.php add this variable

protected $namespace = 'App\Http\Controllers';

and update boot method

public function boot()
{
       $this->configureRateLimiting();

       $this->routes(function () {
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
        });
}

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

If you have trouble in Xcode 12 with simulators, not real device, yes you have to remove VALID_ARCHS settings because it's not supported anymore. Go to "builds settings", search "VALID_ARCHS" and remove the user-defined properties. Do it in every target you have.

Still, you may need to add a script at the bottom of your podfile to have pods compiling with the right architecture and deployment target :

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
      config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
     end
  end
end

DevTools failed to load SourceMap: Could not load content for chrome-extension

I appreciate this is part of your extensions, but I see this message in all sorts of places these days, and I hate it: how I fixed it (EDIT: this fix seems to massively speed up the browser too) was by adding a dead file

  1. physically create the file it wants\ where it wants, as a blank file (EG: "popper.min.js.map")

  2. put this in the blank file

    {
     "version": 1,
     "mappings": "",
     "sources": [],
     "names": [],
     "file": "popper.min.js"
    }
    
  3. make sure that "file": "*******" in the content of the blank file MATCHES the name of your file ******.map (minus the word ".map")

(EDIT: I suspect you could physically add this dead file method to the addon yourself)

When adding a Javascript library, Chrome complains about a missing source map, why?

In my case I had to remove React Dev Tools from Chrome to stop seeing the strange errors during development of React app using a local Express server with a create-react-app client (which uses Webpack). In the interest of community I did a sanity check and quit everything - server/client server/Chrome - and then I opened Chrome and reinstalled React Dev Tools... Started things back up and am seeing this funky address and error again: Error seems to be from React Dev Tools extension in my case

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Just go to your tsconfig.app.json in your project and remove all from it

and copy below code and paste it. It will solve your issue :)

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],
  },

  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "angularCompilerOptions": {
    "enableIvy": false
  }
}

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

In my case, it was because I (at one point) had reactn installed, which also includes its own version of React (for some reason).

After that had been installed (even after uninstalling again), this error occured.

I simply removed node_modules and ran npm install again, and it worked.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

TS1086: An accessor cannot be declared in ambient context

Quick solution: Update package.json

"devDependencies": {
   ...
   "typescript": "~3.7.4",
 }

In tsconfig.json

{
    ...,
    "angularCompilerOptions": {
       ...,
       "disableTypeScriptVersionCheck": true
    }
}

then remove node_modules folder and reinstall with

npm install

For more visit here

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.

Maven dependencies are failing with a 501 error

Add this in pom.xml file. It works fine for me

<pluginRepositories>
    <pluginRepository>
        <id>central</id>
        <name>Central Repository</name>
        <url>https://repo.maven.apache.org/maven2</url>
        <layout>default</layout>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
        <releases>
            <updatePolicy>never</updatePolicy>
        </releases>
    </pluginRepository>
</pluginRepositories>

<repositories>
    <repository>
        <id>central</id>
        <name>Central Repository</name>
        <url>https://repo.maven.apache.org/maven2</url>
        <layout>default</layout>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

IntelliJ: Error:java: error: release version 5 not supported

I've done most things you are proposing with Java compiler and bytecode and solved the problem in the past. It's been almost 1 month since I ran my Java code (and back then everything was fixed), but now the problem appeared again. Don't know why, pretty annoyed though!

This time the solution was: Right click to project name -> Open module settings F4 -> Language level ...and there you can define the language level your project/pc is.

No maven/pom configuration worked for me both in the past and now and I've already set the Java compiler and bytecode at 12.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

Template not provided using create-react-app

One of the easiest way to do it is by using

npx --ignore-existing create-react-app [project name]

This will remove the old cached version of create-react-app and then get the new version to create the project.

Note: Adding the name of the project is important as just ignoring the existing create-react-app version is stale and the changes in your machines global env is temporary and hence later just using npx create-react-app [project name] will not provide the desired result.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

This solution may help you if you know your problem is limited to Facades and you are running Laravel 5.5 or above.

Install laravel-ide-helper

composer require --dev barryvdh/laravel-ide-helper

Add this conditional statement in your AppServiceProvider to register the helper class.

public function register()
{
    if ($this->app->environment() !== 'production') {
        $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
    }
    // ...
}

Then run php artisan ide-helper:generate to generate a file to help the IDE understand Facades. You will need to restart Visual Studio Code.

References

https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/16

https://github.com/barryvdh/laravel-ide-helper

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

If you are using ruby-2.7.0 on MacOS Catalina 10.15

$ brew reinstall [email protected]

or

$ rvm reinstall 2.7.0
$ brew tap --repair
$ brew doctor

What does 'x packages are looking for funding' mean when running `npm install`?

You can skip fund using:

npm install --no-fund YOUR PACKAGE NAME

For example :

npm install --no-fund core-js

@angular/material/index.d.ts' is not a module

Do npm i -g @angular/material --save to solve the problem

SyntaxError: Cannot use import statement outside a module

I had this issue when I was running migration

Its es5 vs es6 issue

Here is how I solved it

I run

npm install @babel/register

and add

require("@babel/register")

at the top of my .sequelizerc file my

and go ahead to run my sequelize migrate. This is applicable to other things apart from sequelize

babel does the transpiling

SameSite warning Chrome 77

When it comes to Google Analytics I found raik's answer at Secure Google tracking cookies very useful. It set secure and samesite to a value.

ga('create', 'UA-XXXXX-Y', {
    cookieFlags: 'max-age=7200;secure;samesite=none'
});

Also more info in this blog post

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

This error is currently being fixed: https://chromium-review.googlesource.com/c/chromium/src/+/2001234

But it helped me, changing nginx settings:

  • turning on gzip;
  • add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
  • expires off;

In my case, Nginx acts as a reverse proxy for Node.js application.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module" to both external as well as internal js scripts.

Say, you have a file 'module.js':

var a = 10;
export {a};

You can use it in an external script, in which you do the import, eg.:

<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>

test.js:

import {a} from "./module.js";
alert(a);

You can also use it in an internal script, eg.:

<!DOCTYPE html><html><body>
<script type="module">
    import {a} from "./module.js";
    alert(a);
</script>
</body></html>

It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:

import {a} from "module.js";     // this won't work

How to fix "set SameSite cookie to none" warning?

I am using both JavaScript Cookie and Java CookieUtil in my project, below settings solved my problem:

JavaScript Cookie

var d = new Date();
d.setTime(d.getTime() + (30*24*60*60*1000)); //keep cookie 30 days
var expires = "expires=" + d.toGMTString();         
document.cookie = "visitName" + "=Hailin;" + expires + ";path=/;SameSite=None;Secure"; //can set SameSite=Lax also

JAVA Cookie (set proxy_cookie_path in Nginx)

location / {
   proxy_pass http://96.xx.xx.34;
   proxy_intercept_errors on;
   #can set SameSite=None also
   proxy_cookie_path / "/;SameSite=Lax;secure";
   proxy_connect_timeout 600;
   proxy_read_timeout 600;
}

Check result in Firefox enter image description here

Read more on https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I was facing same problem when I installed JRE by Oracle and solved this problem after my research.

I moved the environment path C:\Program Files (x86)\Common Files\Oracle\Java\javapath below H:\Program Files\Java\jdk-13.0.1\bin

Like this:

Path

H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath

OR

Path

%JAVA_HOME%
%JRE_HOME%

How to resolve the error on 'react-native start'

Fix it by install metro-config of the latest version (0.57.0 for now) they had fixed the problem:

npm install metro-config

you can remove it later, after react-native guys update module versions

Why powershell does not run Angular commands?

open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.

Server Discovery And Monitoring engine is deprecated

It is simple , remove the code that you have used and use the below code :

const url = 'mongodb://localhost:27017';
var dbConn = mongodb.MongoClient.connect(url, {useUnifiedTopology: true});

A failure occurred while executing com.android.build.gradle.internal.tasks

I got an stacktrace similar to yours only when building to Lollipop or Marshmallow, and the solution was to disable Advanved profiling.

Find it here:

Run -> Edit Configurations -> Profiling -> Enable advanced profiling

https://stackoverflow.com/a/58029739/860488

error: This is probably not a problem with npm. There is likely additional logging output above

Delete node_module directory and run below in command line

rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
npm install

If still not working, try below

npm install webpack --save

Unable to allocate array with shape and data type

I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the pagefile size, as it was a Memory overcommitment problem for me too.

Windows 8

  1. On the Keyboard Press the WindowsKey + X then click System in the popup menu
  2. Tap or click Advanced system settings. You might be asked for an admin password or to confirm your choice
  3. On the Advanced tab, under Performance, tap or click Settings.
  4. Tap or click the Advanced tab, and then, under Virtual memory, tap or click Change
  5. Clear the Automatically manage paging file size for all drives check box.
  6. Under Drive [Volume Label], tap or click the drive that contains the paging file you want to change
  7. Tap or click Custom size, enter a new size in megabytes in the initial size (MB) or Maximum size (MB) box, tap or click Set, and then tap or click OK
  8. Reboot your system

Windows 10

  1. Press the Windows key
  2. Type SystemPropertiesAdvanced
  3. Click Run as administrator
  4. Under Performance, click Settings
  5. Select the Advanced tab
  6. Select Change...
  7. Uncheck Automatically managing paging file size for all drives
  8. Then select Custom size and fill in the appropriate size
  9. Press Set then press OK then exit from the Virtual Memory, Performance Options, and System Properties Dialog
  10. Reboot your system

Note: I did not have the enough memory on my system for the ~282GB in this example but for my particular case this worked.

EDIT

From here the suggested recommendations for page file size:

There is a formula for calculating the correct pagefile size. Initial size is one and a half (1.5) x the amount of total system memory. Maximum size is three (3) x the initial size. So let's say you have 4 GB (1 GB = 1,024 MB x 4 = 4,096 MB) of memory. The initial size would be 1.5 x 4,096 = 6,144 MB and the maximum size would be 3 x 6,144 = 18,432 MB.

Some things to keep in mind from here:

However, this does not take into consideration other important factors and system settings that may be unique to your computer. Again, let Windows choose what to use instead of relying on some arbitrary formula that worked on a different computer.

Also:

Increasing page file size may help prevent instabilities and crashing in Windows. However, a hard drive read/write times are much slower than what they would be if the data were in your computer memory. Having a larger page file is going to add extra work for your hard drive, causing everything else to run slower. Page file size should only be increased when encountering out-of-memory errors, and only as a temporary fix. A better solution is to adding more memory to the computer.

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I use this:

interface IObjectKeys {
  [key: string]: string | number;
}

interface IDevice extends IObjectKeys {
  id: number;
  room_id: number;
  name: string;
  type: string;
  description: string;
}

If you use the optional property in your object:

interface IDevice extends IObjectKeys {
  id: number;
  room_id?: number;
  name?: string;
  type?: string;
  description?: string;
}

... you should add 'undefined' value into the IObjectKeys interface:

interface IObjectKeys {
  [key: string]: string | number | undefined;
}

dotnet ef not found in .NET Core 3

I was having this problem after I installed the dotnet-ef tool using Ansible with sudo escalated previllage on Ubuntu. I had to add become: no for the Playbook task, then the dotnet-ef tool became available to the current user.

  - name: install dotnet tool dotnet-ef
    command: dotnet tool install --global dotnet-ef --version {{dotnetef_version}}
    become: no

"Permission Denied" trying to run Python on Windows 10

This appears to be a limitation in git-bash. The recommendation to use winpty python.exe worked for me. See Python not working in the command line of git bash for additional information.

Adding Git-Bash to the new Windows Terminal

I did as follows:

  1. Add "%programfiles%\Git\Bin" to your PATH
  2. On the profiles.json, set the desired command-line as "commandline" : "sh --cd-to-home"
  3. Restart the Windows Terminal

It worked for me.

Angular @ViewChild() error: Expected 2 arguments, but got 1

In Angular 8 , ViewChild takes 2 parameters

 @ViewChild(ChildDirective, {static: false}) Component

Invalid hook call. Hooks can only be called inside of the body of a function component

happens also when you use a dependency without installing it. happen to me when i called MenuIcon from '@material-ui/icons/' when was missing in the project.

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

This was what I did to solve my related problem

interface Map {
  [key: string]: string | undefined
}

const HUMAN_MAP: Map = {
  draft: "Draft",
}

export const human = (str: string) => HUMAN_MAP[str] || str

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

  1. open cmd from current project
  2. npm uninstall @angular-devkit/build-angular
  3. npm install --save-dev @angular-devkit/build-angular

Make a VStack fill the width of the screen in SwiftUI

This is a useful bit of code:

extension View {
    func expandable () -> some View {
        ZStack {
            Color.clear
            self
        }
    }
}

Compare the results with and without the .expandable() modifier:

Text("hello")
    .background(Color.blue)

-

Text("hello")
    .expandable()
    .background(Color.blue)

enter image description here

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.

Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"

In your spring config,class

@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.

SwiftUI - How do I change the background color of a View?

Xcode 11.5

Simply use ZStack to add background color or images to your main view in SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.black
        }
        .edgesIgnoringSafeArea(.vertical)
    }
}

How to style components using makeStyles and still have lifecycle methods in Material UI?

Instead of converting the class to a function, an easy step would be to create a function to include the jsx for the component which uses the 'classes', in your case the <container></container> and then call this function inside the return of the class render() as a tag. This way you are moving out the hook to a function from the class. It worked perfectly for me. In my case it was a <table> which i moved to a function- TableStmt outside and called this function inside the render as <TableStmt/>

Errors: Data path ".builders['app-shell']" should have required property 'class'

This setting works well under angular 8:

Package.json:

...
"dependencies": {
  "@angular/animations": "^8.2.14",
  "@angular/cdk": "8.2.3",
  "@angular/common": "^8.2.14",
  "@angular/compiler": "^8.2.14",
  "@angular/core": "^8.2.14",

...

"devDependencies": {
  "@angular-devkit/build-angular": "~0.803.29",
  "@angular/cli": "~8.3.29",
  "@angular/compiler-cli": "^8.2.14"

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

For temporary testing during development we can disable it by opening chrome with disabled web security like this.

Open command line terminal and go to folder where chrome is installed i.e. C:\Program Files (x86)\Google\Chrome\Application

Enter this command:

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

A new browser window will open with disabled web security. Use it only for testing your app.

Understanding esModuleInterop in tsconfig file

Problem statement

Problem occurs when we want to import CommonJS module into ES6 module codebase.

Before these flags we had to import CommonJS modules with star (* as something) import:

// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec

// transpiled js (simplified):
const moment = require("moment");
moment();

We can see that * was somehow equivalent to exports variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment in our case) can be only a plain object, not callable (moment() is not allowed).

Solution

With flag esModuleInterop we can import CommonJS modules in compliance with es6 modules spec. Now our import code looks like this:

// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec

// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();

It works and it's perfectly valid with es6 modules spec, because moment is not namespace from star import, it's default import.

But how does it work? As you can see, because we did a default import, we called the default property on a moment object. But we didn't declare a default property on the exports object in the moment library. The key is the __importDefault function. It assigns module (exports) to the default property for CommonJS modules:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default key. This makes it possible to import defaults on CommonJS modules.

__importStar does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default property:

// index.ts file in our app
import * as moment from 'moment'

// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};

Synthetic imports

And what about allowSyntheticDefaultImports - what is it for? Now the docs should be clear:

Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

In moment typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop on. So allowSyntheticDefaultImports will not report an error if we want to import default from a third-party module which doesn't have a default export.

Why am I getting Unknown error in line 1 of pom.xml?

Following actions worked for me.

1.Go to Project in toolbar -> Unchecked "Build Automatically"

2.In POM File,Downgrade the spring-boot version to 2.1.4 RELEASE.

3.Right Click on Project name -> Select Maven -> Click on "Update Project". ->OK Wait till all the maven dependency to get downloaded(Need internet).

How to fix ReferenceError: primordials is not defined in node

I have tried a lot of suggestions to fix this problem for an existing project on my Windows 10 machine and ended up following these steps to fix it;

  • Uninstall Node.js from "Add or remove programs". Fire up a new Command prompt and type gulp -v and then node -v to check that it has been uninstalled completely.
  • Download and install Node.js v10.16.0 - not the latest as latest node & gulp combination is causing the problem as far as I see. During installation I didn't change the installation path which I normally do(C:\Program Files\nodejs).
  • Open up a new Command prompt, go to your project's directory where you have got your gulpfile.js and start gulp as shown in the image.

Please note sometimes when I switch between git branches I might need to close my Visual Studio and run it as Admin again in order to see this solution working again.

As far as I see this problem started to happen after I installed the latest recommended version(12.18.4) of Node.js for a new project and I only realised this when some FE changes weren't reflected on the existing web project.

enter image description here

How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?

Yes, installing previous a version of numpy solved the problem.

For those who uses PyCharm IDE:

in my IDE (Pycharm), File->Settings->Project Interpreter: I found my numpy to be 1.16.3, so I revert back to 1.16.1. Click + and type numpy in the search, tick "specify version" : 1.16.1 and choose--> install package.

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

How to fix missing dependency warning when using useEffect React Hook?

./src/components/BusinessesList.js
Line 51:  React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array  react-hooks/exhaustive-deps

It's not JS/React error but eslint (eslint-plugin-react-hooks) warning.

It's telling you that hook depends on function fetchBusinesses, so you should pass it as dependency.

useEffect(() => {
  fetchBusinesses();
}, [fetchBusinesses]);

It could result in invoking function every render if function is declared in component like:

const Component = () => {
  /*...*/

  //new function declaration every render
  const fetchBusinesses = () => {
    fetch('/api/businesses/')
      .then(...)
  }

  useEffect(() => {
    fetchBusinesses();
  }, [fetchBusinesses]);

  /*...*/
}

because every time function is redeclared with new reference

Correct way of doing this stuff is:

const Component = () => {
  /*...*/

  // keep function reference
  const fetchBusinesses = useCallback(() => {
    fetch('/api/businesses/')
      .then(...)
  }, [/* additional dependencies */]) 

  useEffect(() => {
    fetchBusinesses();
  }, [fetchBusinesses]);

  /*...*/
}

or just defining function in useEffect

More: https://github.com/facebook/react/issues/14920

React Native Error: ENOSPC: System limit for number of file watchers reached

It happened to me with a node app I was developing on a Debian based distro. First, a simple restart solved it, but it happened again on another app.

Since it's related with the number of watchers that inotify uses to monitors files and look for changes in a directory, you have to set a higher number as limit:

I was able to solve it from the answer posted here (thanks to him!)

So, I ran:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Read more about what’s happening at https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers#the-technical-details

Hope it helps!

How to update core-js to core-js@3 dependency?

Install

npm i core-js

Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.

Read: https://www.npmjs.com/package/core-js

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Based on responses and comments below, the following was the simple solution for my issue and THIS WORKED. Now my app, Match4app, is fully compatible with latest iOS versions!

  1. Download Xcode 10.2 from a direct link (not from App Store). (Estimated Size: ~6Gb)
  2. From the downloaded version just copy/paste the DeviceSupport/12.2 directory into "Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
  3. You can discard the downloaded version now (we just need the small 12.2 directory!)

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Try These steps if you have tried everything mentioned in above solutions:

  1. Create File in android/app/src/main/assets
  2. Run the following command :

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

  1. Now run your command to build for e.g. react-native run-android

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try following command sequence on Ubuntu terminal:

sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip

Module not found: Error: Can't resolve 'core-js/es6'

Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts (Optional).

  • From: import 'core-js/es6/symbol';
  • To: import 'core-js/es/symbol';

Updating Anaconda fails: Environment Not Writable Error

If you get this error under Linux when running conda using sudo, you might be suffering from bug #7267:

When logging in as non-root user via sudo, e.g. by:

sudo -u myuser -i

conda seems to assume that it is run as root and raises an error.

The only known workaround seems to be: Add the following line to your ~/.bashrc:

unset SUDO_UID SUDO_GID SUDO_USER

...or unset the ENV variables by running the line in a different way before running conda.

If you mistakenly installed anaconda/miniconda as root/via sudo this can also lead to the same error, then you might want to do the following:

sudo chown -R username /path/to/anaconda3

Tested with conda 4.6.14.

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

For Angular Developers

Although, I'm answering this very late. I have a bad habit of checking changelogs of every library I use and while checking the release notes of Angular CLI, I figured out that they released a new patch yesterday (9th Jan 2020) which fixes this issue.

https://github.com/angular/angular-cli/releases/tag/v8.3.22

So when you will run ng update, you should get updates for @angular/cli:

enter image description here

And running ng update @angular/cli will fix this warning.

Cheers!

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

In my case, the issue was with my Xcode build scheme. When you run react-native run-ios you may see something like,

  • info Found Xcode workspace "myproject.xcworkspace"*

  • info Building (using "xcodebuild -workspace myproject.xcworkspace -configuration Debug -scheme myproject -destination id=xxxxxxxx-xxxxx-xxxxx-xxxx-xxxxxxxxx -derivedDataPath build/myproject")*


In this case, there should be a scheme named myproject in your ios configurations. The way I fixed it is,

Double clicked on myproject.xcworkspace in ios directory (to open workspace with Xcode)

Navigate into Product > Scheme > Manage Schemes...

Created a Scheme appropriately with name myproject (this name is case-sensitive)

Ran react-native run-ios in project directory

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

I had the same problem and solved it by simply downloading a chromedriver file for a previous version of chrome. I have found that version 79 of Chrome is compatible with the current version of Selenium.

I then saved it in a specified path, and linked that path to my webdriver.

The exact steps are specified in this link: http://chromedriver.chromium.org/downloads

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

add @method('PUT') on the form

exp:

<form action="..." method="POST">

@csrf  

@method('PUT')



</form>

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

try this

import tensorflow as tf

tf.compat.v1.disable_eager_execution()

hello = tf.constant('Hello, TensorFlow!')

sess = tf.compat.v1.Session()

print(sess.run(hello))

react hooks useEffect() cleanup for only componentWillUnmount?

Since the cleanup is not dependent on the username, you could put the cleanup in a separate useEffect that is given an empty array as second argument.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
  const [name, setName] = useState("");_x000D_
  const [username, setUsername] = useState("");_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      console.log("effect");_x000D_
    },_x000D_
    [username]_x000D_
  );_x000D_
_x000D_
  useEffect(() => {_x000D_
    return () => {_x000D_
      console.log("cleaned up");_x000D_
    };_x000D_
  }, []);_x000D_
_x000D_
  const handleName = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setName(value);_x000D_
  };_x000D_
_x000D_
  const handleUsername = e => {_x000D_
    const { value } = e.target;_x000D_
_x000D_
    setUsername(value);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <div>_x000D_
        <input value={name} onChange={handleName} />_x000D_
        <input value={username} onChange={handleUsername} />_x000D_
      </div>_x000D_
      <div>_x000D_
        <div>_x000D_
          <span>{name}</span>_x000D_
        </div>_x000D_
        <div>_x000D_
          <span>{username}</span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
function App() {_x000D_
  const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(() => {_x000D_
      setShouldRender(false);_x000D_
    }, 5000);_x000D_
  }, []);_x000D_
_x000D_
  return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Jupyter Notebook not saving: '_xsrf' argument missing from post

The easiest way I found is this:

https://github.com/nteract/hydrogen/issues/922#issuecomment-405456346

Just open another (non-running, existing) notebook on the same kernel, and the issue is magically gone; you can again save the notebooks that were previously showing the _xsrf error.

If you have already closed the Jupyter home page, you can find a link to it on the terminal from which Jupyter was started.

How to use callback with useState hook in react

_x000D_
_x000D_
function Parent() {_x000D_
  const [Name, setName] = useState("");_x000D_
  getChildChange = getChildChange.bind(this);_x000D_
  function getChildChange(value) {_x000D_
    setName(value);_x000D_
  }_x000D_
_x000D_
  return <div> {Name} :_x000D_
    <Child getChildChange={getChildChange} ></Child>_x000D_
  </div>_x000D_
}_x000D_
_x000D_
function Child(props) {_x000D_
  const [Name, setName] = useState("");_x000D_
  handleChange = handleChange.bind(this);_x000D_
  collectState = collectState.bind(this);_x000D_
  _x000D_
  function handleChange(ele) {_x000D_
    setName(ele.target.value);_x000D_
  }_x000D_
_x000D_
  function collectState() {_x000D_
    return Name;_x000D_
  }_x000D_
  _x000D_
   useEffect(() => {_x000D_
    props.getChildChange(collectState());_x000D_
   });_x000D_
_x000D_
  return (<div>_x000D_
    <input onChange={handleChange} value={Name}></input>_x000D_
  </div>);_x000D_
} 
_x000D_
_x000D_
_x000D_

useEffect act as componentDidMount, componentDidUpdate, so after updating state it will work

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Cannot edit in read-only editor VS Code

Click on the file and hover on Preferences. there you will find the first option as Settings and click on that. There search run code. and scroll and find the option code runner: Run in Terminal. now check the option below it

Why am I seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors after upgrading to Cordova Android 8?

In an Ionic 4 capacitor project, when I packaged and deployed to android phone for testing I got this error. Resolved by re-installing capacitor and updating android platform.

npm run build --prod --release
npx cap copy
npm install --save @capacitor/core @capacitor/cli
npx cap init
npx cap update android
npx cap open android

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

We can apply the project deployment target to all pods target. Resolved by adding this code block below to end of your Podfile:

post_install do |installer|
  fix_deployment_target(installer)
end

def fix_deployment_target(installer)
  return if !installer
  project = installer.pods_project
  project_deployment_target = project.build_configurations.first.build_settings['IPHONEOS_DEPLOYMENT_TARGET']

  puts "Make sure all pods deployment target is #{project_deployment_target.green}"
  project.targets.each do |target|
    puts "  #{target.name}".blue
    target.build_configurations.each do |config|
      old_target = config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']
      new_target = project_deployment_target
      next if old_target == new_target
      puts "    #{config.name}: #{old_target.yellow} -> #{new_target.green}"
      config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = new_target
    end
  end
end

Results log:

fix pods deployment target version warning

How to Install pip for python 3.7 on Ubuntu 18?

To install all currently supported python versions (python 3.6 is already pre-installed) including pip for Ubuntu 18.04 do the following:

To install python3.5 and python3.7, use the deadsnakes ppa:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.5
sudo apt-get install python3.7

Install python2.7 via distribution packages:

sudo apt install python-minimal  # on Ubuntu 18.04 python-minimal maps to python2.7

To install pip use:

sudo apt install python-pip  # on Ubuntu 18.04 this refers to pip for python2.7
sudo apt install python3-pip  # on Ubuntu 18.04 this refers to pip for python3.6
python3.5 -m pip install pip # this will install pip only for the current user
python3.7 -m pip install pip

I used it for setting up a CI-chain for a python project with tox and Jenkins.

Flutter Countdown Timer

doesnt directly answer your question. But helpful for those who want to start something after some time.

Future.delayed(Duration(seconds: 1), () {
            print('yo hey');
          });

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Typescript: Type 'string | undefined' is not assignable to type 'string'

try to find out what the actual value is beforehand. If person has a valid name, assign it to name1, else assign undefined.

let name1: string = (person.name) ? person.name : undefined;

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

For those newbies like me, don't assign variable to service response, meaning do

export class ShopComponent implements OnInit {
  public productsArray: Product[];

  ngOnInit() {
      this.productService.getProducts().subscribe(res => {
        this.productsArray = res;
      });
  }
}

Instead of

export class ShopComponent implements OnInit {
    public productsArray: Product[];

    ngOnInit() {
        this.productsArray = this.productService.getProducts().subscribe();
    }
}

How do I prevent Conda from activating the base environment by default?

I have conda 4.6 with a similar block of code that was added by conda. In my case, there's a conda configuration setting to disable the automatic base activation:

conda config --set auto_activate_base false

The first time you run it, it'll create a ./condarc in your home directory with that setting to override the default.

This wouldn't de-clutter your .bash_profile but it's a cleaner solution without manual editing that section that conda manages.

Gradle: Could not determine java version from '11.0.2'

I had the same problem here. In my case I need to use an old version of JDK and I'm using sdkmanager to manage the versions of JDK, so, I changed the version of the virtual machine to 1.8.

sdk use java 8.0.222.j9-adpt

After that, the app runs as expected here.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

MacOS Catalina

Step 1: Changing Android Studio Preference

  1. Open-up your Android Studio
  2. Press Command+, or go to top-left AppBar Android Studio > Preferences.
  3. From Left Pane, select Appearance > System Settings > Android SDK
  4. Select SDK Tools next to SDK Platforms and under Android SDK Location
  5. Check mark Android SDK Command-line Tools (latest) and Press OK button.
  6. Wait for installation to be finished

Locating Preferences of Android Studio

Android Studio Preferences

Step 2 (For Flutter Users):

  1. Go to Terminal and run the following command

flutter doctor --android-licenses

Step 2 (For Android Users):

  1. Go to the Terminal and run the following command

export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home

yes | ~/Library/Android/sdk/tools/bin/sdkmanager --licenses

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Sometimes I have this error when videostream from imutils package doesn't recognize frame or give an empty frame. In that case, solution will be figuring out why you have such a bad frame or use a standard VideoCapture(0) method from opencv2

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

CSS text-align not working

I try to avoid floating elements unless the design really needs it. Because you have floated the <li> they are out of normal flow.

If you add .navigation { text-align:center; } and change .navigation li { float: left; } to .navigation li { display: inline-block; } then entire navigation will be centred.

One caveat to this approach is that display: inline-block; is not supported in IE6 and needs a workaround to make it work in IE7.

How can I specify a [DllImport] path at runtime?

DllImport will work fine without the complete path specified as long as the dll is located somewhere on the system path. You may be able to temporarily add the user's folder to the path.

ALTER table - adding AUTOINCREMENT in MySQL

CREATE TABLE ALLITEMS(
    itemid INT(10)UNSIGNED,
    itemname VARCHAR(50)
);

ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;

DESC ALLITEMS;

INSERT INTO ALLITEMS(itemname)
VALUES
    ('Apple'),
    ('Orange'),
    ('Banana');

SELECT
    *
FROM
    ALLITEMS;

I was confused with CHANGE and MODIFY keywords before too:

ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;

ALTER TABLE ALLITEMS MODIFY itemid INT(5);

While we are there, also note that AUTO_INCREMENT can also start with a predefined number:

ALTER TABLE tbl AUTO_INCREMENT = 100;

dd: How to calculate optimal blocksize?

  • for better performace use the biggest blocksize you RAM can accomodate (will send less I/O calls to the OS)
  • for better accurancy and data recovery set the blocksize to the native sector size of the input

As dd copies data with the conv=noerror,sync option, any errors it encounters will result in the remainder of the block being replaced with zero-bytes. Larger block sizes will copy more quickly, but each time an error is encountered the remainder of the block is ignored.

source

Calling a class function inside of __init__

In parse_file, take the self argument (just like in __init__). If there's any other context you need then just pass it as additional arguments as usual.

How to install wkhtmltopdf on a linux based (shared hosting) web server

Chances are that without full access to this server (due to being a hosted account) you are going to have problems. I would go so far as to say that I think it is a fruitless endeavor--they have to lock servers down in hosted environments for good reason.

Call your hosting company and make the request to them to install it, but don't expect a good response--they typically won't install very custom items for single users unless there is a really good reason (bug fixes for example).

Lastly, depending on how familiar you are with server administration and what you are paying for server hosting now consider something like http://www.slicehost.com. $20 a month will get you a low grade web server (256 ram) and you can install anything you want. However, if you are running multiple sites or have heavy load the cost will go up as you need larger servers.

GL!

What are .tpl files? PHP, web design

Templates. I think that is Smarty syntax.

Arrow operator (->) usage in C

foo->bar is only shorthand for (*foo).bar. That's all there is to it.

Disable resizing of a Windows Forms form

There is far more efficient answer: just put the following instructions in the Form_Load:

Me.MinimumSize = New Size(Width, Height)
Me.MaximumSize = Me.MinimumSize

What techniques can be used to speed up C++ compilation times?

Use

#pragma once

at the top of header files, so if they're included more than once in a translation unit, the text of the header will only get included and parsed once.

Is it possible to do a sparse checkout without checking out the whole repository first?

Works in git 2.28

git clone --filter=blob:none --no-checkout --depth 1 --sparse <project-url>
cd <project>
git sparse-checkout init --cone

Specify the files and folders you want to clone

git sparse-checkout add <folder>/<innerfolder> <folder2>/<innerfolder2>
git checkout

jQuery: Performing synchronous AJAX requests

how remote is that url ? is it from the same domain ? the code looks okay

try this

$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;

What is a thread exit code?

There actually doesn't seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn't exit as expected. But then this exit code can be set in code by yourself to completely overlook this.

The closest link I could find to be useful for more information is this

Quote from above link:

What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.


From the Documentation for GetEXitCodeThread

Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.


My understanding of all this is that the exit code doesn't matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.

cannot download, $GOPATH not set

This one worked

Setting up Go development environment on Ubuntu, and how to fix $GOPATH / $GOROOT

Steps

mkdir ~/go

Set $GOPATH in .bashrc,

export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin

How to prevent vim from creating (and leaving) temporary files?

I'd strongly recommend to keep working with swap files (in case Vim crashes).

You can set the directory where the swap files are stored, so they don't clutter your normal directories:

set swapfile
set dir=~/tmp

See also

:help swap-file

Javascript isnull

You could try this:

if(typeof(results) == "undefined") { 
    return 0;
} else {
    return results[1] || 0;
}

Angular 2: How to style host element of the component?

For anyone looking to style child elements of a :host here is an example of how to use ::ng-deep

:host::ng-deep <child element>

e.g :host::ng-deep span { color: red; }

As others said /deep/ is deprecated

How to replace a string in a SQL Server Table Column

I tried the above but it did not yield the correct result. The following one does:

update table
set path = replace(path, 'oldstring', 'newstring') where path = 'oldstring'

How to convert a date String to a Date or Calendar object?

The DateFormat class has a parse method.

See DateFormat for more information.

What are the date formats available in SimpleDateFormat class?

check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

main

System.out.println("date  : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));

method

 public String getMyDate(String myDate, String returnFormat, String myFormat)
            {
                DateFormat dateFormat = new SimpleDateFormat(returnFormat);
                Date date=null;
                String returnValue="";
                try {
                    date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
                    returnValue = dateFormat.format(date);
                } catch (ParseException e) {
                    returnValue= myDate;
                    System.out.println("failed");
                    e.printStackTrace();
                }

            return returnValue;
            }

How to use Python's "easy_install" on Windows ... it's not so easy

One problem is that easy_install is set up to download and install .egg files or source distributions (contained within .tgz, .tar, .tar.gz, .tar.bz2, or .zip files). It doesn't know how to deal with the PyWin32 extensions because they are put within a separate installer executable. You will need to download the appropriate PyWin32 installer file (for Python 2.7) and run it yourself. When you run easy_install again (provided you have it installed right, like in Sergio's instructions), you should see that your winpexpect package has been installed correctly.

Since it's Windows and open source we are talking about, it can often be a messy combination of install methods to get things working properly. However, easy_install is still better than hand-editing configuration files, for sure.

3-dimensional array in numpy

No need to go in such deep technicalities, and get yourself blasted. Let me explain it in the most easiest way. We all have studied "Sets" during our school-age in Mathematics. Just consider 3D numpy array as the formation of "sets".

x = np.zeros((2,3,4)) 

Simply Means:

2 Sets, 3 Rows per Set, 4 Columns

Example:

Input

x = np.zeros((2,3,4))

Output

Set # 1 ---- [[[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]], ---- Row 3 
    
Set # 2 ----  [[ 0.,  0.,  0.,  0.],  ---- Row 1
               [ 0.,  0.,  0.,  0.],  ---- Row 2
               [ 0.,  0.,  0.,  0.]]] ---- Row 3

Explanation: See? we have 2 Sets, 3 Rows per Set, and 4 Columns.

Note: Whenever you see a "Set of numbers" closed in double brackets from both ends. Consider it as a "set". And 3D and 3D+ arrays are always built on these "sets".

How to use find command to find all files with extensions from list?

find /path/to/ -type f -print0 | xargs -0 file | grep -i image

This uses the file command to try to recognize the type of file, regardless of filename (or extension).

If /path/to or a filename contains the string image, then the above may return bogus hits. In that case, I'd suggest

cd /path/to
find . -type f -print0 | xargs -0 file --mime-type | grep -i image/

What is the best collation to use for MySQL with PHP?

For UTF-8 textual information, you should use utf8_general_ci because...

  • utf8_bin: compare strings by the binary value of each character in the string

  • utf8_general_ci: compare strings using general language rules and using case-insensitive comparisons

a.k.a. it will should making searching and indexing the data faster/more efficient/more useful.

Set div height to fit to the browser using CSS

I think the fastest way is to use grid system with fractions. So your container have 100vw, which is 100% of the window width and 100vh which is 100% of the window height.

Using fractions or 'fr' you can choose the width you like. the sum of the fractions equals to 100%, in this example 4fr. So the first part will be 1fr (25%) and the seconf is 3fr (75%)

More about fr units here.

_x000D_
_x000D_
.container{
  width: 100vw;
  height:100vh; 
  display: grid;
  grid-template-columns: 1fr 3fr;
}

/*You don't need this*/
.div1{
  background-color: yellow;
}

.div2{
  background-color: red;
}
_x000D_
<div class='container'>
  <div class='div1'>This is div 1</div>
  <div class='div2'>This is div 2</div>
</div>
_x000D_
_x000D_
_x000D_

Visual Studio 2010 shortcut to find classes and methods?

Try Alt+F12 in Visual Studio 2010.

It opens up the Find Symbol dialogue which allows you to search for methods, classes, etc.

How do I commit only some files?

I suppose you want to commit the changes to one branch and then make those changes visible in the other branch. In git you should have no changes on top of HEAD when changing branches.

You commit only the changed files by:

git commit [some files]

Or if you are sure that you have a clean staging area you can

git add [some files]       # add [some files] to staging area
git add [some more files]  # add [some more files] to staging area
git commit                 # commit [some files] and [some more files]

If you want to make that commit available on both branches you do

git stash                     # remove all changes from HEAD and save them somewhere else
git checkout <other-project>  # change branches
git cherry-pick <commit-id>   # pick a commit from ANY branch and apply it to the current
git checkout <first-project>  # change to the other branch
git stash pop                 # restore all changes again

NPM clean modules

For windows environment:

"scripts": {
    "clean": "rmdir /s /q node_modules",
    ...
}

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

Thank you for all the input made so far. I just wanna add on that while one may have successfully normalized DB, updated any schema changes to their application (e.g. to dataset) or so, there is also another cause: sql CARTESIAN product (when joining tables in queries).

The existence of a cartesian query result will cause duplicate records in the primary (or key first) table of two or more tables being joined. Even if you specify a "Where" clause in the SQL, a Cartesian may still occur if JOIN with secondary table for example contains the unequal join (useful when to get data from 2 or more UNrelated tables):

FROM tbFirst INNER JOIN tbSystem ON tbFirst.reference_str <> tbSystem.systemKey_str

Solution for this: tables should be related.

Thanks. chagbert

Why should I use a container div in HTML?

This is one of the biggest bad habits perpetrated by front end coders.

All the answers above me are wrong. The body does take a width, margins, borders, etc and should act as your initial container. The html element should act as your background "canvas" as it was intended. In dozens of sites I've done I've only had to use a container div once.

I'd be willing to be that these same coders using container divs are also littering their markup with divs inside of divs--everywhere else.

Dont' do it. Use divs sparingly and aim for lean markup.

-=-=- UPDATE - Not sure what's wrong with SO because I can edit this answer from 5 years ago but I can't reply to the comments as it says I need 50 Rep before I can do so. Accordingly, I'll add my answer to the replies it received here. -=-=-

I just found this, years after my answer, and see that there are some follow up replies. And, surely you jest?

The installed placeholder site you found for my domain, which I never claimed was my markup or styling, or even mentioned in my post, was very clearly a basic CMS install with not one word of content (it said as much on the homepage). That was not my markup and styling. That was the Silverstripe default template. And I take no credit for it. It is, though, perhaps one of only two examples I can think of that would necessitate a container div.

Example 1: A generic template designed to accommodate unknowns. In this case you were seeing a default CMS template that had divs inside of divs inside of divs.

The horror.

Example 2: A three column layout to get the footer to clear properly (I think this was probably the scenario I had that needed a container div, hard to remember because that was years ago.)

I did just build (not even finished yet) a theme for my domain and started loading content. For this easily achieved example of semantic markup, click the link.

http://www.bitbeyond.com

Frankly, I'm baffled that people think you actually need a container div and start with one before ever even trying just a body. The body, as I heard it explained once by one of the original authors of the CSS spec, was intended as the "initial container".

Markup should be added as needed, not because thats just the way you've seen it done.

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

AngularJS view not updating on model change

setTimout executes outside of angular. You need to use $timeout service for this to work:

var app = angular.module('test', []);

    app.controller('TestCtrl', function ($scope, $timeout) {
       $scope.testValue = 0;

        $timeout(function() {
            console.log($scope.testValue++);
        }, 500);
    });

The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply() kicks off a $digest cycle. This will apply the binding. $timeout handles the $apply for you so it is the recommended service to use when using timeouts.

Essentially, binding happens during the $digest cycle (if the value is seen to be different).

How to change the status bar color in Android?

this is very easy way to do this without any Library: if the OS version is not supported - under kitkat - so nothing happend. i do this steps:

  1. in my xml i added to the top this View:
<View
        android:id="@+id/statusBarBackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

then i made this method:

 public void setStatusBarColor(View statusBar,int color){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
           Window w = getWindow();
           w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
           //status bar height
           int actionBarHeight = getActionBarHeight();
           int statusBarHeight = getStatusBarHeight();
           //action bar height
           statusBar.getLayoutParams().height = actionBarHeight + statusBarHeight;
           statusBar.setBackgroundColor(color);
     }
}

also you need those both methods to get action Bar & status bar height:

public int getActionBarHeight() {
    int actionBarHeight = 0;
    TypedValue tv = new TypedValue();
    if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
    {
       actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
    }
    return actionBarHeight;
}

public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

then the only thing you need is this line to set status bar color:

setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));

OpenCV get pixel channel value from Mat image

Assuming the type is CV_8UC3 you would do this:

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        Vec3b bgrPixel = foo.at<Vec3b>(i, j);

        // do something with BGR values...
    }
}

Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.

EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:

Here is how you might go about this:

uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
        bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
        bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R

        // do something with BGR values...
    }
}

Or alternatively:

int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    uint8_t* rowPtr = foo.row(i);
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
        bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
        bgrPixel.val[2] = rowPtr[j*cn + 2]; // R

        // do something with BGR values...
    }
}

PHP substring extraction. Get the string before the first '/' or the whole string

$string="kalion/home/public_html";

$newstring=( stristr($string,"/")==FALSE ) ? $string : substr($string,0,stripos($string,"/"));

bootstrap 3 - how do I place the brand in the center of the navbar?

css:

.navbar-header {
    float: left;
    padding: 15px;
    text-align: center;
    width: 100%;
}
.navbar-brand {float:none;}

html:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <a class="navbar-brand" href="#">Brand</a>
  </div>
</nav>

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

How to remove a branch locally?

You can delete multiple branches on windows using Git GUI:

  1. Go to your Project folder
  2. Open Git Gui: enter image description here
  3. Click on 'Branch': enter image description here
  4. Now choose 'Delete': enter image description here
  5. If you want to delete all branches besides the fact they are merged or not, then check 'Always (Do not perform merge checks)' enter image description here

Using boolean values in C

If you are using C99 then you can use the _Bool type. No #includes are necessary. You do need to treat it like an integer, though, where 1 is true and 0 is false.

You can then define TRUE and FALSE.

_Bool this_is_a_Boolean_var = 1;


//or using it with true and false
#define TRUE 1
#define FALSE 0
_Bool var = TRUE;

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

Tab separated values in awk

Should this not work?

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk '{print $1}'

Error using eclipse for Android - No resource found that matches the given name

Project ---> Clean does the trick in most of the cases. It did in mine.

How to test if a file is a directory in a batch script?

CD returns an EXIT_FAILURE when the specified directory does not exist. And you got conditional processing symbols, so you could do like the below for this.

SET cd_backup=%cd%
(CD "%~1" && CD %cd_backup%) || GOTO Error

:Error
CD %cd_backup%

Difference between parameter and argument

Argument is often used in the sense of actual argument vs. formal parameter.

The formal parameter is what is given in the function declaration/definition/prototype, while the actual argument is what is passed when calling the function — an instance of a formal parameter, if you will.

That being said, they are often used interchangeably, their exact use depending on different programming languages and their communities. For example, I have also heard actual parameter etc.

So here, x and y would be formal parameters:

int foo(int x, int y) {
    ...
}

Whereas here, in the function call, 5 and z are the actual arguments:

foo(5, z);

How do I prevent CSS inheritance?

You either use the child selector

So using

#parent > child

Will make only the first level children to have the styles applied. Unfortunately IE6 doesn't support the child selector.

Otherwise you can use

#parent child child

To set another specific styles to children that are more than one level below.

How does Go update third-party packages?

Go to path and type

go get -u ./..

It will update all require packages.

how to destroy bootstrap modal window completely?

I have tried accepted answer but it isn't seems working on my end and I don't know how the accepted answer suppose to work.

$('#modalId').on('hidden.bs.modal', function () {
  $(this).remove();
})

This is working perfectly fine on my side. BS Version > 3

Add a reference column migration in Rails 4

Just to document if someone has the same problem...

In my situation I've been using :uuid fields, and the above answers does not work to my case, because rails 5 are creating a column using :bigint instead :uuid:

add_reference :uploads, :user, index: true, type: :uuid

Reference: Active Record Postgresql UUID

JavaScript seconds to time string with format hh:mm:ss

Milliseconds to duration, the simple way:

// To have leading zero digits in strings.
function pad(num, size) {
    var s = num + "";
    while (s.length < size) s = "0" + s;
    return s;
}

// ms to time/duration
msToDuration = function(ms){
    var seconds = ms / 1000;
    var hh = Math.floor(seconds / 3600),
    mm = Math.floor(seconds / 60) % 60,
    ss = Math.floor(seconds) % 60,
    mss = ms % 1000;
    return pad(hh,2)+':'+pad(mm,2)+':'+pad(ss,2)+'.'+pad(mss,3);
}

It converts 327577 to 00:05:27.577.

UPDATE

Another way for different scenario:

toHHMMSS = function (n) {
    var sep = ':',
        n = parseFloat(n),
        sss = parseInt((n % 1)*1000),
        hh = parseInt(n / 3600);
    n %= 3600;
    var mm = parseInt(n / 60),
        ss = parseInt(n % 60);
    return pad(hh,2)+sep+pad(mm,2)+sep+pad(ss,2)+'.'+pad(sss,3);
    function pad(num, size) {
        var str = num + "";
        while (str.length < size) str = "0" + str;
        return str;
    }
}

toHHMMSS(6315.077) // Return 01:45:15.077

android on Text Change Listener

Another solution that may help someone. There are 2 EditText which change instead of each other after editing. By default, it led to cyclicity.

use variable:

Boolean uahEdited = false;
Boolean usdEdited = false;

add TextWatcher

uahEdit = findViewById(R.id.uahEdit);
usdEdit = findViewById(R.id.usdEdit);

uahEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!usdEdited) {
                uahEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = uahEdit.getText().toString();

            if(!tmp.isEmpty() && uahEdited) {
                uah = Double.valueOf(tmp);
                usd = uah / 27;
                usdEdit.setText(String.valueOf(usd));
            } else if (tmp.isEmpty()) {
                usdEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            uahEdited = false;
        }
    });

usdEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            if (!uahEdited) {
                usdEdited = true;
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String tmp = usdEdit.getText().toString();

            if (!tmp.isEmpty() && usdEdited) {
                usd = Double.valueOf(tmp);
                uah = usd * 27;
                uahEdit.setText(String.valueOf(uah));
            } else if (tmp.isEmpty()) {
                uahEdit.getText().clear();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            usdEdited = false;
        }
    });

Don't criticize too much. I am a novice developer

@selector() in Swift?

Just in case somebody else have the same problem I had with NSTimer where none of the other answers fixed the issue, is really important to mention that, if you are using a class that do not inherits from NSObject either directly or deep in the hierarchy(e.g. manually created swift files), none of the other answers will work even when is specified as follows:

let timer = NSTimer(timeInterval: 1, target: self, selector: "test", 
                    userInfo: nil, repeats: false)
func test () {}

Without changing anything else other than just making the class inherit from NSObject I stopped getting the "Unrecognized selector" Error and got my logic working as expected.

Rename a file using Java

In short:

Files.move(source, source.resolveSibling("newname"));

More detail:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:

Suppose we want to rename a file to "newname", keeping the file in the same directory:

Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));

Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);

How do you log all events fired by an element in jQuery?

https://github.com/robertleeplummerjr/wiretap.js

new Wiretap({
  add: function() {
      //fire when an event is bound to element
  },
  before: function() {
      //fire just before an event executes, arguments are automatic
  },
  after: function() {
      //fire just after an event executes, arguments are automatic
  }
});

JOIN two SELECT statement results

Try something like this:

SELECT 
* 
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1 
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks

How to debug .htaccess RewriteRule not working

To answer the first question of the three asked, a simple way to see if the .htaccess file is working or not is to trigger a custom error at the top of the .htaccess file:

ErrorDocument 200 "Hello. This is your .htaccess file talking."
RewriteRule ^ - [L,R=200]

On to your second question, if the .htaccess file is not being read it is possible that the server's main Apache configuration has AllowOverride set to None. Apache's documentation has troubleshooting tips for that and other cases that may be preventing the .htaccess from taking effect.

Finally, to answer your third question, if you need to debug specific variables you are referencing in your rewrite rule or are using an expression that you want to evaluate independently of the rule you can do the following:

Output the variable you are referencing to make sure it has the value you are expecting:

ErrorDocument 200 "Request: %{THE_REQUEST} Referrer: %{HTTP_REFERER} Host: %{HTTP_HOST}"
RewriteRule ^ - [L,R=200]

Test the expression independently by putting it in an <If> Directive. This allows you to make sure your expression is written properly or matching when you expect it to:

<If "%{REQUEST_URI} =~ /word$/">
    ErrorDocument 200 "Your expression is priceless!"
    RewriteRule ^ - [L,R=200]
</If>

Happy .htaccess debugging!

Django ChoiceField

New method in Django 3

you can use Field.choices Enumeration Types new update in django3 like this :

from django.db import models

class Status(models.TextChoices):
    UNPUBLISHED = 'UN', 'Unpublished'
    PUBLISHED = 'PB', 'Published'


class Book(models.Model):
    status = models.CharField(
        max_length=2,
        choices=Status.choices,
        default=Status.UNPUBLISHED,
    )

django docs

Twitter Bootstrap alert message close and open again

I agree with the answer posted by Henrik Karlsson and edited by Martin Prikryl. I have one suggestion, based on accessibility. I would add .attr("aria-hidden", "true") to the end of it, so that it looks like:

$(this).closest("." + $(this).attr("data-hide")).attr("aria-hidden", "true");

Stop fixed position at footer

I've made some changes to the second most popular answer as i found this worked better for me. The changes use window.innerHeight as it is more dynamic than adding your own height for the nav (above used + 570). this allows the code to work on mobile, tablet and desktop dynamicly.

$(window).scroll(() => {
            //Distance from top fo document to top of footer
            topOfFooter = $('#footer').position().top;
             // Distance user has scrolled from top + windows inner height
             scrollDistanceFromTopOfDoc = $(document).scrollTop() + window.innerHeight;
             // Difference between the two.
             scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter; 
            // If user has scrolled further than footer,
              if (scrollDistanceFromTopOfDoc > topOfFooter) {
                // add margin-bottom so button stays above footer.
                $('#floating-button').css('margin-bottom',  0 + scrollDistanceFromTopOfFooter);
              } else  {
                // remove margin-bottom so button goes back to the bottom of the page
                $('#floating-button').css('margin-bottom', 0);
              }
            });

jQuery lose focus event

Like this:

$(selector).focusout(function () {
    //Your Code
});

Int to Decimal Conversion - Insert decimal point at specified location

Declare it as a decimal which uses the int variable and divide this by 100

int number = 700
decimal correctNumber = (decimal)number / 100;

Edit: Bala was faster with his reaction

Angular 4 - Observable catch error

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

_x000D_
_x000D_
import { Injectable } from '@angular/core';_x000D_
import { Headers, Http, ResponseOptions} from '@angular/http';_x000D_
import { AuthHttp } from 'angular2-jwt';_x000D_
_x000D_
import { MEAT_API } from '../app.api';_x000D_
_x000D_
import { Observable } from 'rxjs/Observable';_x000D_
import 'rxjs/add/operator/map';_x000D_
import 'rxjs/add/operator/catch';_x000D_
_x000D_
@Injectable()_x000D_
export class CompareNfeService {_x000D_
_x000D_
_x000D_
  constructor(private http: AuthHttp) {}_x000D_
_x000D_
  envirArquivos(order): Observable < any > {_x000D_
    const headers = new Headers();_x000D_
    return this.http.post(`${MEAT_API}compare/arquivo`, order,_x000D_
        new ResponseOptions({_x000D_
          headers: headers_x000D_
        }))_x000D_
      .map(response => response.json())_x000D_
      .catch((e: any) => Observable.throw(this.errorHandler(e)));_x000D_
  }_x000D_
_x000D_
  errorHandler(error: any): void {_x000D_
    console.log(error)_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Using Observable.throw() worked for me

You need to use a Theme.AppCompat theme (or descendant) with this activity

Your Activity is extending ActionBarActivity which requires the AppCompat.theme to be applied. Change from ActionBarActivity to Activity or FragmentActivity, it will solve the problem.

If you use no Action bar then :

android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" 

How do I kill a VMware virtual machine that won't die?

If you are using Windows, the virtual machine should have it's own process that is visible in task manager. Use sysinternals Process Explorer to find the right one and then kill it from there.

Delete branches in Bitbucket

If you like fun, then you can just go to the listing page of you branches (for example merged) and just run in the javascript console:

document.querySelectorAll('tr td div a:first-child').forEach(function(item) { fetch('https://bitbucket.org/snippets/new?owner=<yourprofilenick>', {'credentials': 'same-origin'}).then((response) => {return response.text()}).then(function(string) { return /'csrfmiddlewaretoken' value='(.*)'/g.exec(string)[1] }).then(function(csrf) { if (!~item.innerText.indexOf('/')) return; 
 fetch(`https://bitbucket.org/!api/2.0/repositories/<your_organization_path>/refs/branches/${item.innerText}`, {headers: {"x-csrftoken": csrf}, credentials: "same-origin", method: 'DELETE'}).then(() => console.log(`${item.innerText} DELETED!`)) }) })

BEFORE RUN

  • replace <yourprofilenick> with your BitBucket nick
  • replace <your_organization_path> with your organization path

HOW IT WORKS

First we need a page with with a CSRF token in the page source, so I choose:

https://bitbucket.org/snippets/new?owner=<yourprofilenick>

Then for each branch (in a branch listing) it gets CSRF token and deletes that branch.

BEWARE

Remeber to prevent sensitive branches before deleting in repo settings.

It WON'T delete the main branch.

ADDITIONAL INFO

You have to be logged in.

It deletes only branches visible on that page (so to delete the rest of branches you have to go to the next page).

Convert seconds into days, hours, minutes and seconds

Although it is quite old question - one may find these useful (not written to be fast):

function d_h_m_s__string1($seconds)
{
    $ret = '';
    $divs = array(86400, 3600, 60, 1);

    for ($d = 0; $d < 4; $d++)
    {
        $q = (int)($seconds / $divs[$d]);
        $r = $seconds % $divs[$d];
        $ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
        $seconds = $r;
    }

    return $ret;
}

function d_h_m_s__string2($seconds)
{
    if ($seconds == 0) return '0s';

    $can_print = false; // to skip 0d, 0d0m ....
    $ret = '';
    $divs = array(86400, 3600, 60, 1);

    for ($d = 0; $d < 4; $d++)
    {
        $q = (int)($seconds / $divs[$d]);
        $r = $seconds % $divs[$d];
        if ($q != 0) $can_print = true;
        if ($can_print) $ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
        $seconds = $r;
    }

    return $ret;
}

function d_h_m_s__array($seconds)
{
    $ret = array();

    $divs = array(86400, 3600, 60, 1);

    for ($d = 0; $d < 4; $d++)
    {
        $q = $seconds / $divs[$d];
        $r = $seconds % $divs[$d];
        $ret[substr('dhms', $d, 1)] = $q;

        $seconds = $r;
    }

    return $ret;
}

echo d_h_m_s__string1(0*86400+21*3600+57*60+13) . "\n";
echo d_h_m_s__string2(0*86400+21*3600+57*60+13) . "\n";

$ret = d_h_m_s__array(9*86400+21*3600+57*60+13);
printf("%dd%dh%dm%ds\n", $ret['d'], $ret['h'], $ret['m'], $ret['s']);

result:

0d21h57m13s
21h57m13s
9d21h57m13s

Explode PHP string by new line

For a new line, it's just

$list = explode("\n", $text);

For a new line and carriage return (as in Windows files), it's as you posted. Is your skuList a text area?

How do I make a composite key with SQL Server Management Studio?

create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO


ALTER TABLE myTable
    ADD  PRIMARY KEY (Column1,Column2)
GO

POST Multipart Form Data using Retrofit 2.0 including image

Don't use multiple parameters in the function name just go with simple few args convention that will increase the readability of codes, for this you can do like -

// MultipartBody.Part.createFormData("partName", data)
Call<SomReponse> methodName(@Part MultiPartBody.Part part);
// RequestBody.create(MediaType.get("text/plain"), data)
Call<SomReponse> methodName(@Part(value = "partName") RequestBody part); 
/* for single use or you can use by Part name with Request body */

// add multiple list of part as abstraction |ease of readability|
Call<SomReponse> methodName(@Part List<MultiPartBody.Part> parts); 
Call<SomReponse> methodName(@PartMap Map<String, RequestBody> parts);
// this way you will save the abstraction of multiple parts.

There can be multiple exceptions that you may encounter while using Retrofit, all of the exceptions documented as code, have a walkthrough to retrofit2/RequestFactory.java. you can able to two functions parseParameterAnnotation and parseMethodAnnotation where you can able to exception thrown, please go through this, it will save your much of time than googling/stackoverflow

CSS Change List Item Background Color with Class

The ul.nav li is more restrictive and so takes precedence, try this:

ul.nav li.selected {  
  background-color:red; 
}

Why aren't python nested functions called closures?

Python 2 didn't have closures - it had workarounds that resembled closures.

There are plenty of examples in answers already given - copying in variables to the inner function, modifying an object on the inner function, etc.

In Python 3, support is more explicit - and succinct:

def closure():
    count = 0
    def inner():
        nonlocal count
        count += 1
        print(count)
    return inner

Usage:

start = closure()
start() # prints 1
start() # prints 2
start() # prints 3

The nonlocal keyword binds the inner function to the outer variable explicitly mentioned, in effect enclosing it. Hence more explicitly a 'closure'.

how to display data values on Chart.js

I think the nicest option to do this in chartJS v2.x is by using a plugin, so you don't have a large block of code in the options. In addition, it prevents the data from disappearing when hovering over a bar.

I.e. simply use this code, which registers a plugin that adds the text after the chart is drawn.

Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;

        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i], model.x, model.y - 2);
            }
        });
  }
});

Comparing two java.util.Dates to see if they are in the same day

Joda-Time

As for adding a dependency, I'm afraid the java.util.Date & .Calendar really are so bad that the first thing I do to any new project is add the Joda-Time library. In Java 8 you can use the new java.time package, inspired by Joda-Time.

The core of Joda-Time is the DateTime class. Unlike java.util.Date, it understands its assigned time zone (DateTimeZone). When converting from j.u.Date, assign a zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeQuébec = new DateTime( date , zone );

LocalDate

One way to verify if two date-times land on the same date is to convert to LocalDate objects.

That conversion depends on the assigned time zone. To compare LocalDate objects, they must have been converted with the same zone.

Here is a little utility method.

static public Boolean sameDate ( DateTime dt1 , DateTime dt2 )
{
    LocalDate ld1 = new LocalDate( dt1 );
    // LocalDate determination depends on the time zone.
    // So be sure the date-time values are adjusted to the same time zone.
    LocalDate ld2 = new LocalDate( dt2.withZone( dt1.getZone() ) );
    Boolean match = ld1.equals( ld2 );
    return match;
}

Better would be another argument, specifying the time zone rather than assuming the first DateTime object’s time zone should be used.

static public Boolean sameDate ( DateTimeZone zone , DateTime dt1 , DateTime dt2 )
{
    LocalDate ld1 = new LocalDate( dt1.withZone( zone ) );
    // LocalDate determination depends on the time zone.
    // So be sure the date-time values are adjusted to the same time zone.
    LocalDate ld2 = new LocalDate( dt2.withZone( zone ) );
    return ld1.equals( ld2 );
}

String Representation

Another approach is to create a string representation of the date portion of each date-time, then compare strings.

Again, the assigned time zone is crucial.

DateTimeFormatter formatter = ISODateTimeFormat.date();  // Static method.
String s1 = formatter.print( dateTime1 );
String s2 = formatter.print( dateTime2.withZone( dt1.getZone() )  );
Boolean match = s1.equals( s2 );
return match;

Span of Time

The generalized solution is to define a span of time, then ask if the span contains your target. This example code is in Joda-Time 2.4. Note that the "midnight"-related classes are deprecated. Instead use the withTimeAtStartOfDay method. Joda-Time offers three classes to represent a span of time in various ways: Interval, Period, and Duration.

Using the "Half-Open" approach where the beginning of the span is inclusive and the ending exclusive.

The time zone of the target can be different than the time zone of the interval.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime target = new DateTime( 2012, 3, 4, 5, 6, 7, timeZone );
DateTime start = DateTime.now( timeZone ).withTimeAtStartOfDay();
DateTime stop = start.plusDays( 1 ).withTimeAtStartOfDay();
Interval interval = new Interval( start, stop );
boolean containsTarget = interval.contains( target );

java.time

Java 8 and later comes with the java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See Tutorial.

The makers of Joda-Time have instructed us all to move to java.time as soon as is convenient. In the meantime Joda-Time continues as an actively maintained project. But expect future work to occur only in java.time and ThreeTen-Extra rather than Joda-Time.

To summarize java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime object. To move off the timeline, to get the vague indefinite idea of a date-time, use the "local" classes: LocalDateTime, LocalDate, LocalTime.

The logic discussed in the Joda-Time section of this Answer applies to java.time.

The old java.util.Date class has a new toInstant method for conversion to java.time.

Instant instant = yourJavaUtilDate.toInstant(); // Convert into java.time type.

Determining a date requires a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" );

We apply that time zone object to the Instant to obtain a ZonedDateTime. From that we extract a date-only value (a LocalDate) as our goal is to compare dates (not hours, minutes, etc.).

ZonedDateTime zdt1 = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate1 = LocalDate.from( zdt1 );

Do the same to the second java.util.Date object we need for comparison. I’ll just use the current moment instead.

ZonedDateTime zdt2 = ZonedDateTime.now( zoneId );
LocalDate localDate2 = LocalDate.from( zdt2 );

Use the special isEqual method to test for the same date value.

Boolean sameDate = localDate1.isEqual( localDate2 );

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

How find out which process is using a file in Linux?

$ lsof | tree MyFold

As shown in the image attached:

enter image description here

Unable to preventDefault inside passive event listener

In plain JS add { passive: false } as third argument

document.addEventListener('wheel', function(e) {
    e.preventDefault();
    doStuff(e);
}, { passive: false });

Build tree array from flat array in javascript

also do it with lodashjs(v4.x)

function buildTree(arr){
  var a=_.keyBy(arr, 'id')
  return _
   .chain(arr)
   .groupBy('parentId')
   .forEach(function(v,k){ 
     k!='0' && (a[k].children=(a[k].children||[]).concat(v));
   })
   .result('0')
   .value();
}

How to save picture to iPhone photo library?

Below function would work. You can copy from here and paste there...

-(void)savePhotoToAlbum:(UIImage*)imageToSave {

    CGImageRef imageRef = imageToSave.CGImage;
    NSDictionary *metadata = [NSDictionary new]; // you can add
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library writeImageToSavedPhotosAlbum:imageRef metadata:metadata completionBlock:^(NSURL *assetURL,NSError *error){
        if(error) {
            NSLog(@"Image save eror");
        }
    }];
}

How to make sure that string is valid JSON using JSON.NET

Through Code:

Your best bet is to use parse inside a try-catch and catch exception in case of failed parsing. (I am not aware of any TryParse method).

(Using JSON.Net)

Simplest way would be to Parse the string using JToken.Parse, and also to check if the string starts with { or [ and ends with } or ] respectively (added from this answer):

private static bool IsValidJson(string strInput)
{
    if (string.IsNullOrWhiteSpace(strInput)) { return false;}
    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JToken.Parse(strInput);
            return true;
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            Console.WriteLine(jex.Message);
            return false;
        }
        catch (Exception ex) //some other exception
        {
            Console.WriteLine(ex.ToString());
            return false;
        }
    }
    else
    {
        return false;
    }
}

The reason to add checks for { or [ etc was based on the fact that JToken.Parse would parse the values such as "1234" or "'a string'" as a valid token. The other option could be to use both JObject.Parse and JArray.Parse in parsing and see if anyone of them succeeds, but I believe checking for {} and [] should be easier. (Thanks @RhinoDevel for pointing it out)

Without JSON.Net

You can utilize .Net framework 4.5 System.Json namespace ,like:

string jsonString = "someString";
try
{
    var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
    //Invalid json format
    Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
    Console.WriteLine(ex.ToString());
}

(But, you have to install System.Json through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343 on Package Manager Console) (taken from here)

Non-Code way:

Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:

How to trim a string after a specific character in java

Use regex:

result = result.replaceAll("\n.*", "");

replaceAll() uses regex to find its target, which I have replaced with "nothing" - effectively deleting the target.

The target I've specified by the regex \n.* means "the newline char and everything after"

How to do associative array/hashing in JavaScript

All modern browsers support a JavaScript Map object. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are Strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

Detect Windows version in .net

First solution

To make sure you get the right version with Environment.OSVersion you should add an app.manifest using Visual Studio and uncomment following supportedOS tags:

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- A list of the Windows versions that this application has been tested on
           and is designed to work with. Uncomment the appropriate elements
           and Windows will automatically select the most compatible environment. -->

      <!-- Windows Vista -->
      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />

      <!-- Windows 7 -->
      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />

      <!-- Windows 8 -->
      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />

      <!-- Windows 8.1 -->
      <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />

      <!-- Windows 10 -->
      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

    </application>
  </compatibility>

Then in your code you can use Environment.OSVersion like this:

var version = System.Environment.OSVersion;
Console.WriteLine(version);

Example

For instance in my machine (Windows 10.0 Build 18362.476) result would be like this which is incorrect:

Microsoft Windows NT 6.2.9200.0

By adding app.manifest and uncomment those tags I will get the right version number:

Microsoft Windows NT 10.0.18362.0

Alternative solution

If you don't like adding app.manifest to your project, you can use OSDescription which is available since .NET Framework 4.7.1 and .NET Core 1.0.

string description = RuntimeInformation.OSDescription;

Note: Don't forget to add following using statement at top of your file.

using System.Runtime.InteropServices;

You can read more about it and supported platforms here.

Insert content into iFrame

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

Delegates in swift?

DELEGATES IN SWIFT 2

I am explaining with example of Delegate with two viewControllers.In this case, SecondVC Object is sending data back to first View Controller.

Class with Protocol Declaration

protocol  getDataDelegate  {
    func getDataFromAnotherVC(temp: String)
}


import UIKit
class SecondVC: UIViewController {

    var delegateCustom : getDataDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()
     }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func backToMainVC(sender: AnyObject) {
      //calling method defined in first View Controller with Object  
      self.delegateCustom?.getDataFromAnotherVC(temp: "I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
        self.navigationController?.popViewControllerAnimated(true)
    }
    
}

In First ViewController Protocol conforming is done here:

class ViewController: UIViewController, getDataDelegate

Protocol method definition in First View Controller(ViewController)

func getDataFromAnotherVC(temp : String)
{
  // dataString from SecondVC
   lblForData.text = dataString
}

During push the SecondVC from First View Controller (ViewController)

let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)

how to cancel/abort ajax request in axios

Using cp-axios wrapper you able to abort your requests with three diffent types of the cancellation API:

1. Promise cancallation API (CPromise):

Live browser example

 const cpAxios= require('cp-axios');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 
 const chain = cpAxios(url)
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    chain.cancel();
 }, 500);

2. Using AbortController signal API:

 const cpAxios= require('cp-axios');
 const CPromise= require('c-promise2');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 
 const abortController = new CPromise.AbortController();
 const {signal} = abortController;
 
 const chain = cpAxios(url, {signal})
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    abortController.abort();
 }, 500);

3. Using a plain axios cancelToken:

 const cpAxios= require('cp-axios');
 const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';

 const source = cpAxios.CancelToken.source();
 
 cpAxios(url, {cancelToken: source.token})
      .timeout(5000)
      .then(response=> {
          console.log(`Done: ${JSON.stringify(response.data)}`)
      }, err => {
          console.warn(`Request failed: ${err}`)
      });
 
 setTimeout(() => {
    source.cancel();
 }, 500);

Find package name for Android apps to use Intent to launch Market app from web

Not sure if you still need this, but in http://www.appbrain.com/ , you look up the app and the package name is in the url. For example: http://www.appbrain.com/app/fruit-ninja/com.halfbrick.fruitninja is the link for fruit ninja. Notice the bold

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

ORA-01034 and ORA-27101 normally indicate that the database instance you're attempting to connect to is shut down and that you're not connected as a user who has permission to start it up. Log on to the server 192.168.1.53 and start up the orcl instance, or ask your DBA to do this for you.

How to count certain elements in array?

Not using a loop usually means handing the process over to some method that does use a loop.

Here is a way our loop hating coder can satisfy his loathing, at a price:

var a=[1, 2, 3, 5, 2, 8, 9, 2];

alert(String(a).replace(/[^2]+/g,'').length);


/*  returned value: (Number)
3
*/

You can also repeatedly call indexOf, if it is available as an array method, and move the search pointer each time.

This does not create a new array, and the loop is faster than a forEach or filter.

It could make a difference if you have a million members to look at.

function countItems(arr, what){
    var count= 0, i;
    while((i= arr.indexOf(what, i))!= -1){
        ++count;
        ++i;
    }
    return count
}

countItems(a,2)

/*  returned value: (Number)
3
*/

Sorting Python list based on the length of the string

def lensort(list_1):
    list_2=[];list_3=[]
for i in list_1:
    list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
    list_3.append(i[0])
return list_3

This works for me!

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

Row count where data exists

Assuming that your Sheet1 is not necessary active you would need to use this improved code of yours:

i = ActiveWorkbook.Worksheets("Sheet1").Range("A2" , Worksheets("Sheet1").Range("A2").End(xlDown)).Rows.Count

Look into full worksheet reference for second argument for Range(arg1, arg2) which important in this situation.

Is there a way to list all resources in AWS

EDIT: This answer is deprecated. Check the other answers.

No,
There is no way to get all resources within your account in one go. Each region is independent and for some services like IAM concept of a region does not exist at all. Although there are API calls available to list down resources and services.
For example:

  • To get list of all available regions for your account:

    output, err := client.DescribeRegions(&ec2.DescribeRegionsInput{})
    

  • To get list of IAM users, roles or group you can use:

    client.GetAccountAuthorizationDetails(&iam.GetAccountAuthorizationDetailsInput{})

    You can find more detail about API calls and their use at: https://docs.aws.amazon.com/sdk-for-go/api/service/iam/

    Above link is only for IAM. Similarly, you can find API for all other resources and services.

  • How do I turn a String into a InputStreamReader in java?

    ByteArrayInputStream also does the trick:

    InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
    

    Then convert to reader:

    InputStreamReader reader = new InputStreamReader(is);
    

    How to include NA in ifelse?

    So, I hear this works:

    Data$X1<-as.character(Data$X1)
    Data$GEOID<-as.character(Data$BLKIDFP00)
    Data<-within(Data,X1<-ifelse(is.na(Data$X1),GEOID,Data$X2)) 
    

    But I admit I have only intermittent luck with it.

    How to generate random number with the specific length in python

    If you want it as a string (for example, a 10-digit phone number) you can use this:

    n = 10
    ''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
    

    Permission denied (publickey,keyboard-interactive)

    The server first tries to authenticate you by public key. That doesn't work (I guess you haven't set one up), so it then falls back to 'keyboard-interactive'. It should then ask you for a password, which presumably you're not getting right. Did you see a password prompt?

    How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

    String Fpath = getPath(this, uri) ;
    File file = new File(Fpath);
    String filename = file.getName();
    

    Dynamically display a CSV file as an HTML table on a web page

    Just improved phihag's code because it runs into a infinite loop if file not exists.

    <?php
    
    $filename = "so-csv.csv";
    
    echo "<html><body><table>\n\n";
    
    if (file_exists($filename)) {
    $f = fopen($filename, "r");
    while (($line = fgetcsv($f)) !== false) {
            echo "<tr>";
            foreach ($line as $cell) {
                    echo "<td>" . htmlspecialchars($cell) . "</td>";
            }
            echo "</tr>\n";
    }
    fclose($f);
    }
    
    else{ echo "<tr><td>No file exists ! </td></tr>" ;}
    echo "\n</table></body></html>";
    ?>
    

    No mapping found for HTTP request with URI Spring MVC

    I have the same problem.... I change my project name and i have this problem...my solution was the checking project refences and use / in my web.xml (instead of /*)

    What is base 64 encoding used for?

    Mostly, I've seen it used to encode binary data in contexts that can only handle ascii - or a simple - character sets.

    Code line wrapping - how to handle long lines

    IMHO this is the best way to write your line :

    private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper =
            new HashMap<Class<? extends Persistent>, PersistentHelper>();
    

    This way the increased indentation without any braces can help you to see that the code was just splited because the line was too long. And instead of 4 spaces, 8 will make it clearer.

    What is the difference between utf8mb4 and utf8 charsets in MySQL?

    Taken from the MySQL 8.0 Reference Manual:

    • utf8mb4: A UTF-8 encoding of the Unicode character set using one to four bytes per character.

    • utf8mb3: A UTF-8 encoding of the Unicode character set using one to three bytes per character.

    In MySQL utf8 is currently an alias for utf8mb3 which is deprecated and will be removed in a future MySQL release. At that point utf8 will become a reference to utf8mb4.

    So regardless of this alias, you can consciously set yourself an utf8mb4 encoding.

    To complete the answer, I'd like to add the @WilliamEntriken's comment below (also taken from the manual):

    To avoid ambiguity about the meaning of utf8, consider specifying utf8mb4 explicitly for character set references instead of utf8.

    How to make HTTP Post request with JSON body in Swift

    Swift 4 and 5

    HTTP POST request using URLSession API in Swift 4

    func postRequest(username: String, password: String, completion: @escaping ([String: Any]?, Error?) -> Void) {
    
        //declare parameter as a dictionary which contains string as key and value combination.
        let parameters = ["name": username, "password": password]
    
        //create the url with NSURL
        let url = URL(string: "https://www.myserver.com/api/login")!
    
        //create the session object
        let session = URLSession.shared
    
        //now create the Request object using the url object
        var request = URLRequest(url: url)
        request.httpMethod = "POST" //set http method as POST
    
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
        } catch let error {
            print(error.localizedDescription)
            completion(nil, error)
        }
    
        //HTTP Headers
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
    
        //create dataTask using the session object to send data to the server
        let task = session.dataTask(with: request, completionHandler: { data, response, error in
    
            guard error == nil else {
                completion(nil, error)
                return
            }
    
            guard let data = data else {
                completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
                return
            }
    
            do {
                //create json object from data
                guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
                    completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
                    return
                }
                print(json)
                completion(json, nil)
            } catch let error {
                print(error.localizedDescription)
                completion(nil, error)
            }
        })
    
        task.resume()
    }
    
    @objc func submitAction(_ sender: UIButton) {
        //call postRequest with username and password parameters
        postRequest(username: "username", password: "password") { (result, error) in
        if let result = result {
            print("success: \(result)")
        } else if let error = error {
            print("error: \(error.localizedDescription)")
        }
    }
    

    Using Alamofire:

    let parameters = ["name": "username", "password": "password123"]
    Alamofire.request("https://www.myserver.com/api/login", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
    

    Mapping two integers to one, in a unique and deterministic way

    For positive integers as arguments and where argument order doesn't matter:

    1. Here's an unordered pairing function:

      <x, y> = x * y + trunc((|x - y| - 1)^2 / 4) = <y, x>
      
    2. For x ? y, here's a unique unordered pairing function:

      <x, y> = if x < y:
                 x * (y - 1) + trunc((y - x - 2)^2 / 4)
               if x > y:
                 (x - 1) * y + trunc((x - y - 2)^2 / 4)
             = <y, x>
      

    Using {% url ??? %} in django templates

    Instead of importing the logout_view function, you should provide a string in your urls.py file:

    So not (r'^login/', login_view),

    but (r'^login/', 'login.views.login_view'),

    That is the standard way of doing things. Then you can access the URL in your templates using:

    {% url login.views.login_view %}
    

    ldconfig error: is not a symbolic link

    I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.

    The error was that libexpat.so.1 was not a symbolic link.

    It turned out that there were two identical files, libexpat.so.1.5.2 and libexpat.so.1. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.

    Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.

    How to call a method in another class in Java?

    Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");

    You have to add the class' and at a point like

    yourClassNameWhereTheMethodIs.theMethodsName();
    

    I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

    Calling an API from SQL Server stored procedure

    Screams in to the void - just "no" don't do it. This is a dumb idea.

    Integrating with external data sources is what SSIS is for, or write a dot net application/service which queries the box and makes the API calls.

    Writing CLR code to enable a SQL process to call web-services is the sort of thing that can bring a SQL box to its knees if done badly - imagine putting the the CLR function in a view somewhere - later someone else comes along not knowing what you've donem and joins on that view with a million row table - suddenly your SQL box is making a million individual webapi calls.

    The whole idea is insane.

    This doing sort of thing is the reason that enterprise DBAs dont' trust developers.

    CLR is the kind of great power, which brings great responsibility, and the above is an abuse of it.

    Where to get this Java.exe file for a SQL Developer installation

    You have to give the path to jdk ...typically C:\Program Files\Java.. Still if it is asking you for the path then Check this http://www.shellperson.net/oracle-sql-developer-enter-the-full-pathname-for-java-exe/

    How do I get the current date and time in PHP?

    <?php
    // Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
    // Mountain Standard Time (MST) Time Zone
    
    $today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
    $today = date("m.d.y");                         // 03.10.01
    $today = date("j, n, Y");                       // 10, 3, 2001
    $today = date("Ymd");                           // 20010310
    $today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
    $today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
    $today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
    $today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
    $today = date("H:i:s");                         // 17:16:18
    $today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
    ?>
    

    Split column at delimiter in data frame

    The newly popular tidyr package does this with separate. It uses regular expressions so you'll have to escape the |

    df <- data.frame(ID=11:13, FOO=c('a|b', 'b|c', 'x|y'))
    separate(data = df, col = FOO, into = c("left", "right"), sep = "\\|")
    
      ID left right
    1 11    a     b
    2 12    b     c
    3 13    x     y
    

    though in this case the defaults are smart enough to work (it looks for non-alphanumeric characters to split on).

    separate(data = df, col = FOO, into = c("left", "right"))
    

    Inline labels in Matplotlib

    A simpler approach like the one Ioannis Filippidis do :

    import matplotlib.pyplot as plt
    import numpy as np
    
    # evenly sampled time at 200ms intervals
    tMin=-1 ;tMax=10
    t = np.arange(tMin, tMax, 0.1)
    
    # red dashes, blue points default
    plt.plot(t, 22*t, 'r--', t, t**2, 'b')
    
    factor=3/4 ;offset=20  # text position in view  
    textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
    plt.text(textPosition[0],textPosition[1]+offset,'22  t',color='red',fontsize=20)
    textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
    plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
    plt.show()
    

    code python 3 on sageCell

    What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

    Replying on old post however I found it useful to wrap it as follows:

    using System;
    using System.Collections.Generic;
    
    public class DeepCopy
    {
      public static Dictionary<T1, T2> CloneKeys<T1, T2>(Dictionary<T1, T2> dict)
        where T1 : ICloneable
      {
        if (dict == null)
          return null;
        Dictionary<T1, T2> ret = new Dictionary<T1, T2>();
        foreach (var e in dict)
          ret[(T1)e.Key.Clone()] = e.Value;
        return ret;
      }
    
      public static Dictionary<T1, T2> CloneValues<T1, T2>(Dictionary<T1, T2> dict)
        where T2 : ICloneable
      {
        if (dict == null)
          return null;
        Dictionary<T1, T2> ret = new Dictionary<T1, T2>();
        foreach (var e in dict)
          ret[e.Key] = (T2)(e.Value.Clone());
        return ret;
      }
    
      public static Dictionary<T1, T2> Clone<T1, T2>(Dictionary<T1, T2> dict)
        where T1 : ICloneable
        where T2 : ICloneable
      {
        if (dict == null)
          return null;
        Dictionary<T1, T2> ret = new Dictionary<T1, T2>();
        foreach (var e in dict)
          ret[(T1)e.Key.Clone()] = (T2)(e.Value.Clone());
        return ret;
      }
    }
    

    TypeError: $(...).on is not a function

    The usual cause of this is that you're also using Prototype, MooTools, or some other library that makes use of the $ symbol, and you're including that library after jQuery, and so that library is "winning" (taking $ for itself). So the return value of $ isn't a jQuery instance, and so it doesn't have jQuery methods on it (like on).

    You can use jQuery with those other libraries, but if you do, you have to use the jQuery symbol rather than its alias $, e.g.:

    jQuery('body').on(...);
    

    And it's usually best if you add this immediately after your script tag including jQuery, before the one including the other library:

    <script>jQuery.noConflict();</script>
    

    ...although it's not required if you load the other library after jQuery (it is if you load the other library first).

    Using multiple full-function DOM manipulation libraries on the same page isn't ideal, though, just in terms of page weight. So if you can stick with just Prototype/MooTools/whatever or just jQuery, that's usually better.

    How do I fetch multiple columns for use in a cursor loop?

    Here is slightly modified version. Changes are noted as code commentary.

    BEGIN TRANSACTION
    
    declare @cnt int
    declare @test nvarchar(128)
    -- variable to hold table name
    declare @tableName nvarchar(255)
    declare @cmd nvarchar(500) 
    -- local means the cursor name is private to this code
    -- fast_forward enables some speed optimizations
    declare Tests cursor local fast_forward for
     SELECT COLUMN_NAME, TABLE_NAME
       FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE COLUMN_NAME LIKE 'pct%' 
        AND TABLE_NAME LIKE 'TestData%'
    
    open Tests
    -- Instead of fetching twice, I rather set up no-exit loop
    while 1 = 1
    BEGIN
      -- And then fetch
      fetch next from Tests into @test, @tableName
      -- And then, if no row is fetched, exit the loop
      if @@fetch_status <> 0
      begin
         break
      end
      -- Quotename is needed if you ever use special characters
      -- in table/column names. Spaces, reserved words etc.
      -- Other changes add apostrophes at right places.
      set @cmd = N'exec sp_rename ''' 
               + quotename(@tableName) 
               + '.' 
               + quotename(@test) 
               + N''',''' 
               + RIGHT(@test,LEN(@test)-3) 
               + '_Pct''' 
               + N', ''column''' 
    
      print @cmd
    
      EXEC sp_executeSQL @cmd
    END
    
    close Tests 
    deallocate Tests
    
    ROLLBACK TRANSACTION
    --COMMIT TRANSACTION
    

    fast way to copy formatting in excel

    Just use the NumberFormat property after the Value property: In this example the Ranges are defined using variables called ColLetter and SheetRow and this comes from a for-next loop using the integer i, but they might be ordinary defined ranges of course.

    TransferSheet.Range(ColLetter & SheetRow).Value = Range(ColLetter & i).Value TransferSheet.Range(ColLetter & SheetRow).NumberFormat = Range(ColLetter & i).NumberFormat

    #ifdef replacement in the Swift language

    As of Swift 4.1, if all you need is just check whether the code is built with debug or release configuration, you may use the built-in functions:

    • _isDebugAssertConfiguration() (true when optimization is set to -Onone)
    • _isReleaseAssertConfiguration() (true when optimization is set to -O) (not available on Swift 3+)
    • _isFastAssertConfiguration() (true when optimization is set to -Ounchecked)

    e.g.

    func obtain() -> AbstractThing {
        if _isDebugAssertConfiguration() {
            return DecoratedThingWithDebugInformation(Thing())
        } else {
            return Thing()
        }
    }
    

    Compared with preprocessor macros,

    • ? You don't need to define a custom -D DEBUG flag to use it
    • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
    • ? Undocumented, which means the function can be removed in any update (but it should be AppStore-safe since the optimizer will turn these into constants)

    • ? Using in if/else will always generate a "Will never be executed" warning.

    JavaScript adding decimal numbers issue

    Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

    +(0.1 + 0.2).toFixed(12) // 0.3
    

    It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

    Math.round((0.1 + 0.2) * 1e12) / 1e12
    

    Removing address bar from browser (to view on Android)

    I found that if you add the command to unload, he keeps down the page, ie the page that move! Hope it works with you too!

    window.addEventListener("load", function() { window.scrollTo(0, 1); });
    window.addEventListener("unload", function() { window.scrollTo(0, 1); });
    

    Using a 7-inch tablet with android, www.kupsoft.com visit my website and check how it behaves page, I use this command in my portal.

    Char Comparison in C

    A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

    So, when you write the following assignment:

    char a = 'a'; 
    

    It is the same thing as:

    char a = 97;
    

    So, you can compare two char variables using the >, <, ==, <=, >= operators:

    char a = 'a';
    char b = 'b';
    
    if( a < b ) printf("%c is smaller than %c", a, b);
    if( a > b ) printf("%c is smaller than %c", a, b);
    if( a == b ) printf("%c is equal to %c", a, b);
    

    ReactJS map through Object

    Use Object.entries() function.

    Object.entries(object) return:

    [
        [key, value],
        [key, value],
        ...
    ]
    

    see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

    {Object.entries(subjects).map(([key, subject], i) => (
        <li className="travelcompany-input" key={i}>
            <span className="input-label">key: {i} Name: {subject.name}</span>
        </li>
    ))}
    

    Watermark / hint text / placeholder TextBox

    You can create a watermark that can be added to any TextBox with an Attached Property. Here is the source for the Attached Property:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using System.Windows.Documents;
    
    /// <summary>
    /// Class that provides the Watermark attached property
    /// </summary>
    public static class WatermarkService
    {
        /// <summary>
        /// Watermark Attached Dependency Property
        /// </summary>
        public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached(
           "Watermark",
           typeof(object),
           typeof(WatermarkService),
           new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged)));
    
        #region Private Fields
    
        /// <summary>
        /// Dictionary of ItemsControls
        /// </summary>
        private static readonly Dictionary<object, ItemsControl> itemsControls = new Dictionary<object, ItemsControl>();
    
        #endregion
    
        /// <summary>
        /// Gets the Watermark property.  This dependency property indicates the watermark for the control.
        /// </summary>
        /// <param name="d"><see cref="DependencyObject"/> to get the property from</param>
        /// <returns>The value of the Watermark property</returns>
        public static object GetWatermark(DependencyObject d)
        {
            return (object)d.GetValue(WatermarkProperty);
        }
    
        /// <summary>
        /// Sets the Watermark property.  This dependency property indicates the watermark for the control.
        /// </summary>
        /// <param name="d"><see cref="DependencyObject"/> to set the property on</param>
        /// <param name="value">value of the property</param>
        public static void SetWatermark(DependencyObject d, object value)
        {
            d.SetValue(WatermarkProperty, value);
        }
    
        /// <summary>
        /// Handles changes to the Watermark property.
        /// </summary>
        /// <param name="d"><see cref="DependencyObject"/> that fired the event</param>
        /// <param name="e">A <see cref="DependencyPropertyChangedEventArgs"/> that contains the event data.</param>
        private static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Control control = (Control)d;
            control.Loaded += Control_Loaded;
    
            if (d is ComboBox)
            {
                control.GotKeyboardFocus += Control_GotKeyboardFocus;
                control.LostKeyboardFocus += Control_Loaded;
            }
            else if (d is TextBox)
            {
                control.GotKeyboardFocus += Control_GotKeyboardFocus;
                control.LostKeyboardFocus += Control_Loaded;
                ((TextBox)control).TextChanged += Control_GotKeyboardFocus;
            }
    
            if (d is ItemsControl && !(d is ComboBox))
            {
                ItemsControl i = (ItemsControl)d;
    
                // for Items property  
                i.ItemContainerGenerator.ItemsChanged += ItemsChanged;
                itemsControls.Add(i.ItemContainerGenerator, i);
    
                // for ItemsSource property  
                DependencyPropertyDescriptor prop = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, i.GetType());
                prop.AddValueChanged(i, ItemsSourceChanged);
            }
        }
    
        #region Event Handlers
    
        /// <summary>
        /// Handle the GotFocus event on the control
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
        private static void Control_GotKeyboardFocus(object sender, RoutedEventArgs e)
        {
            Control c = (Control)sender;
            if (ShouldShowWatermark(c))
            {
                ShowWatermark(c);
            }
            else
            {
                RemoveWatermark(c);
            }
        }
    
        /// <summary>
        /// Handle the Loaded and LostFocus event on the control
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="RoutedEventArgs"/> that contains the event data.</param>
        private static void Control_Loaded(object sender, RoutedEventArgs e)
        {
            Control control = (Control)sender;
            if (ShouldShowWatermark(control))
            {
                ShowWatermark(control);
            }
        }
    
        /// <summary>
        /// Event handler for the items source changed event
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="EventArgs"/> that contains the event data.</param>
        private static void ItemsSourceChanged(object sender, EventArgs e)
        {
            ItemsControl c = (ItemsControl)sender;
            if (c.ItemsSource != null)
            {
                if (ShouldShowWatermark(c))
                {
                    ShowWatermark(c);
                }
                else
                {
                    RemoveWatermark(c);
                }
            }
            else
            {
                ShowWatermark(c);
            }
        }
    
        /// <summary>
        /// Event handler for the items changed event
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="ItemsChangedEventArgs"/> that contains the event data.</param>
        private static void ItemsChanged(object sender, ItemsChangedEventArgs e)
        {
            ItemsControl control;
            if (itemsControls.TryGetValue(sender, out control))
            {
                if (ShouldShowWatermark(control))
                {
                    ShowWatermark(control);
                }
                else
                {
                    RemoveWatermark(control);
                }
            }
        }
    
        #endregion
    
        #region Helper Methods
    
        /// <summary>
        /// Remove the watermark from the specified element
        /// </summary>
        /// <param name="control">Element to remove the watermark from</param>
        private static void RemoveWatermark(UIElement control)
        {
            AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
    
            // layer could be null if control is no longer in the visual tree
            if (layer != null)
            {
                Adorner[] adorners = layer.GetAdorners(control);
                if (adorners == null)
                {
                    return;
                }
    
                foreach (Adorner adorner in adorners)
                {
                    if (adorner is WatermarkAdorner)
                    {
                        adorner.Visibility = Visibility.Hidden;
                        layer.Remove(adorner);
                    }
                }
            }
        }
    
        /// <summary>
        /// Show the watermark on the specified control
        /// </summary>
        /// <param name="control">Control to show the watermark on</param>
        private static void ShowWatermark(Control control)
        {
            AdornerLayer layer = AdornerLayer.GetAdornerLayer(control);
    
            // layer could be null if control is no longer in the visual tree
            if (layer != null)
            {
                layer.Add(new WatermarkAdorner(control, GetWatermark(control)));
            }
        }
    
        /// <summary>
        /// Indicates whether or not the watermark should be shown on the specified control
        /// </summary>
        /// <param name="c"><see cref="Control"/> to test</param>
        /// <returns>true if the watermark should be shown; false otherwise</returns>
        private static bool ShouldShowWatermark(Control c)
        {
            if (c is ComboBox)
            {
                return (c as ComboBox).Text == string.Empty;
            }
            else if (c is TextBoxBase)
            {
                return (c as TextBox).Text == string.Empty;
            }
            else if (c is ItemsControl)
            {
                return (c as ItemsControl).Items.Count == 0;
            }
            else
            {
                return false;
            }
        }
    
        #endregion
    }
    

    The Attached Property uses a class called WatermarkAdorner, here is that source:

    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Media;
    
    /// <summary>
    /// Adorner for the watermark
    /// </summary>
    internal class WatermarkAdorner : Adorner
    {
        #region Private Fields
    
        /// <summary>
        /// <see cref="ContentPresenter"/> that holds the watermark
        /// </summary>
        private readonly ContentPresenter contentPresenter;
    
        #endregion
    
        #region Constructor
    
        /// <summary>
        /// Initializes a new instance of the <see cref="WatermarkAdorner"/> class
        /// </summary>
        /// <param name="adornedElement"><see cref="UIElement"/> to be adorned</param>
        /// <param name="watermark">The watermark</param>
        public WatermarkAdorner(UIElement adornedElement, object watermark) :
           base(adornedElement)
        {
            this.IsHitTestVisible = false;
    
            this.contentPresenter = new ContentPresenter();
            this.contentPresenter.Content = watermark;
            this.contentPresenter.Opacity = 0.5;
            this.contentPresenter.Margin = new Thickness(Control.Margin.Left + Control.Padding.Left, Control.Margin.Top + Control.Padding.Top, 0, 0);
    
            if (this.Control is ItemsControl && !(this.Control is ComboBox))
            {
                this.contentPresenter.VerticalAlignment = VerticalAlignment.Center;
                this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center;
            }
    
            // Hide the control adorner when the adorned element is hidden
            Binding binding = new Binding("IsVisible");
            binding.Source = adornedElement;
            binding.Converter = new BooleanToVisibilityConverter();
            this.SetBinding(VisibilityProperty, binding);
        }
    
        #endregion
    
        #region Protected Properties
    
        /// <summary>
        /// Gets the number of children for the <see cref="ContainerVisual"/>.
        /// </summary>
        protected override int VisualChildrenCount
        {
            get { return 1; }
        }
    
        #endregion
    
        #region Private Properties
    
        /// <summary>
        /// Gets the control that is being adorned
        /// </summary>
        private Control Control
        {
            get { return (Control)this.AdornedElement; }
        }
    
        #endregion
    
        #region Protected Overrides
    
        /// <summary>
        /// Returns a specified child <see cref="Visual"/> for the parent <see cref="ContainerVisual"/>.
        /// </summary>
        /// <param name="index">A 32-bit signed integer that represents the index value of the child <see cref="Visual"/>. The value of index must be between 0 and <see cref="VisualChildrenCount"/> - 1.</param>
        /// <returns>The child <see cref="Visual"/>.</returns>
        protected override Visual GetVisualChild(int index)
        {
            return this.contentPresenter;
        }
    
        /// <summary>
        /// Implements any custom measuring behavior for the adorner.
        /// </summary>
        /// <param name="constraint">A size to constrain the adorner to.</param>
        /// <returns>A <see cref="Size"/> object representing the amount of layout space needed by the adorner.</returns>
        protected override Size MeasureOverride(Size constraint)
        {
            // Here's the secret to getting the adorner to cover the whole control
            this.contentPresenter.Measure(Control.RenderSize);
            return Control.RenderSize;
        }
    
        /// <summary>
        /// When overridden in a derived class, positions child elements and determines a size for a <see cref="FrameworkElement"/> derived class. 
        /// </summary>
        /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
        /// <returns>The actual size used.</returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            this.contentPresenter.Arrange(new Rect(finalSize));
            return finalSize;
        }
    
        #endregion
    }
    

    Now you can put a watermark on any TextBox like this:

    <AdornerDecorator>
       <TextBox x:Name="SearchTextBox">
          <controls:WatermarkService.Watermark>
             <TextBlock>Type here to search text</TextBlock>
          </controls:WatermarkService.Watermark>
       </TextBox>
    </AdornerDecorator>
    

    The watermark can be anything you want (text, images ...). In addition to working for TextBoxes, this watermark also works for ComboBoxes and ItemControls.

    This code was adapted from this blog post.

    JavaScript alert box with timer

    tooltips can be used as alerts. These can be timed to appear and disappear.

    CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.

    Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.

    Access to the path is denied

    I got this problem when I try to save the file without set the file name.

    Old Code

    File.WriteAllBytes(@"E:\Folder", Convert.FromBase64String(Base64String));
    

    Working Code

    File.WriteAllBytes(@"E:\Folder\"+ fileName, Convert.FromBase64String(Base64String));
    

    What is the order of precedence for CSS?

    Also important to note is that when you have two styles on an HTML element with equal precedence, the browser will give precedence to the styles that were written to the DOM last ... so if in the DOM:

    <html>
    <head>
    <style>.container-ext { width: 100%; }</style>
    <style>.container { width: 50px; }</style>
    </head>
    <body>
    <div class="container container-ext">Hello World</div>
    </body>
    

    ...the width of the div will be 50px

    Replace part of a string with another string

    I'm just now learning C++, but editing some of the code previously posted, I'd probably use something like this. This gives you the flexibility to replace 1 or multiple instances, and also lets you specify the start point.

    using namespace std;
    
    // returns number of replacements made in string
    long strReplace(string& str, const string& from, const string& to, size_t start = 0, long count = -1) {
        if (from.empty()) return 0;
    
        size_t startpos = str.find(from, start);
        long replaceCount = 0;
    
        while (startpos != string::npos){
            str.replace(startpos, from.length(), to);
            startpos += to.length();
            replaceCount++;
    
            if (count > 0 && replaceCount >= count) break;
            startpos = str.find(from, startpos);
        }
    
        return replaceCount;
    }
    

    self referential struct definition?

    In C, you cannot reference the typedef that you're creating withing the structure itself. You have to use the structure name, as in the following test program:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct Cell {
      int cellSeq;
      struct Cell* next; /* 'tCell *next' will not work here */
    } tCell;
    
    int main(void) {
        int i;
        tCell *curr;
        tCell *first;
        tCell *last;
    
        /* Construct linked list, 100 down to 80. */
    
        first = malloc (sizeof (tCell));
        last = first;
        first->cellSeq = 100;
        first->next = NULL;
        for (i = 0; i < 20; i++) {
            curr = malloc (sizeof (tCell));
            curr->cellSeq = last->cellSeq - 1;
            curr->next = NULL;
            last->next = curr;
            last = curr;
        }
    
        /* Walk the list, printing sequence numbers. */
    
        curr = first;
        while (curr != NULL) {
            printf ("Sequence = %d\n", curr->cellSeq);
            curr = curr->next;
        }
    
        return 0;
    }
    

    Although it's probably a lot more complicated than this in the standard, you can think of it as the compiler knowing about struct Cell on the first line of the typedef but not knowing about tCell until the last line :-) That's how I remember that rule.

    jquery toggle slide from left to right and back

    Sliding from the right:

    $('#example').animate({width:'toggle'},350);
    

    Sliding to the left:

    $('#example').toggle({ direction: "left" }, 1000);
    

    refresh both the External data source and pivot tables together within a time schedule

    Auto Refresh Workbook for example every 5 sec. Apply to module

    Public Sub Refresh()
    'refresh
    ActiveWorkbook.RefreshAll
    
    alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
        Application.OnTime alertTime, "Refresh"
    
    End Sub
    

    Apply to Workbook on Open

    Private Sub Workbook_Open()
    alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"
    End Sub
    

    :)

    How can I install packages using pip according to the requirements.txt file from a local directory?

    Installing requirements.txt file inside virtual env with Python 3:

    I had the same issue. I was trying to install the requirements.txt file inside a virtual environment. I found the solution.

    Initially, I created my virtualenv in this way:

    virtualenv -p python3 myenv
    

    Activate the environment using:

    source myenv/bin/activate
    

    Now I installed the requirements.txt file using:

    pip3 install -r requirements.txt
    

    Installation was successful and I was able to import the modules.

    Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

    The root cause is that the sql server database you took the schema from has a collation that differs from your local installation. If you don't want to worry about collation re install SQL Server locally using the same collation as the SQL Server 2008 database.

    Convert dictionary to bytes and back again python?

    If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

    For example:

    my_dict = {'key' : [1,2,3]}
    
    import json
    def dict_to_binary(the_dict):
        str = json.dumps(the_dict)
        binary = ' '.join(format(ord(letter), 'b') for letter in str)
        return binary
    
    
    def binary_to_dict(the_binary):
        jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
        d = json.loads(jsn)  
        return d
    
    bin = dict_to_binary(my_dict)
    print bin
    
    dct = binary_to_dict(bin)
    print dct
    

    will give the output

    1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101
    
    {u'key': [1, 2, 3]}
    

    jQuery toggle animation

    I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

    For example:

    $('.btnName').click(function() {
     top.$('#panel').toggle(function() {
       $(this).animate({ 
         // style change
       }, 500);
       },
       function() {
       $(this).animate({ 
         // style change back
       }, 500);
     });
    

    Get the index of a certain value in an array in PHP

    You'll have to create a function for this. I don't think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:

    <?php
    
    $given_array = array('Monday' => 'boring',
    'Friday' => 'yay',
    'boring',
    'Sunday' => 'fun',
    7 => 'boring',
    'Saturday' => 'yay fun',
    'Wednesday' => 'boring',
    'my life' => 'boring');
    
    $repeating_value = "boring";
    
    function array_value_positions($array, $value){
        $index = 0;
        $value_array = array();
            foreach($array as $v){
                if($value == $v){
                    $value_array[$index] = $value;
                }
            $index++;
            }
        return $value_array;
    }
    
    $value_array = array_value_positions($given_array, $repeating_value);
    
    $result = "The value '$value_array[0]' was found at these indices in the given array: ";
    
    $key_string = implode(', ',array_keys($value_array));
    
    echo $result . $key_string . "\n";//Output: The value 'boring' was found at these indices in the given array: 0, 2, 4, 6, 7
    
    

    C++ unordered_map using a custom class type as the key

    For enum type, I think this is a suitable way, and the difference between class is how to calculate hash value.

    template <typename T>
    struct EnumTypeHash {
      std::size_t operator()(const T& type) const {
        return static_cast<std::size_t>(type);
      }
    };
    
    enum MyEnum {};
    class MyValue {};
    
    std::unordered_map<MyEnum, MyValue, EnumTypeHash<MyEnum>> map_;
    

    Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

    You may need to do AndroidStudio - Build - Clean

    If you updated manifest through the filesystem or Git it won't pick up the changes.

    How to stop creating .DS_Store on Mac?

    Open Terminal. Execute this command:

    defaults write com.apple.desktopservices DSDontWriteNetworkStores true
    

    Either restart the computer or log out and back in to the user account.

    for more informations:

    http://support.apple.com/kb/ht1629

    SQL: Group by minimum value in one field while selecting distinct rows

    To get the cheapest product in each category, you use the MIN() function in a correlated subquery as follows:

        SELECT categoryid,
           productid,
           productName,
           unitprice 
        FROM products a WHERE unitprice = (
                    SELECT MIN(unitprice)
                    FROM products b
                    WHERE b.categoryid = a.categoryid)
    

    The outer query scans all rows in the products table and returns the products that have unit prices match with the lowest price in each category returned by the correlated subquery.

    session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

    Ran into this issue and was able to solve by 2 main steps:

    1 - Update to latest chromedriver via homebrew cli

    brew cask upgrade chromedriver
    

    2 - update to lastest ver via Chrome GUI

    chrome://settings/help or cmd + , then tacking on help at the end (your choice)

    from there you should land on the About Chrome Page. Here you will need to verify that you are on the latest and greatest version (problem i was running into stemmed from a mismatch in the cli vs the current chrome version)

    if you getting the error, you will see a update & relaunch primary action button.

    after chrome "relaunches" it will now have the newest version matching your cli

    example:

    Google Chrome is up to date
    Version 80.0.3987.87 (Official Build) (64-bit)
    

    Couldn't load memtrack module Logcat Error

    I had the same error. Creating a new AVD with the appropriate API level solved my problem.

    When is layoutSubviews called?

    I had a similar question, but wasn't satisfied with the answer (or any I could find on the net), so I tried it in practice and here is what I got:

    • init does not cause layoutSubviews to be called (duh)
    • addSubview: causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target
    • view setFrame intelligently calls layoutSubviews on the view having its frame set only if the size parameter of the frame is different
    • scrolling a UIScrollView causes layoutSubviews to be called on the scrollView, and its superview
    • rotating a device only calls layoutSubview on the parent view (the responding viewControllers primary view)
    • Resizing a view will call layoutSubviews on its superview

    My results - http://blog.logichigh.com/2011/03/16/when-does-layoutsubviews-get-called/

    Django request.GET

    from django.http import QueryDict
    
    def search(request):
    if request.GET.\__contains__("q"):
        message = 'You submitted: %r' % request.GET['q']
    else:
        message = 'You submitted nothing!'
    return HttpResponse(message)
    

    Use this way, django offical document recommended __contains__ method. See https://docs.djangoproject.com/en/1.9/ref/request-response/

    How can I make an entire HTML form "readonly"?

    You add html invisible layer over the form. For instance

    <div class="coverContainer">
    <form></form>
    </div>
    

    and style:

    .coverContainer{
        width: 100%;
        height: 100%;
        z-index: 100;
        background: rgba(0,0,0,0);
        position: absolute;
    }
    

    Ofcourse user can hide this layer in web browser.

    python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

    So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

    r" |(?<![0-9])[.,](?![0-9])"
    

    Which HTML elements can receive focus?

    There isn't a definite list, it's up to the browser. The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement and HTMLAnchorElement. This notably omits HTMLButtonElement and HTMLAreaElement.

    Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of:

    • HTMLAnchorElement/HTMLAreaElement with an href
    • HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
    • HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
    • Any element with a tabindex

    There are likely to be other subtle exceptions and additions to this behaviour depending on browser.

    Reset ID autoincrement ? phpmyadmin

    ALTER TABLE xxx AUTO_INCREMENT =1; or clear your table by TRUNCATE

    If isset $_POST

    To answer the posted question: isset and empty together gives three conditions. This can be used by Javascript with an ajax command as well.

    $errMess="Didn't test";   // This message should not show
    if(isset($_POST["foo"])){ // does it exist or not
        $foo = $_POST["foo"]; // save $foo from POST made by HTTP request
        if(empty($foo)){      // exist but it's null
            $errMess="Empty"; // #1 Nothing in $foo it's emtpy
    
        } else {              // exist and has data
            $errMess="None";  // #2 Something in $foo use it now
          }
    } else {                  // couldn't find ?foo=dataHere
         $errMess="Missing";  // #3 There's no foo in request data
      }
    
    echo "Was there a problem: ".$errMess."!";
    

    Removing multiple files from a Git repo that have already been deleted from disk

    As mentioned

    git add -u
    

    stages the removed files for deletion, BUT ALSO modified files for update.

    To unstage the modified files you can do

    git reset HEAD <path>
    

    if you like to keep your commits organized and clean.
    NOTE: This could also unstage the deleted files, so careful with those wildcards.

    Why does flexbox stretch my image rather than retaining aspect ratio?

    Adding margin to align images:

    Since we wanted the image to be left-aligned, we added:

    img {
      margin-right: auto;
    }
    

    Similarly for image to be right-aligned, we can add margin-right: auto;. The snippet shows a demo for both types of alignment.

    Good Luck...

    _x000D_
    _x000D_
    div {_x000D_
      display:flex; _x000D_
      flex-direction:column;_x000D_
      border: 2px black solid;_x000D_
    }_x000D_
    _x000D_
    h1 {_x000D_
      text-align: center;_x000D_
    }_x000D_
    hr {_x000D_
      border: 1px black solid;_x000D_
      width: 100%_x000D_
    }_x000D_
    img.one {_x000D_
      margin-right: auto;_x000D_
    }_x000D_
    _x000D_
    img.two {_x000D_
      margin-left: auto;_x000D_
    }
    _x000D_
    <div>_x000D_
      <h1>Flex Box</h1>_x000D_
      _x000D_
      <hr />_x000D_
      _x000D_
      <img src="https://via.placeholder.com/80x80" class="one" _x000D_
      />_x000D_
      _x000D_
      _x000D_
      <img src="https://via.placeholder.com/80x80" class="two" _x000D_
      />_x000D_
      _x000D_
      <hr />_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    arranging div one below the other

    The default behaviour of divs is to take the full width available in their parent container.
    This is the same as if you'd give the inner divs a width of 100%.

    By floating the divs, they ignore their default and size their width to fit the content. Everything behind it (in the HTML), is placed under the div (on the rendered page).
    This is the reason that they align theirselves next to each other.

    The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.

    Source: https://developer.mozilla.org/en-US/docs/Web/CSS/float

    Get rid of the float, and the divs will be aligned under each other.
    If this does not happen, you'll have some other css on divs or children of wrapper defining a floating behaviour or an inline display.

    If you want to keep the float, for whatever reason, you can use clear on the 2nd div to reset the floating properties of elements before that element.
    clear has 5 valid values: none | left | right | both | inherit. Clearing no floats (used to override inherited properties), left or right floats or both floats. Inherit means it'll inherit the behaviour of the parent element

    Also, because of the default behaviour, you don't need to set the width and height on auto.
    You only need this is you want to set a hardcoded height/width. E.g. 80% / 800px / 500em / ...

    <div id="wrapper">
        <div id="inner1"></div>
        <div id="inner2"></div>
    </div>
    

    CSS is

    #wrapper{
        margin-left:auto;
        margin-right:auto;
        height:auto; // this is not needed, as parent container, this div will size automaticly
        width:auto; // this is not needed, as parent container, this div will size automaticly
    }
    
    /*
    You can get rid of the inner divs in the css, unless you want to style them.
    If you want to style them identicly, you can use concatenation
    */
    #inner1, #inner2 {
        border: 1px solid black;
    }
    

    Reading data from XML

    I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).

    Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath"). From there its just a matter of querying the data you want, say like this:

    var authors = doc.Root.Elements().Select( x => x.Element("Author") );
    

    HTH.

    EDIT:

    Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):

    using System;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1 {
        class Program {
            static void Main( string[] args )  {
                XDocument doc = XDocument.Load( "XMLFile1.xml" );
                var authors = doc.Descendants( "Author" );
                foreach ( var author in authors ) {
                    Console.WriteLine( author.Value );
                }
                Console.ReadLine();
            }
        }
    }
    

    You will need to adjust the path in XDocument.Load() to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.

    Clicking URLs opens default browser

    Official documentation says, click on a link in a WebView will launch application that handles URLs. You need to override this default behavior

        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
    

    or if there is no conditional logic in the method simply do this

    myWebView.setWebViewClient(new WebViewClient());
    

    Create a file from a ByteArrayOutputStream

    You can do it with using a FileOutputStream and the writeTo method.

    ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
    try(OutputStream outputStream = new FileOutputStream("thefilename")) {
        byteArrayOutputStream.writeTo(outputStream);
    }
    

    Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

    phpMyAdmin + CentOS 6.0 - Forbidden

    I have faced the same problem when I tape the URL

    https://www.nameDomain.com/phpmyadmin
    

    the forbidden message shows up, because of the rules on /use/share/phpMyAdmin directory I fix it by adding in this file /etc/httpd/conf.d/phpMyAdmin.conf in this section

    <Directory /usr/share/phpMyAdmin/>
        ....
    </Directory>
    

    these line of rules

    <Directory /usr/share/phpMyAdmin/>
       Order Deny,Allow
       Deny from All
       Allow from 127.0.0.1
       Allow from ::1
       Allow from All
       ...
    </Directory>
    

    you save the file, then you restart the apache service whatever method you choose service httpd graceful or service httpd restart it depends on your policy

    for security reasons you can specify one connection by setting one IP address if your IP does not change, else if your IP changes every time you have to change it also.

    <Directory /usr/share/phpMyAdmin/>
       Order Deny,Allow
       Deny from All
       Allow from 127.0.0.1
       Allow from ::1
       Allow from 105.105.105.254 ## set here your IP address
       ...
    </Directory>
    

    LF will be replaced by CRLF in git - What is that and is it important?

    In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.

    If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line

    git config core.autocrlf true
    

    If you want to make an intelligent decision how git should handle this, read the documentation

    Here is a snippet

    Formatting and Whitespace

    Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.

    core.autocrlf
    

    If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.

    Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:

    $ git config --global core.autocrlf true
    

    If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:

    $ git config --global core.autocrlf input
    

    This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.

    If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:

    $ git config --global core.autocrlf false
    

    ValueError: max() arg is an empty sequence

    When the length of v will be zero, it'll give you the value error.

    You should check the length or you should check the list first whether it is none or not.

    if list:
        k.index(max(list))
    

    or

    len(list)== 0
    

    How to redirect both stdout and stderr to a file

    You can do it like that 2>&1:

     command > file 2>&1
    

    In PHP, what is a closure and why does it use the "use" identifier?

    closures are beautiful! they solve a lot of problems that come with anonymous functions, and make really elegant code possible (at least as long as we talk about php).

    javascript programmers use closures all the time, sometimes even without knowing it, because bound variables aren't explicitly defined - that's what "use" is for in php.

    there are better real-world examples than the above one. lets say you have to sort an multidimensional array by a sub-value, but the key changes.

    <?php
        function generateComparisonFunctionForKey($key) {
            return function ($left, $right) use ($key) {
                if ($left[$key] == $right[$key])
                    return 0;
                else
                    return ($left[$key] < $right[$key]) ? -1 : 1;
            };
        }
    
        $myArray = array(
            array('name' => 'Alex', 'age' => 70),
            array('name' => 'Enrico', 'age' => 25)
        );
    
        $sortByName = generateComparisonFunctionForKey('name');
        $sortByAge  = generateComparisonFunctionForKey('age');
    
        usort($myArray, $sortByName);
    
        usort($myArray, $sortByAge);
    ?>
    

    warning: untested code (i don't have php5.3 installed atm), but it should look like something like that.

    there's one downside: a lot of php developers may be a bit helpless if you confront them with closures.

    to understand the nice-ty of closures more, i'll give you another example - this time in javascript. one of the problems is the scoping and the browser inherent asynchronity. especially, if it comes to window.setTimeout(); (or -interval). so, you pass a function to setTimeout, but you can't really give any parameters, because providing parameters executes the code!

    function getFunctionTextInASecond(value) {
        return function () {
            document.getElementsByName('body')[0].innerHTML = value; // "value" is the bound variable!
        }
    }
    
    var textToDisplay = prompt('text to show in a second', 'foo bar');
    
    // this returns a function that sets the bodys innerHTML to the prompted value
    var myFunction = getFunctionTextInASecond(textToDisplay);
    
    window.setTimeout(myFunction, 1000);
    

    myFunction returns a function with a kind-of predefined parameter!

    to be honest, i like php a lot more since 5.3 and anonymous functions/closures. namespaces may be more important, but they're a lot less sexy.

    What does "commercial use" exactly mean?

    I suggest this discriminative question:

    Is the open-source tool necessary in your process of making money?

    • a blog engine on your commercial web site is necessary: commercial use.
    • winamp for listening to music is not necessary: non-commercial use.

    Serialize Class containing Dictionary member

    You can't serialize a class that implements IDictionary. Check out this link.

    Q: Why can't I serialize hashtables?

    A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

    So I think you need to create your own version of the Dictionary for this. Check this other question.

    How to use wget in php?

    wget

    wget is a linux command, not a PHP command, so to run this you woud need to use exec, which is a PHP command for executing shell commands.

    exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");
    

    This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.

    The exec function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini, to enable, remove exec from the disabled_functions config string.

    alternative

    Using file_get_contents we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.

    // standard url
    $content = file_get_contents("http://www.example.com/file.xml");
    
    // or with basic auth
    $content = file_get_contents("http://user:[email protected]/file.xml");
    

    As noted by Sean the Bean - you may also need to change allow_url_fopen to true in your php.ini to allow the use of a URL in this method, however, this should be true by default.

    If you want to then store that file locally, there is a function file_put_contents to write that into a file, combined with the previous, this could emulate a file download:

    file_put_contents("local_file.xml", $content);
    

    how to open popup window using jsp or jquery?

    <a href="javaScript:{openPopUp();}"></a>
    <form action="actionName">
    <div id="divId" style="display:none;">
    UsreName:<input type="text" name="userName"/>
    </div>
    </form>
    
    function openPopUp()
    {
      $('#divId').css('display','block');
    $('#divId').dialog();
    }
    

    C# windows application Event: CLR20r3 on application start

    Have been fighting this all morning and now have it solved and why it happened. Posting with the hope it helps others

    I installed the Krypton.Toolkit which added the tools to the Visual studio toolbox automatically. I then added the tools to the designer, which automatically added the dll to the projrect references, however the toolkit was marked as CopyLocal=false

    I built an installer, using all dlls in the release build folder (of course the above dll wasn't there).

    Setting copylocal=true, then rebuilding the installer, everything worked fine.

    How to add a single item to a Pandas Series

    TLDR: do not append items to a series one by one, better extend with an ordered collection

    I think the question in its current form is a bit tricky. And the accepted answer does answer the question. But the more I use pandas, the more I understand that it's a bad idea to append items to a Series one by one. I'll try to explain why for pandas beginners.

    You might think that appending data to a given Series might allow you to reuse some resources, but in reality a Series is just a container that stores a relation between an index and a values array. Each is a numpy.array under the hood, and the index is immutable. When you add to Series an item with a label that is missing in the index, a new index with size n+1 is created, and a new values values array of the same size. That means that when you append items one by one, you create two more arrays of the n+1 size on each step.

    By the way, you can not append a new item by position (you will get an IndexError) and the label in an index does not have to be unique, that is when you assign a value with a label, you assign the value to all existing items with the the label, and a new row is not appended in this case. This might lead to subtle bugs.

    The moral of the story is that you should not append data one by one, you should better extend with an ordered collection. The problem is that you can not extend a Series inplace. That is why it is better to organize your code so that you don't need to update a specific instance of a Series by reference.

    If you create labels yourself and they are increasing, the easiest way is to add new items to a dictionary, then create a new Series from the dictionary (it sorts the keys) and append the Series to an old one. If the keys are not increasing, then you will need to create two separate lists for the new labels and the new values.

    Below are some code samples:

    In [1]: import pandas as pd
    In [2]: import numpy as np
    
    In [3]: s = pd.Series(np.arange(4)**2, index=np.arange(4))
    
    In [4]: s
    Out[4]:
    0    0
    1    1
    2    4
    3    9
    dtype: int64
    
    In [6]: id(s.index), id(s.values)
    Out[6]: (4470549648, 4470593296)
    

    When we update an existing item, the index and the values array stay the same (if you do not change the type of the value)

    In [7]: s[2] = 14  
    
    In [8]: id(s.index), id(s.values)
    Out[8]: (4470549648, 4470593296)
    

    But when you add a new item, a new index and a new values array is generated:

    In [9]: s[4] = 16
    
    In [10]: s
    Out[10]:
    0     0
    1     1
    2    14
    3     9
    4    16
    dtype: int64
    
    In [11]: id(s.index), id(s.values)
    Out[11]: (4470548560, 4470595056)
    

    That is if you are going to append several items, collect them in a dictionary, create a Series, append it to the old one and save the result:

    In [13]: new_items = {item: item**2 for item in range(5, 7)}
    
    In [14]: s2 = pd.Series(new_items)
    
    In [15]: s2  # keys are guaranteed to be sorted!
    Out[15]:
    5    25
    6    36
    dtype: int64
    
    In [16]: s = s.append(s2); s
    Out[16]:
    0     0
    1     1
    2    14
    3     9
    4    16
    5    25
    6    36
    dtype: int64
    

    Remove leading zeros from a number in Javascript

    It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

    value = +value;
    

    If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

    input.value = +input.value;
    

    is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

    open link of google play store in mobile version android

    You'll want to use the specified market protocol:

    final String appPackageName = "com.example"; // Can also use getPackageName(), as below
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
    

    Keep in mind, this will crash on any device that does not have the Market installed (the emulator, for example). Hence, I would suggest something like:

    final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
    try {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
    } catch (android.content.ActivityNotFoundException anfe) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
    }
    

    While using getPackageName() from Context or subclass thereof for consistency (thanks @cprcrack!). You can find more on Market Intents here: link.

    how to use sqltransaction in c#

    You can create a SqlTransaction from a SqlConnection.

    And use it to create any number of SqlCommands

    SqlTransaction transaction = connection.BeginTransaction();
    var cmd1 = new SqlCommand(command1Text, connection, transaction);
    var cmd2 = new SqlCommand(command2Text, connection, transaction);
    

    Or

    var cmd1 = new SqlCommand(command1Text, connection, connection.BeginTransaction());
    var cmd2 = new SqlCommand(command2Text, connection, cmd1.Transaction);
    

    If the failure of commands never cause unexpected changes don't use transaction.

    if the failure of commands might cause unexpected changes put them in a Try/Catch block and rollback the operation in another Try/Catch block.

    Why another try/catch? According to MSDN:

    Try/Catch exception handling should always be used when rolling back a transaction. A Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

    Here is a sample code:

    string connStr = "[connection string]";
    string cmdTxt = "[t-sql command text]";
    
    using (var conn = new SqlConnection(connStr))
    {
        conn.Open();
        var cmd = new SqlCommand(cmdTxt, conn, conn.BeginTransaction());
    
    
        try
        {
            cmd.ExecuteNonQuery();
            //before this line, nothing has happened yet
            cmd.Transaction.Commit();
        }
        catch(System.Exception ex)
        {
            //You should always use a Try/Catch for transaction's rollback
            try
            {
                cmd.Transaction.Rollback();
            }
            catch(System.Exception ex2)
            {
                throw ex2;
            }
            throw ex;
        }
    
        conn.Close();
    }
    

    The transaction is rolled back in the event it is disposed before Commit or Rollback is called.

    So you don't need to worry about app being closed.

    Sorting an array in C?

    Depends

    It depends on various things. But in general algorithms using a Divide-and-Conquer / dichotomic approach will perform well for sorting problems as they present interesting average-case complexities.

    Basics

    To understand which algorithms work best, you will need basic knowledge of algorithms complexity and big-O notation, so you can understand how they rate in terms of average case, best case and worst case scenarios. If required, you'd also have to pay attention to the sorting algorithm's stability.

    For instance, usually an efficient algorithm is quicksort. However, if you give quicksort a perfectly inverted list, then it will perform poorly (a simple selection sort will perform better in that case!). Shell-sort would also usually be a good complement to quicksort if you perform a pre-analysis of your list.

    Have a look at the following, for "advanced searches" using divide and conquer approaches:

    And these more straighforward algorithms for less complex ones:

    Further

    The above are the usual suspects when getting started, but there are countless others.

    As pointed out by R. in the comments and by kriss in his answer, you may want to have a look at HeapSort, which provides a theoretically better sorting complexity than a quicksort (but will won't often fare better in practical settings). There are also variants and hybrid algorithms (e.g. TimSort).

    Add days to JavaScript Date

    As simple as this:

    new Date((new Date()).getTime() + (60*60*24*1000));
    

    Windows service on Local Computer started and then stopped error

    The account which is running the service might not have mapped the D:-drive (they are user-specific). Try sharing the directory, and use full UNC-path in your backupConfig.

    Your watcher of type FileSystemWatcher is a local variable, and is out of scope when the OnStart method is done. You probably need it as an instance or class variable.

    @Cacheable key on multiple method arguments

    After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}. This can also include null values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)

    I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:

    @Cacheable(value="bookCache", 
      key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
    public Book findBook(ISBN isbn, boolean checkWarehouse) 
    ...
    
    @Cacheable(value="bookCache", 
      key="{ #root.methodName, #asin, #checkWarehouse }")
    public Book findBookByAmazonId(String asin, boolean checkWarehouse)
    ...
    

    Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:

    <cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
    <bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />
    

    ...with:

    public class CacheKeyGenerator 
      implements org.springframework.cache.interceptor.KeyGenerator {
    
        @Override
        public Object generate(final Object target, final Method method, 
          final Object... params) {
    
            final List<Object> key = new ArrayList<>();
            key.add(method.getDeclaringClass().getName());
            key.add(method.getName());
    
            for (final Object o : params) {
                key.add(o);
            }
            return key;
        }
    }
    

    How do I get SUM function in MySQL to return '0' if no values are found?

    Use IFNULL or COALESCE:

    SELECT IFNULL(SUM(Column1), 0) AS total FROM...
    
    SELECT COALESCE(SUM(Column1), 0) AS total FROM...
    

    The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.

    Simple way to measure cell execution time in ipython notebook

    %time and %timeit now come part of ipython's built-in magic commands

    How to get enum value by string or int

    Following is the method in C# to get the enum value by string

    ///
    /// Method to get enumeration value from string value.
    ///
    ///
    ///
    
    public T GetEnumValue<T>(string str) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val = ((T[])Enum.GetValues(typeof(T)))[0];
        if (!string.IsNullOrEmpty(str))
        {
            foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
            {
                if (enumValue.ToString().ToUpper().Equals(str.ToUpper()))
                {
                    val = enumValue;
                    break;
                }
            }
        }
    
        return val;
    }
    

    Following is the method in C# to get the enum value by int.

    ///
    /// Method to get enumeration value from int value.
    ///
    ///
    ///
    
    public T GetEnumValue<T>(int intValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val = ((T[])Enum.GetValues(typeof(T)))[0];
    
        foreach (T enumValue in (T[])Enum.GetValues(typeof(T)))
        {
            if (Convert.ToInt32(enumValue).Equals(intValue))
            {
                val = enumValue;
                break;
            }             
        }
        return val;
    }
    

    If I have an enum as follows:

    public enum TestEnum
    {
        Value1 = 1,
        Value2 = 2,
        Value3 = 3
    }
    

    then I can make use of above methods as

    TestEnum reqValue = GetEnumValue<TestEnum>("Value1");  // Output: Value1
    TestEnum reqValue2 = GetEnumValue<TestEnum>(2);        // OutPut: Value2
    

    Hope this will help.

    IO Error: The Network Adapter could not establish the connection

    Most probably you have listener configured wrongly, the hostname you specify in connection string must be the same as in the listener.

    First check the Firewall and network related issues.

    Check if Oracle Listener service is available and running. If not you may use Oracle Net Configuration Assistant tool to add and register new listener.

    If the above steps are ok then you need to configure Oracle Listener appropriately. You may use Oracle Net Manager tool or edit “%ORACLE_HOME%\network\admin\listener.ora” file manually.

    There are 2 options that need to be considered carefully: Listening Locations associated with the Listener – Hostname(IP) and Port in Listening Location must exactly match the ones used in the connection string.

    For example, if you use 192.168.74.139 as target hostname, then there must be Listening Location registered with the same IP address.

    Also make sure the you use the same SID as indicated in Database Service associated with the Listener.

    https://adhoctuts.com/fix-oracle-io-error-the-network-adapter-could-not-establish-the-connection-error/

    Update ViewPager dynamically?

    After hours of frustration while trying all the above solutions to overcome this problem and also trying many solutions on other similar questions like this, this and this which all FAILED with me to solve this problem and to make the ViewPager to destroy the old Fragment and fill the pager with the new Fragments. I have solved the problem as following:

    1) Make the ViewPager class to extends FragmentPagerAdapter as following:

     public class myPagerAdapter extends FragmentPagerAdapter {
    

    2) Create an Item for the ViewPager that store the title and the fragment as following:

    public class PagerItem {
    private String mTitle;
    private Fragment mFragment;
    
    
    public PagerItem(String mTitle, Fragment mFragment) {
        this.mTitle = mTitle;
        this.mFragment = mFragment;
    }
    public String getTitle() {
        return mTitle;
    }
    public Fragment getFragment() {
        return mFragment;
    }
    public void setTitle(String mTitle) {
        this.mTitle = mTitle;
    }
    
    public void setFragment(Fragment mFragment) {
        this.mFragment = mFragment;
    }
    
    }
    

    3) Make the constructor of the ViewPager take my FragmentManager instance to store it in my class as following:

    private FragmentManager mFragmentManager;
    private ArrayList<PagerItem> mPagerItems;
    
    public MyPagerAdapter(FragmentManager fragmentManager, ArrayList<PagerItem> pagerItems) {
        super(fragmentManager);
        mFragmentManager = fragmentManager;
        mPagerItems = pagerItems;
    }
    

    4) Create a method to re-set the adapter data with the new data by deleting all the previous fragment from the fragmentManager itself directly to make the adapter to set the new fragment from the new list again as following:

    public void setPagerItems(ArrayList<PagerItem> pagerItems) {
        if (mPagerItems != null)
            for (int i = 0; i < mPagerItems.size(); i++) {
                mFragmentManager.beginTransaction().remove(mPagerItems.get(i).getFragment()).commit();
            }
        mPagerItems = pagerItems;
    }
    

    5) From the container Activity or Fragment do not re-initialize the adapter with the new data. Set the new data through the method setPagerItems with the new data as following:

    ArrayList<PagerItem> pagerItems = new ArrayList<PagerItem>();
        pagerItems.add(new PagerItem("Fragment1", new MyFragment1()));
        pagerItems.add(new PagerItem("Fragment2", new MyFragment2()));
    
        mPagerAdapter.setPagerItems(pagerItems);
        mPagerAdapter.notifyDataSetChanged();
    

    I hope it helps.

    Changing case in Vim

    Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

    Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

    For more of these, see Section 3 in Vim's change.txt help file.

    How to filter wireshark to see only dns queries that are sent/received from/by my computer?

    Rather than using a DisplayFilter you could use a very simple CaptureFilter like

    port 53
    

    See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.

    How can I represent an infinite number in Python?

    There is an infinity in the NumPy library: from numpy import inf. To get negative infinity one can simply write -inf.

    Does java.util.List.isEmpty() check if the list itself is null?

    This will throw a NullPointerException - as will any attempt to invoke an instance method on a null reference - but in cases like this you should make an explicit check against null:

    if ((test != null) && !test.isEmpty())
    

    This is much better, and clearer, than propagating an Exception.

    Notification bar icon turns white in Android 5 Lollipop

    You Need to import the single color transparent PNG image. So You can set the Icon color of the small icon. Otherwise it will be shown white in some devices like MOTO

    Verify a certificate chain using openssl verify

    From verify documentation:

    If a certificate is found which is its own issuer it is assumed to be the root CA.

    In other words, root CA needs to self signed for verify to work. This is why your second command didn't work. Try this instead:

    openssl verify -CAfile RootCert.pem -untrusted Intermediate.pem UserCert.pem
    

    It will verify your entire chain in a single command.

    Is it possible to open developer tools console in Chrome on Android phone?

    You can do it using remote debugging, here is official documentation. Basic process:

    1. Connect your android device
    2. Select your device: More tools > Inspect devices* from dev tools on pc/mac.
    3. Authorize on your mobile.
    4. Happy debugging!!

    * This is now "Remote devices".

    Iterator over HashMap in Java

    Can we see your import block? because it seems that you have imported the wrong Iterator class.

    The one you should use is java.util.Iterator

    To make sure, try:

    java.util.Iterator iter = hm.keySet().iterator();
    

    I personally suggest the following:

    Map Declaration using Generics and declaration using the Interface Map<K,V> and instance creation using the desired implementation HashMap<K,V>

    Map<Integer, String> hm = new HashMap<>();
    

    and for the loop:

    for (Integer key : hm.keySet()) {
        System.out.println("Key = " + key + " - " + hm.get(key));
    }
    

    UPDATE 3/5/2015

    Found out that iterating over the Entry set will be better performance wise:

    for (Map.Entry<Integer, String> entry : hm.entrySet()) {
        Integer key = entry.getKey();
        String value = entry.getValue();
    
    }
    

    UPDATE 10/3/2017

    For Java8 and streams, your solution will be (Thanks @Shihe Zhang)

     hm.forEach((key, value) -> System.out.println(key + ": " + value))
    

    What is the difference between public, protected, package-private and private in Java?

    David's answer provides the meaning of each access modifier. As for when to use each, I'd suggest making public all classes and the methods of each class that are meant for external use (its API), and everything else private.

    Over time you'll develop a sense for when to make some classes package-private and when to declare certain methods protected for use in subclasses.

    How to add a new row to an empty numpy array

    using an custom dtype definition, what worked for me was:

    import numpy
    
    # define custom dtype
    type1 = numpy.dtype([('freq', numpy.float64, 1), ('amplitude', numpy.float64, 1)])
    # declare empty array, zero rows but one column
    arr = numpy.empty([0,1],dtype=type1)
    # store row data, maybe inside a loop
    row = numpy.array([(0.0001, 0.002)], dtype=type1)
    # append row to the main array
    arr = numpy.row_stack((arr, row))
    # print values stored in the row 0
    print float(arr[0]['freq'])
    print float(arr[0]['amplitude'])
    

    How to parse JSON response from Alamofire API in Swift?

    Swift 3, Alamofire 4.4, and SwiftyJSON:

    Alamofire.request(url, method: .get)
      .responseJSON { response in
          if response.data != nil {
            let json = JSON(data: response.data!)
            let name = json["people"][0]["name"].string
            if name != nil {
              print(name!)
            }
          }
      }
    

    That will parse this JSON input:

    {
      people: [
        { name: 'John' },
        { name: 'Dave' }
      ]
    }
    

    change cursor to finger pointer

    Here is something cool if you want to go the extra mile with this. in the url, you can use a link or save an image png and use the path. for example:

    url('assets/imgs/theGoods.png');

    below is the code:

    .cursor{
      cursor:url(http://www.icon100.com/up/3772/128/425-hand-pointer.png), auto;
    }
    

    So this will only work under the size 128 X 128, any bigger and the image wont load. But you can practically use any image you want! This would be consider pure css3, and some html. all you got to do in html is

    <div class='cursor'></div>
    

    and only in that div, that cursor will show. So I usually add it to the body tag.

    Select statement to find duplicates on certain fields

    To see duplicate values:

    with MYCTE  as (
        select row_number() over ( partition by name  order by name) rown, *
        from tmptest  
        ) 
    select * from MYCTE where rown <=1
    

    How do I concatenate strings and variables in PowerShell?

    There is a difference between single and double quotes. (I am using PowerShell 4).

    You can do this (as Benjamin said):

    $name = 'Slim Shady'
    Write-Host 'My name is'$name
    -> My name is Slim Shady
    

    Or you can do this:

    $name = 'Slim Shady'
    Write-Host "My name is $name"
    -> My name is Slim Shady
    

    The single quotes are for literal, output the string exactly like this, please. The double quotes are for when you want some pre-processing done (such as variables, special characters, etc.)

    So:

    $name = "Marshall Bruce Mathers III"
    Write-Host "$name"
    -> Marshall Bruce Mathers III
    

    Whereas:

    $name = "Marshall Bruce Mathers III"
    Write-Host '$name'
    -> $name
    

    (I find How-to: Escape characters, Delimiters and Quotes good for reference).

    What does EntityManager.flush do and why do I need to use it?

    So when you call EntityManager.persist(), it only makes the entity get managed by the EntityManager and adds it (entity instance) to the Persistence Context. An Explicit flush() will make the entity now residing in the Persistence Context to be moved to the database (using a SQL).

    Without flush(), this (moving of entity from Persistence Context to the database) will happen when the Transaction to which this Persistence Context is associated is committed.

    Drop shadow on a div container?

    .shadow {
        -moz-box-shadow:    3px 3px 5px 6px #ccc;
        -webkit-box-shadow: 3px 3px 5px 6px #ccc;
        box-shadow:         3px 3px 5px 6px #ccc;
    }
    

    How to get relative path from absolute path

    A bit late to the question, but I just needed this feature as well. I agree with DavidK that since there is a built-in API function that provides this, you should use it. Here's a managed wrapper for it:

    public static string GetRelativePath(string fromPath, string toPath)
    {
        int fromAttr = GetPathAttribute(fromPath);
        int toAttr = GetPathAttribute(toPath);
    
        StringBuilder path = new StringBuilder(260); // MAX_PATH
        if(PathRelativePathTo(
            path,
            fromPath,
            fromAttr,
            toPath,
            toAttr) == 0)
        {
            throw new ArgumentException("Paths must have a common prefix");
        }
        return path.ToString();
    }
    
    private static int GetPathAttribute(string path)
    {
        DirectoryInfo di = new DirectoryInfo(path);
        if (di.Exists)
        {
            return FILE_ATTRIBUTE_DIRECTORY;
        }
    
        FileInfo fi = new FileInfo(path);
        if(fi.Exists)
        {
            return FILE_ATTRIBUTE_NORMAL;
        }
    
        throw new FileNotFoundException();
    }
    
    private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
    private const int FILE_ATTRIBUTE_NORMAL = 0x80;
    
    [DllImport("shlwapi.dll", SetLastError = true)]
    private static extern int PathRelativePathTo(StringBuilder pszPath, 
        string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
    

    WiX tricks and tips

    Performing a forced reinstall when an install doesn't allow uninstall or reinstall and doesn't roll back.

    VBscript script used for overriding an install that isn't uninstalling for whatever reason..

    Dim objShell
    set objShell = wscript.createObject("wscript.shell")
    
    iReturn = objShell.Run("CMD /K MsiExec.exe /I ""C:\Users\TheUser\Documents\Visual Studio 2010\Projects\InstallationTarget\HelloInstaller\bin\Debug\HelloInstaller.msi"" REINSTALLMODE=vomus REINSTALL=ALL",,True)
    

    Http Servlet request lose params from POST body after read it once

    As an aside, an alternative way to solve this problem is to not use the filter chain and instead build your own interceptor component, perhaps using aspects, which can operate on the parsed request body. It will also likely be more efficient as you are only converting the request InputStream into your own model object once.

    However, I still think it's reasonable to want to read the request body more than once particularly as the request moves through the filter chain. I would typically use filter chains for certain operations that I want to keep at the HTTP layer, decoupled from the service components.

    As suggested by Will Hartung I achieved this by extending HttpServletRequestWrapper, consuming the request InputStream and essentially caching the bytes.

    public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
      private ByteArrayOutputStream cachedBytes;
    
      public MultiReadHttpServletRequest(HttpServletRequest request) {
        super(request);
      }
    
      @Override
      public ServletInputStream getInputStream() throws IOException {
        if (cachedBytes == null)
          cacheInputStream();
    
          return new CachedServletInputStream();
      }
    
      @Override
      public BufferedReader getReader() throws IOException{
        return new BufferedReader(new InputStreamReader(getInputStream()));
      }
    
      private void cacheInputStream() throws IOException {
        /* Cache the inputstream in order to read it multiple times. For
         * convenience, I use apache.commons IOUtils
         */
        cachedBytes = new ByteArrayOutputStream();
        IOUtils.copy(super.getInputStream(), cachedBytes);
      }
    
      /* An inputstream which reads the cached request body */
      public class CachedServletInputStream extends ServletInputStream {
        private ByteArrayInputStream input;
    
        public CachedServletInputStream() {
          /* create a new input stream from the cached request body */
          input = new ByteArrayInputStream(cachedBytes.toByteArray());
        }
    
        @Override
        public int read() throws IOException {
          return input.read();
        }
      }
    }
    

    Now the request body can be read more than once by wrapping the original request before passing it through the filter chain:

    public class MyFilter implements Filter {
      @Override
      public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
    
        /* wrap the request in order to read the inputstream multiple times */
        MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);
    
        /* here I read the inputstream and do my thing with it; when I pass the
         * wrapped request through the filter chain, the rest of the filters, and
         * request handlers may read the cached inputstream
         */
        doMyThing(multiReadRequest.getInputStream());
        //OR
        anotherUsage(multiReadRequest.getReader());
        chain.doFilter(multiReadRequest, response);
      }
    }
    

    This solution will also allow you to read the request body multiple times via the getParameterXXX methods because the underlying call is getInputStream(), which will of course read the cached request InputStream.

    Edit

    For newer version of ServletInputStream interface. You need to provide implementation of few more methods like isReady, setReadListener etc. Refer this question as provided in comment below.