Programs & Examples On #Hat

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.

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

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

The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.

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 are missing a closing h2 tag. It should be:

<h2><!-- Content --></h2> 

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"/> 

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

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

How to make a variable accessible outside a function?

$.getJSON is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.

Alternatively you could use jQuery's $.when/.then(), similar to this:

var input = "netuetamundis";  var sID;  $(document).ready(function () {     $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () {         obj = name;         sID = obj.id;         console.log(sID);     })).then(function () {         $.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);         });     }); }); 

This would be more open for future modification and separates out the responsibility for the first call to know about the second call.

The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.

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.

Crop image to specified size and picture location

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

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

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); 

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).

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

python variable NameError

I would approach it like this:

sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s)                 for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1):     size = sizes[choice - 1] # note index offset from choice print "You  want to create a random song list that is {0}Mb.".format(size) 

You could also loop until you get an acceptable answer and cover yourself in case of error:

choice = 0 while choice not in range(1, len(sizes) + 1): # loop     try: # guard against error         choice = int(raw_input(...))     except ValueError: # couldn't make an int         print "Please enter a number"         choice = 0 size = sizes[choice - 1] # now definitely valid 

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

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

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" 

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?

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)

I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?

You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging '5' into the println method?

The JIT is smart enough to turn fields which don't change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

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.

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)  

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?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

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

I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:

<ul> {% for page in site.pages %}     {% if page.title != 'index' %}     <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li>     {% endif %} {% endfor %} </ul> 

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?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

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:

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 add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

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.

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

You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do

for (var i = myArray.length - 1; i >= 0; i--) {    console.log(eval(myArray[i])); }; 

More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.

var result = {}; for (var i = myArray.length - 1; i >= 0; i--) {     result[myArray[i]] = eval(myArray[i]);   }; 

I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

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

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

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.

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; 

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

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

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

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);     } } 

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

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.

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); 

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.

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.

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

In my case:

I had 4 configurations(+ DebugQa and ReleaseQa) Cocoapods is used as a dependency Manager

For Debug, I gathered on the device and in the simulator, and on qa only on the device.

It helped to set BuildActiveArchitecture to yes in PodsProject

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

Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

  1. First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)

  2. Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..

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

Simply update react-scripts to the latest version.

yarn add react-scripts@latest

OR IF USING NPM

npm install react-scripts@latest

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

Maven dependencies are failing with a 501 error

Using Ubuntu 16.04, java 1.8.0_201.

I un-installed old maven and installed Maven 3.6.3, still got this error that Maven dependencies are failing with a 501 error.

Realized it could be a truststore/keystore issue associated with requiring https. Found that you can now configure -Djavax options using a jvm.config file, see: https://maven.apache.org/configure.html.

As I am also using Tomcat I copied the keystore & truststore config from Tomcat (setenv.sh) to my jvm.config and then it worked!

There is also an option to pass the this config in 'export MAVEN_OPTS' (when using mvn generate) but although this stopped the 501 error it created another: it expected a pom file.

Creating a separate jvm.config file works perfectly, just put it in the root of your project.

Hopefully this helps someone, took me all day to figure it out!

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

In my case it was enough to add this part to the pom.xml file:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
        </plugins>
    </build>

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

1)

npm uninstall -g create-react-app

or

yarn global remove create-react-app

2)

There seems to be a bug where create-react-app isn't properly uninstalled and using one of the new commands lead to:

A template was not provided. This is likely because you're using an outdated version of create-react-app.

After uninstalling it with npm uninstall -g create-react-app, check whether you still have it "installed" with which create-react-app (Windows: where create-react-app) on your command line. If it returns something (e.g. /usr/local/bin/create-react-app), then do a rm -rf /usr/local/bin/create-react-app to delete manually.

3)

Then one of these ways:

npx create-react-app my-app
npm init react-app my-app
yarn create react-app my-app

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

To those would prefer to keep it simple, stupid; If you rather get rid of the notices instead of installing a helper or downgrading, simply disable the error in your settings.json by adding this:

"intelephense.diagnostics.undefinedTypes": false

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

This might be a problem because of having the older version of brew and installed byobu which require new dependency in order to solve this problem run the following command

brew update && brew upgrade
brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb

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

When you run npm update in the command prompt, when it is done it will recommend you type a new command called npm fund.

When you run npm fund it will list all the modules and packages you have installed that were created by companies or organizations that need money for their IT projects. You will see a list of webpages where you can send them money. So "funds" means "Angular packages you installed that could use some money from you as an option to help support their businesses".

It's basically a list of the modules you have that need contributions or donations of money to their projects and which list websites where you can enter a credit card to help pay for them.

SyntaxError: Cannot use import statement outside a module

If anyone is running into this issue with Typescript, the key to solving it for me was changing

    "target": "esnext",
    "module": "esnext",

to

    "target": "esnext",
    "module": "commonjs",

In my tsconfig.json. I was under the impression "esnext" was the "best", but that was just a mistake.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I hit this issue working with Server Sent Events. The problem was solved when I noticed that the domain name I used to initiate the connection included a trailing slash, e.g. https://foo.bar.bam/ failed with ERR_HTTP_PROTOCOL_ERROR while https://foo.bar.bam worked.

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

I'm also in a "trial and error" for that, but this answer from Google Chrome Labs' Github helped me a little. I defined it into my main file and it worked - well, for only one third-party domain. Still making tests, but I'm eager to update this answer with a better solution :)

EDIT: I'm using PHP 7.4 now, and this syntax is working good (Sept 2020):

$cookie_options = array(
  'expires' => time() + 60*60*24*30,
  'path' => '/',
  'domain' => '.domain.com', // leading dot for compatibility or use subdomain
  'secure' => true, // or false
  'httponly' => false, // or false
  'samesite' => 'None' // None || Lax || Strict
);

setcookie('cors-cookie', 'my-site-cookie', $cookie_options);

If you have PHP 7.2 or lower (as Robert's answered below):

setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

If your host is already updated to PHP 7.3, you can use (thanks to Mahn's comment):

setcookie('cookieName', 'cookieValue', [
  'expires' => time()+(7*24*3600,
  'path' => '/',
  'domain' => 'domain.com',
  'samesite' => 'None',
  'secure' => true,
  'httponly' => true
]);

Another thing you can try to check the cookies, is to enable the flag below, which—in their own words—"will add console warning messages for every single cookie potentially affected by this change":

chrome://flags/#cookie-deprecation-messages

See the whole code at: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md, they have the code for same-site-cookies too.

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

All mentioned comments above are great, sharing the path that worked with me for this Blacklist file that need to be edited:

"Your project name\node_modules\metro-bundler\src" File name "blacklist.js"

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

Use the following code to avoid that error

MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true});

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

I'm on Ubuntu 18.04. I fixed this problem by increasing the inotify max_user_watches using this command:

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches

Unable to allocate array with shape and data type

I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.

With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.

You can check which version you have by entering the interpreter. I, with a 64-bit version, now have: Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)], where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".

Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.

Sources :

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

How to prevent Google Colab from disconnecting?

GNU Colab lets you run a standard persistent desktop environment on top of a Colaboratory instance.

Indeed it contains a mechanism to not let machines die of idling.

Here's a video demonstration.

dotnet ef not found in .NET Core 3

I had the same problem. I resolved, uninstalling all de the versions in my pc and then reinstall dotnet.

"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.

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

If you use Arch Linux (distributions like Manjaro or Antegros) simply type:

sudo pacman -S tk

And all will work perfectly!

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

I resolved a similar issue in my getClass function like this:

import { ApiGateway } from './api-gateway.class';
import { AppSync } from './app-sync.class';
import { Cognito } from './cognito.class';

export type stackInstances = typeof ApiGateway | typeof  AppSync | typeof Cognito

export const classes = {
  ApiGateway,
  AppSync,
  Cognito
} as {
  [key: string]: stackInstances
};

export function getClass(name: string) {
  return classes[name];
}

Typing my classes const with my union type made typescript happy and it makes sense to me.

Is it possible to opt-out of dark mode on iOS 13?

I think I've found the solution. I initially pieced it together from UIUserInterfaceStyle - Information Property List and UIUserInterfaceStyle - UIKit, but have now found it actually documented at Choosing a specific interface style for your iOS app.

In your info.plist, set UIUserInterfaceStyle (User Interface Style) to 1 (UIUserInterfaceStyle.light).

EDIT: As per dorbeetle's answer, a more appropriate setting for UIUserInterfaceStyle may be Light.

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

You can do something like:

.background(Color.black)

around your view.

eg. from the default template (I am encompassing it around a Group):

    var body: some View {
        VStack {
          Text("Hello SwiftUI!")
        }
       .background(Color.black)
    }

To add some opacity to it, you can add the .opacity method as well:

.background(Color.black.opacity(0.5))

You can also make use of the inspect element of the view by CMD + click on the View and clicking Show SwiftUI Inspector > Background > Your Color

Inspect View

Inspect Detail View

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

I used withStyles instead of makeStyle

EX :

import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";

const useStyles = theme => ({
        root: {
           flexGrow: 1,
         },
  });

class App extends Component {
       render() {
                const { classes } = this.props;
                return(
                    <div className={classes.root}>
                       Test
                </div>
                )
          }
} 

export default withStyles(useStyles)(App)

Understanding esModuleInterop in tsconfig file

esModuleInterop generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:

//ts 
import React from 'react'
//js 
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));

__importDefault: If the module is not an es module then what is returned by require becomes the default. This means that if you use default import on a commonjs module, the whole module is actually the default.

__importStar is best described in this PR:

TypeScript treats a namespace import (i.e. import * as foo from "foo") as equivalent to const foo = require("foo"). Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.

Babel first requires in the module, and checks for a property named __esModule. If __esModule is set to true, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:

  1. All properties are plucked off of the require'd module and made available as named imports.
  2. The originally require'd module is made available as a default import.

So we get this:

// ts
import * as React from 'react'

// emitted js
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));

allowSyntheticDefaultImports is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react' will raise the error Module '".../node_modules/@types/react/index"' has no default export. if allowSyntheticDefaultImports is false.

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 got the same issue installing the npm package https://www.npmjs.com/package/webshot

NOTE: it was a known issue for that package as it depends on graceful-fs behind the scenes.

FIX:1. upgrade graceful-fs to 4.x or higher

fix:2. use webshot-node instead https://www.npmjs.com/package/webshot-node

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

Following this issue on GitHub, the official solution is to edit the imdb.py file. This fix worked well for me without the need to downgrade numpy. Find the imdb.py file at tensorflow/python/keras/datasets/imdb.py (full path for me was: C:\Anaconda\Lib\site-packages\tensorflow\python\keras\datasets\imdb.py - other installs will be different) and change line 85 as per the diff:

-  with np.load(path) as f:
+  with np.load(path, allow_pickle=True) as f:

The reason for the change is security to prevent the Python equivalent of an SQL injection in a pickled file. The change above will ONLY effect the imdb data and you therefore retain the security elsewhere (by not downgrading numpy).

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Module 'tensorflow' has no attribute 'contrib'

This issue might be helpful for you, it explains how to achieve TPUStrategy, a popular functionality of tf.contrib in TF<2.0.

So, in TF 1.X you could do the following:

resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.contrib.distribute.initialize_tpu_system(resolver)
strategy = tf.contrib.distribute.TPUStrategy(resolver)

And in TF>2.0, where tf.contrib is deprecated, you achieve the same by:

tf.config.experimental_connect_to_host('grpc://' + os.environ['COLAB_TPU_ADDR'])
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver) 

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

Just pass the function as the argument in the array of useEffect...

useEffect(() => {
   functionName()
}, [functionName])

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

Late answer, and there are many good answers already.

In case you want a simple script to check if the maximum file watches is big enough, and if not, increase the limit, here it is:

#!/usr/bin/env bash

let current_watches=`sysctl -n fs.inotify.max_user_watches`

if (( current_watches < 80000 ))
then
  echo "Current max_user_watches ${current_watches} is less than 80000."
else
  echo "Current max_user_watches ${current_watches} is already equal to or greater than 80000."
  exit 0
fi

if sudo sysctl -w fs.inotify.max_user_watches=80000 && sudo sysctl -p && echo fs.inotify.max_user_watches=80000 | sudo tee /etc/sysctl.d/10-user-watches.conf
then
  echo "max_user_watches changed to 80000."
else
  echo "Could not change max_user_watches."
  exit 1
fi

The script increases the limit to 80000, but feel free to set a limit that you want.

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

If you are on linux open the terminal from the App root directory and run

npm start

then open another terminal window and run:

react-native run-android

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

The imports have changed for core-js version 3.0.1 - for example

import 'core-js/es6/array'; and import 'core-js/es7/array';

can now be provided simply by the following

import 'core-js/es/array';

if you would prefer not to bring in the whole of core-js

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

In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).

setValue:

  • Initialize Model Structure in Constructor:

    this.newForm = this.formBuilder.group({  
       firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
       lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
    });
    
  • If you want to update all fields of form:

    this.newForm.setValue({
       firstName: 'abc',
       lastName: 'def'
    });
    
  • If you want to update specific field of form:

    this.newForm.controls.firstName.setValue('abc');
    

Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.

patchValue:

  • If you want to update some/ specific fields of form:

    this.newForm.patchValue({
       firstName: 'abc'
    });
    

Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.

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

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 only solution worked for me was:

  1. I opened a new tab in chrome
  2. I pasted : http://localhost:8888/?token=......
  3. then I went to my original notebook and I was able to save it

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();

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

There are two things to correct in config.xml So the right answer should be adding the xmls:android:

<widget id="com.my.awesomeapp" version="1.0.0" 
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:cdv="http://cordova.apache.org/ns/1.0">

plus editing the config to allow:

<platform name="android">
  <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
      <application android:usesCleartextTraffic="true" />
  </edit-config>
</platform>

If step 1 is avoided error: unbound prefix. will appear

Push method in React Hooks (useState)?

The same way you do it with "normal" state in React class components.

example:

function App() {
  const [state, setState] = useState([]);

  return (
    <div>
      <p>You clicked {state.join(" and ")}</p>
      //destructuring
      <button onClick={() => setState([...state, "again"])}>Click me</button>
      //old way
      <button onClick={() => setState(state.concat("again"))}>Click me</button>
    </div>
  );
}

How to Install pip for python 3.7 on Ubuntu 18?

When i use apt install python3-pip, i get a lot of packages need install, but i donot need them. So, i DO like this:

apt update
apt-get install python3-setuptools
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
rm -f get-pip.py

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');
          });

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

This might be a bug of the recent anaconda. What works for me:

step1: vim /anaconda/bin/activate, it shows:

 #!/bin/sh                                                                                
 _CONDA_ROOT="/anaconda"
 # Copyright (C) 2012 Anaconda, Inc
 # SPDX-License-Identifier: BSD-3-Clause
 \. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
 conda activate "$@"

step2: comment out the last line: # conda activate "$@"

Gradle: Could not determine java version from '11.0.2'

To put long answer short, upgrade your gradlew using the system gradle tool. Note that the below upgrade works even if your system gradle version is < 5.

gradle wrapper --gradle-version=5.1.1

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

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

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>

React Hooks useState() with Object

Initially I used object in useState, but then I moved to useReducer hook for complex cases. I felt a performance improvement when I refactored the code.

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

useReducer React docs

I already implemented such hook for my own use:

/**
 * Same as useObjectState but uses useReducer instead of useState
 *  (better performance for complex cases)
 * @param {*} PropsWithDefaultValues object with all needed props 
 * and their initial value
 * @returns [state, setProp] state - the state object, setProp - dispatch 
 * changes one (given prop name & prop value) or multiple props (given an 
 * object { prop: value, ...}) in object state
 */
export function useObjectReducer(PropsWithDefaultValues) {
  const [state, dispatch] = useReducer(reducer, PropsWithDefaultValues);

  //newFieldsVal={[field_name]: [field_value], ...}
  function reducer(state, newFieldsVal) {
    return { ...state, ...newFieldsVal };
  }

  return [
    state,
    (newFieldsVal, newVal) => {
      if (typeof newVal !== "undefined") {
        const tmp = {};
        tmp[newFieldsVal] = newVal;
        dispatch(tmp);
      } else {
        dispatch(newFieldsVal);
      }
    },
  ];
}

more related hooks.

Error: Java: invalid target release: 11 - IntelliJ IDEA

I Could say I had similar issue. My case: I switched from new version to old version of the project in workspace, try to run single junit which require recompil, recompilation error was thrown with invalid target.

From Projects settings (F4) in IntelliJ everything was looking good and java was set to 1.7. But when I try recompile from IDE error was thrown because of wrong target level. After checking I found that in one of the iml file language was set to JDK_11. After manual change to JDK_1_7 everything back to normal.

Worth to also manual check lang level in *iml files created by IDE.

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

This errors happens in VSCode with Python 3.7.3 but works fine in IDLE editor in Windows 10 with Python 3.7.0.

How to setup virtual environment for Python in VS Code?

In vscode select folder and create WS and it will work fine

useState set method not reflecting change immediately

useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.

object and array spread or rest will not work inside useEffect.

React.useEffect(() => {
    console.log("effect");
    (async () => {
        try {
            let result = await fetch("/query/countries");
            const res = await result.json();
            let result1 = await fetch("/query/projects");
            const res1 = await result1.json();
            let result11 = await fetch("/query/regions");
            const res11 = await result11.json();
            setData({
                countries: res,
                projects: res1,
                regions: res11
            });
        } catch {}
    })(data)
}, [setData])
# or use this
useEffect(() => {
    (async () => {
        try {
            await Promise.all([
                fetch("/query/countries").then((response) => response.json()),
                fetch("/query/projects").then((response) => response.json()),
                fetch("/query/regions").then((response) => response.json())
            ]).then(([country, project, region]) => {
                // console.log(country, project, region);
                setData({
                    countries: country,
                    projects: project,
                    regions: region
                });
            })
        } catch {
            console.log("data fetch error")
        }
    })()
}, [setData]);

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Pylint "unresolved import" error in Visual Studio Code

This works for me:

Open the command palette (Ctrl + Shift + P) and choose "Python: Select Interpreter".

Doing this, you set the Python interpreter in Visual Studio Code.

React hooks useState Array

To expand on Ryan's answer:

Whenever setStateValues is called, React re-renders your component, which means that the function body of the StateSelector component function gets re-executed.

React docs:

setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

Essentially, you're setting state with:

setStateValues(allowedState);

causing a re-render, which then causes the function to execute, and so on. Hence, the loop issue.

To illustrate the point, if you set a timeout as like:

  setTimeout(
    () => setStateValues(allowedState),
    1000
  )

Which ends the 'too many re-renders' issue.

In your case, you're dealing with a side-effect, which is handled with UseEffectin your component functions. You can read more about it here.

HTTP Error 500.30 - ANCM In-Process Start Failure

Make sure that your *.deps.js json file copied correctly to the deployed location

Can I set state inside a useEffect hook

? 1. Can I set state inside a useEffect hook?

In principle, you can set state freely where you need it - including inside useEffect and even during rendering. Just make sure to avoid infinite loops by settting Hook deps properly and/or state conditionally.


? 2. Lets say I have some state that is dependent on some other state. Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?

You just described the classic use case for useReducer:

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. (React docs)

When setting a state variable depends on the current value of another state variable, you might want to try replacing them both with useReducer. [...] When you find yourself writing setSomething(something => ...), it’s a good time to consider using a reducer instead. (Dan Abramov, Overreacted blog)

_x000D_
_x000D_
let MyComponent = () => {_x000D_
  let [state, dispatch] = useReducer(reducer, { a: 1, b: 2 });_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("Some effect with B");_x000D_
  }, [state.b]);_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>A: {state.a}, B: {state.b}</p>_x000D_
      <button onClick={() => dispatch({ type: "SET_A", payload: 5 })}>_x000D_
        Set A to 5 and Check B_x000D_
      </button>_x000D_
      <button onClick={() => dispatch({ type: "INCREMENT_B" })}>_x000D_
        Increment B_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
// B depends on A. If B >= A, then reset B to 1._x000D_
function reducer(state, { type, payload }) {_x000D_
  const someCondition = state.b >= state.a;_x000D_
_x000D_
  if (type === "SET_A")_x000D_
    return someCondition ? { a: payload, b: 1 } : { ...state, a: payload };_x000D_
  else if (type === "INCREMENT_B") return { ...state, b: state.b + 1 };_x000D_
  return state;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect } = React</script>
_x000D_
_x000D_
_x000D_


? 3. Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render?

useEffect always runs after the render is committed and DOM changes are applied. The first effect fires, changes b and causes a re-render. After this render has completed, second effect will run due to b changes.

_x000D_
_x000D_
let MyComponent = props => {_x000D_
  console.log("render");_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
_x000D_
  let isFirstRender = useRef(true);_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect a, value:", a);_x000D_
    if (isFirstRender.current) isFirstRender.current = false;_x000D_
    else setB(3);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect a, value:", a);_x000D_
    };_x000D_
  }, [a]);_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
    };_x000D_
  }, [b]);_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>a: {a}, b: {b}</p>_x000D_
      <button_x000D_
        onClick={() => {_x000D_
          console.log("Clicked!");_x000D_
          setA(5);_x000D_
        }}_x000D_
      >_x000D_
        click me_x000D_
      </button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_


? 4. Are there any performance downsides to structuring code like this?

Yes. By wrapping the state change of b in a separate useEffect for a, the browser has an additional layout/paint phase - these effects are potentially visible for the user. If there is no way you want give useReducer a try, you could change b state together with a directly:

_x000D_
_x000D_
let MyComponent = () => {_x000D_
  console.log("render");_x000D_
  let [a, setA] = useState(1);_x000D_
  let [b, setB] = useState(2);_x000D_
_x000D_
  useEffect(() => {_x000D_
    console.log("useEffect b, value:", b);_x000D_
    return () => {_x000D_
      console.log("unmount useEffect b, value:", b);_x000D_
    };_x000D_
  }, [b]);_x000D_
_x000D_
  const handleClick = () => {_x000D_
    console.log("Clicked!");_x000D_
    setA(5);_x000D_
    b >= 5 ? setB(1) : setB(b + 1);_x000D_
  };_x000D_
_x000D_
  return (_x000D_
    <div>_x000D_
      <p>_x000D_
        a: {a}, b: {b}_x000D_
      </p>_x000D_
      <button onClick={handleClick}>click me</button>_x000D_
    </div>_x000D_
  );_x000D_
};_x000D_
_x000D_
ReactDOM.render(<MyComponent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
_x000D_
_x000D_

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

FlutterError: Unable to load asset

Don't struggle to add the path to each image asset, instead just specify the path to your images directory.
just make sure you use proper indentations as the pubspec.yaml is indent sensitive.

flutter:

  uses-material-design: true
  assets:
    - images/

and you can simply access each image as

  new Image.asset('images/pizza1.png',width:300,height:100)

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

To fix this install the specific typescript version 3.1.6

npm i [email protected] --save-dev --save-exact

internal/modules/cjs/loader.js:582 throw err

same happen to me i just resolved by deleting "dist" file and re run the app.

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

How to compare oldValues and newValues on React Hooks useEffect?

Incase anybody is looking for a TypeScript version of usePrevious:

In a .tsx module:

import { useEffect, useRef } from "react";

const usePrevious = <T extends unknown>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Or in a .ts module:

import { useEffect, useRef } from "react";

const usePrevious = <T>(value: T): T | undefined => {
  const ref = useRef<T>();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

Receiving "Attempted import error:" in react app

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.

import React, { Component } from "react";

export class Counter extends Component { // type this  
export default Counter; // this is eliminated  

What is the meaning of "Failed building wheel for X" in pip install?

It might be helpful to address this question from a package deployment perspective.

There are many tutorials out there that explain how to publish a package to PyPi. Below are a couple I have used;

medium
real python

My experience is that most of these tutorials only have you use the .tar of the source, not a wheel. Thus, when installing packages created using these tutorials, I've received the "Failed to build wheel" error.

I later found the link on PyPi to the Python Software Foundation's docs PSF Docs. I discovered that their setup and build process is slightly different, and does indeed included building a wheel file.

After using the officially documented method, I no longer received the error when installing my packages.

So, the error might simply be a matter of how the developer packaged and deployed the project. None of us were born knowing how to use PyPi, and if they happened upon the wrong tutorial -- well, you can fill in the blanks.

I'm sure that is not the only reason for the error, but I'm willing to bet that is a major reason for it.

What is useState() in React?

Thanks loelsonk, i did so

_x000D_
_x000D_
const [dataAction, setDataAction] = useState({name: '', description: ''});_x000D_
_x000D_
    const _handleChangeName = (data) => {_x000D_
        if(data.name)_x000D_
            setDataAction( prevState  => ({ ...prevState,   name : data.name }));_x000D_
        if(data.description)_x000D_
            setDataAction( prevState  => ({ ...prevState,   description : data.description }));_x000D_
    };_x000D_
    _x000D_
    ....return (_x000D_
    _x000D_
          <input onChange={(event) => _handleChangeName({name: event.target.value})}/>_x000D_
          <input onChange={(event) => _handleChangeName({description: event.target.value})}/>_x000D_
    )
_x000D_
_x000D_
_x000D_

Set the space between Elements in Row Flutter

Just add "Container(width: 5, color: Colors.transparent)," between elements

new Container(
      alignment: FractionalOffset.center,
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new FlatButton(
            child: new Text('Don\'t have an account?', style: new TextStyle(color: Color(0xFF2E3233))),
          ),
            Container(width: 5, color: Colors.transparent),
          new FlatButton(
            child: new Text('Register.', style: new TextStyle(color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),),
            onPressed: moveToRegister,
          )
        ],
      ),
    ),  

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.

More information on the answer can be found here

Linked Info Summary

Enable TLS 1.2 at the system (SCHANNEL) level:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

(equivalent keys are probably also available for other TLS versions)

Tell .NET Framework to use the system TLS versions:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001

This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.

How to call loading function with React useEffect only once

TL;DR

useEffect(yourCallback, []) - will trigger the callback only after the first render.

Detailed explanation

useEffect runs by default after every render of the component (thus causing an effect).

When placing useEffect in your component you tell React you want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.

If you pass only a callback - the callback will run after each render.

If passing a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. for example when placing useEffect(() => console.log('hello'), [someVar, someOtherVar]) - the callback will run after the first render and after any render that one of someVar or someOtherVar are changed.

By passing the second argument an empty array, React will compare after each render the array and will see nothing was changed, thus calling the callback only after the first render.

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

For RobotFramework

I solved it! using --no-sandbox

${chrome_options}=  Evaluate  sys.modules['selenium.webdriver'].ChromeOptions()  sys, selenium.webdriver
Call Method    ${chrome_options}    add_argument    test-type
Call Method    ${chrome_options}    add_argument    --disable-extensions
Call Method    ${chrome_options}    add_argument    --headless
Call Method    ${chrome_options}    add_argument    --disable-gpu
Call Method    ${chrome_options}    add_argument    --no-sandbox
Create Webdriver    Chrome    chrome_options=${chrome_options}

Instead of

Open Browser    about:blank    headlesschrome
Open Browser    about:blank    chrome

Could not install packages due to an EnvironmentError: [Errno 13]

try this command line below for MacOS to check user's permission.

$ sudo python -m pip install --user --upgrade pip

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


Solutions

  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. Use shrinkWrap, if your ListView isn't too big.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

Space between Column's children in Flutter

You can also use a helper function to add spacing after each child.

List<Widget> childrenWithSpacing({
  @required List<Widget> children,
  double spacing = 8,
}) {
  final space = Container(width: spacing, height: spacing);
  return children.expand((widget) => [widget, space]).toList();
}

So then, the returned list may be used as a children of a column

Column(
  children: childrenWithSpacing(
    spacing: 14,
    children: [
      Text('This becomes a text with an adjacent spacing'),
      if (true == true) Text('Also, makes it easy to add conditional widgets'),
    ],
  ),
);

I'm not sure though if it's wrong or have a performance penalty to run the children through a helper function for the same goal?

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

OpenCV !_src.empty() in function 'cvtColor' error

If anyone is experiencing this same problem when reading a frame from a webcam:

Verify if your webcam is being used on another task and close it. This wil solve the problem.

I spent some time with this error when I realized my camera was online in a google hangouts group. Also, Make sure your webcam drivers are up to date

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

I reached the point that I set, up to max_iter=1200000 on my LinearSVC classifier, but still the "ConvergenceWarning" was still present. I fix the issue by just setting dual=False and leaving max_iter to its default.

With LogisticRegression(solver='lbfgs') classifier, you should increase max_iter. Mine have reached max_iter=7600 before the "ConvergenceWarning" disappears when training with large dataset's features.

How do I install Java on Mac OSX allowing version switching?

To stay with a specific major release, activate the AdoptOpenJDK tap with brew tap and then install the desired version with brew cask install:

$ brew tap AdoptOpenJDK/openjdk
$ brew cask install <version>

To install AdoptOpenJDK 14 with HotSpot, run:

$ brew tap AdoptOpenJDK/openjdk
$ brew cask install adoptopenjdk14

How to install OpenJDK 11 on Windows?

You can use Amazon Corretto. It is free to use multiplatform, production-ready distribution of the OpenJDK. It comes with long-term support that will include performance enhancements and security fixes. Check the installation instructions here.

You can also check Zulu from Azul.

One more thing I like to highlight here is both Amazon Corretto and Zulu are TCK Compliant. You can see the OpenJDK builds comparison here and here.

Can't compile C program on a Mac after upgrade to Mojave

After trying every answer I could find here and online, I was still getting errors for some missing headers. When trying to compile pyRFR, I was getting errors about stdexcept not being found, which apparently was not installed in /usr/include with the other headers. However, I found where it was hiding in Mojave and added this to the end of my ~/.bash_profile file:

export CPATH=/Library/Developer/CommandLineTools/usr/include/c++/v1

Having done that, I can now compile pyRFR and other C/C++ programs. According to echo | gcc -E -Wp,-v -, gcc was looking in the old location for these headers (without the /c++/v1), but not the new location, so adding that to CFLAGS fixed it.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

In my case, it was caused from gms services 4.3.0. So i had to change it to:

com.google.gms:google-services:4.2.0

I have found this by running:

gradlew sync -Pandroid.debug.obsoleteApi=true

in terminal. Go to view -> tool windows -> Terminal in Android Studio.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

Quick summary, you can do either:

  1. Include the JavaFX modules via --module-path and --add-modules like in José's answer.

    OR

  2. Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java file).


This answer is a supplement to Jose's answer.

The situation is this:

  1. You are using a recent Java version, e.g. 13.
  2. You have a JavaFX application as a Maven project.
  3. In your Maven project you have the JavaFX plugin configured and JavaFX dependencies setup as per Jose's answer.
  4. You go to the source code of your main class which extends Application, you right-click on it and try to run it.
  5. You get an IllegalAccessError involving an "unnamed module" when trying to launch the app.

Excerpt for a stack trace generating an IllegalAccessError when trying to run a JavaFX app from Intellij Idea:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main

OK, now you are kind of stuck and have no clue what is going on.

What has actually happened is this:

  1. Maven has successfully downloaded the JavaFX dependencies for your application, so you don't need to separately download the dependencies or install a JavaFX SDK or module distribution or anything like that.
  2. Idea has successfully imported the modules as dependencies to your project, so everything compiles OK and all of the code completion and everything works fine.

So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).

This is where some of the other answers to this question, which reference module-info.java, come into the picture.

So let's take a crash course in Java modules:

The key part is this:

4.9. Opens

If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.

But remember, this will open the package up to the entire world, so make sure that is what you want:

module my.module { opens com.my.package; }

So, perhaps you don't want to open your package to the entire world, then you can do:

4.10. Opens … To

Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:

module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }

So, you end up creating a src/main/java/module-info.java class which looks like this:

module org.jewelsea.demo.javafx.springboot {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}

Where, org.jewelsea.demo.javafx.springboot is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics and javafx.fxml to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError generated by JavaFX's use of reflection will no longer occur.

But what if you don't want to create a module-info.java file

If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:

  1. Went to the Maven window in the side of the IDE.
  2. Chose the javafx maven plugin target javafx.run.
  3. Right-clicked on that and chose either Run Maven Build or Debug....

Then the app will run without the module-info.java file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java file, though I don't know how this is accomplished.

To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run Maven target and choose the option to Create Run/Debug Configuration for the target. Then you can just choose Run from the top toolbar to execute the Maven target.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I had a similar error while I was creating a custom modal.

const CustomModal = (visible, modalText, modalHeader) => {}

Problem was that I didn't wrap my values to curly brackets like this.

const CustomModal = ({visible, modalText, modalHeader}) => {}

If you have multiple values to pass to the component, you should use curly brackets around it.

Xcode 10: A valid provisioning profile for this executable was not found

I did the following :

  1. Disconnected the device where the app was not getting installed
  2. Connected a different device < It installed on this second device
  3. After some time connected the first device and it worked!

This is very weird but it worked for me, might work for others and save the frustration.

What is "not assignable to parameter of type never" error in typescript?

This seems to be a recent regression or some strange behavior in typescript. If you have the code:

const result = []

Usually it would be treated as if you wrote:

const result:any[] = []

however, if you have both noImplicitAny FALSE, AND strictNullChecks TRUE in your tsconfig, it is treated as:

const result:never[] = []

This behavior defies all logic, IMHO. Turning on null checks changes the entry types of an array?? And then turning on noImplicitAny actually restores the use of any without any warnings??

When you truly have an array of any, you shouldn't need to indicate it with extra code.

How to reload current page?

I found a better way than reload the page. instead i will reload the data that just got updated. this way faster n better

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

The answer by Agalin is already great and I just want to explain it in a step by step format for a novice like myself:

  • find your Python version by python --version mine is 3.7.3 for example
  • the easiest way to check either you have 64 or 32 Python just open it in the terminal:

  • find the appropriate .whl file from here, for example mine is PyAudio-0.2.11-cp37-cp37m-win_amd64.whl, and download it.
  • go to the folder where it is downloaded for example cd C:\Users\foobar\Downloads
  • install the .whl file with pip for example in my case:
pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

How to open a link in new tab using angular?

Use window.open(). It's pretty straightforward !

In your component.html file-

<a (click)="goToLink("www.example.com")">page link</a>

In your component.ts file-

goToLink(url: string){
    window.open(url, "_blank");
}

Support for the experimental syntax 'classProperties' isn't currently enabled

I faced the same issue while trying to transpile some jsx with babel. Below is the solution that worked for me. You can add the following json to your .babelrc

{
  "presets": [
    [
      "@babel/preset-react",
      { "targets": { "browsers": ["last 3 versions", "safari >= 6"] } }
    ]
  ],
  "plugins": [["@babel/plugin-proposal-class-properties"]]
}

System has not been booted with systemd as init system (PID 1). Can't operate

You can simply run sudo service docker start which will start running your docker server. You can check if you have the docker server by running service --status-all, you should see docker listed.

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I solved the problem by changing the StartupType of the ssh-agent to Manual via Set-Service ssh-agent -StartupType Manual.

Then I was able to start the service via Start-Service ssh-agent or just ssh-agent.exe.

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

Can I use library that used android support with Androidx projects.

Add the lines in the gradle.properties file

android.useAndroidX=true
android.enableJetifier=true

enter image description here enter image description here Refer also https://developer.android.com/jetpack/androidx

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink], then it should be assigned a name of the property the value of which will be the route it should navigate the user to.

So to fix your issue, replace this routerLink="['/about']" with routerLink="/about" in your HTML.

There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:

<nav class="main-nav>
  <ul 
    class="main-nav__list" 
    ng-sticky 
    addClass="main-sticky-link" 
    [ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
    <li class="main-nav__item" routerLinkActive="active">
      <a class="main-nav__link" routerLink="/">Home</a>
    </li>
    <li class="main-nav__item" routerLinkActive="active"> 
      <a class="main-nav__link" routerLink="/about">About us</a>
    </li>
  </ul>
</nav>

It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>, either in your template provided above or in a parent component.

There's another issue with your AppRoutingModule. You need to export the RouterModule from there so that it is available to your AppModule when it imports it. To fix that, export it from your AppRoutingModule by adding it to the exports array.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
  { path: 'about', component: AboutComponent },
  { path: 'what', component: WhatwedoComponent },
  { path: 'contacts', component: FooterComponent },
  { path: 'projects', component: ProjectsComponent},
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forRoot(routes),
  ],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule { }

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

Iterating over arrays in Python 3

You can use

    nditer

Here I calculated no. of positive and negative coefficients in a logistic regression:

b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
    if i>0:
    pos_coef=pos_coef+1
    else:
    neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))

Output:

no. of positive coefficients is : 85035
no. of negative coefficients is : 36199

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

Oh my. There are so many bad answers here. Well meaning but misleading. I am usually fine with dealing with permissions on Mac/Linux. Windows is new to me these days. This is the problem I had.

  1. Create a virtualenv - ok
  2. activate my virtualenv - failed. Needs Scope to run powershell. Windows is helpful and tell you exactly the command you need to run to allow .ps to run. Sort of like chmod but with execution scope which I think is good.
  3. Now if you are past the above and install a few packages then it's fine. Until you suddenly cant. Then you get this permission error.
  4. Something you or another process did set the permission on the folder where pip installs packages. i.e. ...site-packages/ In my case I suspect it's OneDrive or some permission inheritence.

The ideal way forward is to check permissions. This is hard but you are a Python developer are you not! First check your own user.

  1. whoami e.g. mycomputer\vangel
  2. Get-Acl <path which is an issue>
  3. on the Python install folder or your virtualenv right click and go to Security Tab. Click advanced and review permissions. I removed all inherited permissions and other users etc and added my whoami user explicity with full permissions. then applied to all objects.

Dont do these without verifying the below steps. Read the message carefully.

By no means it is the solution for all permissions issues that may affect you. I can only provide guidance on how to troubleshoot and hopefully you resolve.

setting --user flag is not necessary anywhere, if it works good for you. But you still do not know what went wrong.

More steps: Try removing a package and installing it. pip uninstall requests pip install requests This works, yet I get permission issue for a specific package.

Turns out, Windows gives permission error when the file is locked by a process. Python reports it as [Winerror 5] and I could not easily find that documentation reference anyway. lets test this theory.

I find the exact file that gets permission error. Hit delete. Sure enough Windows window prompt that its open in python Of course it is.

I hit end task on all python It has worked since 1996. But I waited a few seconds just in case some process is launching python. Checked Task manager all good.

Having failed 20 times in getting pip to install the specific azureml package I was feeling pretty sure this resolved it.

I ran my pip install and it installed perfectly fine.

Moral of the story: Understand what you are doing before copy pasting from Stackoverflow. All the best.

p.s. Please stop installing Python or its packages as administrator. We are past that since 2006

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

A simple way is set android:usesCleartextTraffic="true" on you AndroidManifest.xml

android:usesCleartextTraffic="true"

Your AndroidManifest.xml look like

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.dww.drmanar">
   <application
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:usesCleartextTraffic="true"
       android:theme="@style/AppTheme"
       tools:targetApi="m">
       <activity
            android:name=".activity.SplashActivity"
            android:theme="@style/FullscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
       </activity>
    </application>
</manifest>

I hope this will help you.

How do I install opencv using pip?

You can install opencv in a simple way $ pip install opencv-python If u are having errors, you can do this $ pip install opencv-python-headless

Android Material and appcompat Manifest merger failed

As of Android P, the support libraries have been moved to AndroidX

Please do a refactor for your libs from this page.

https://developer.android.com/topic/libraries/support-library/refactor

How to scroll page in flutter

Thanks guys for help. From your suggestions i reached a solution like this.

new LayoutBuilder(
        builder:
            (BuildContext context, BoxConstraints viewportConstraints) {
          return SingleChildScrollView(
            child: ConstrainedBox(
              constraints:
                  BoxConstraints(minHeight: viewportConstraints.maxHeight),
              child: Column(children: [
             // remaining stuffs
              ]),
            ),
          );
        },
      )

Find the smallest positive integer that does not occur in a given sequence

My Java solution got 100%. I feel this is simple and the complexity is O(n).

public int solution(int[] A) {
    Integer s = 1;
    List<Integer> list = new ArrayList<>();

    for (int i : A) {
        if (i>0) {
            list.add(i);
        }
    }

    Collections.sort(list);

    for (int i : list) {
        if (s < i) {
            return s;
        }
        s = i + 1;
    }

    return s;
}

Let me know if we can improve this more.

Angular: How to download a file from HttpClient?

I ended up here when searching for ”rxjs download file using post”.

This was my final product. It uses the file name and type given in the server response.

import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

downloadPost(url: string, data: any) {
    return ajax({
        url: url,
        method: 'POST',
        responseType: 'blob',
        body: data,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'text/plain, */*',
            'Cache-Control': 'no-cache',
        }
    }).pipe(
        map(handleDownloadSuccess),
    );
}


handleDownloadSuccess(response: AjaxResponse) {
    const downloadLink = document.createElement('a');
    downloadLink.href = window.URL.createObjectURL(response.response);

    const disposition = response.xhr.getResponseHeader('Content-Disposition');
    if (disposition) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            const filename = matches[1].replace(/['"]/g, '');
            downloadLink.setAttribute('download', filename);
        }
    }

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

Under which circumstances textAlign property works in Flutter?

Set alignment: Alignment.centerRight in Container:

Container(
    alignment: Alignment.centerRight,
    child:Text(
       "Hello",
    ),
)

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Set distributionUrl path in gradle-wrapper-properties files as :

distributionUrl=https://services.gradle.org/distributions/gradle-4.10.2-all.zip

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

Best way to "push" into C# array

I don't think there is another way other than assigning value to that particular index of that array.

Google Recaptcha v3 example demo

I thought a fully-functioning reCaptcha v3 example demo in PHP, using a Bootstrap 4 form, might be useful to some.

Reference the shown dependencies, swap in your email address and keys (create your own keys here), and the form is ready to test and use. I made code comments to better clarify the logic and also included commented-out console log and print_r lines to quickly enable viewing the validation token and data generated from Google.

The included jQuery function is optional, though it does create a much better user prompt experience in this demo.


PHP file (mail.php):

Add secret key (2 places) and email address where noted.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  # BEGIN Setting reCaptcha v3 validation data
  $url = "https://www.google.com/recaptcha/api/siteverify";
  $data = [
    'secret' => "your-secret-key-here",
    'response' => $_POST['token'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
  ];

  $options = array(
    'http' => array(
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    )
    );
  
  # Creates and returns stream context with options supplied in options preset 
  $context  = stream_context_create($options);
  # file_get_contents() is the preferred way to read the contents of a file into a string
  $response = file_get_contents($url, false, $context);
  # Takes a JSON encoded string and converts it into a PHP variable
  $res = json_decode($response, true);
  # END setting reCaptcha v3 validation data
   
    // print_r($response); 
# Post form OR output alert and bypass post if false. NOTE: score conditional is optional
# since the successful score default is set at >= 0.5 by Google. Some developers want to
# be able to control score result conditions, so I included that in this example.

  if ($res['success'] == true && $res['score'] >= 0.5) {
 
    # Recipient email
    $mail_to = "[email protected]";
    
    # Sender form data
    $subject = trim($_POST["subject"]);
    $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST["phone"]);
    $message = trim($_POST["message"]);
    
    if (empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
      # Set a 400 (bad request) response code and exit
      http_response_code(400);
      echo '<p class="alert-warning">Please complete the form and try again.</p>';
      exit;
    }

    # Mail content
    $content = "Name: $name\n";
    $content .= "Email: $email\n\n";
    $content .= "Phone: $phone\n";
    $content .= "Message:\n$message\n";

    # Email headers
    $headers = "From: $name <$email>";

    # Send the email
    $success = mail($mail_to, $subject, $content, $headers);
    
    if ($success) {
      # Set a 200 (okay) response code
      http_response_code(200);
      echo '<p class="alert alert-success">Thank You! Your message has been successfully sent.</p>';
    } else {
      # Set a 500 (internal server error) response code
      http_response_code(500);
      echo '<p class="alert alert-warning">Something went wrong, your message could not be sent.</p>';
    }   

  } else {

    echo '<div class="alert alert-danger">
        Error! The security token has expired or you are a bot.
       </div>';
  }  

} else {
  # Not a POST request, set a 403 (forbidden) response code
  http_response_code(403);
  echo '<p class="alert-warning">There was a problem with your submission, please try again.</p>';
} ?>

HTML <head>

Bootstrap CSS dependency and reCaptcha client-side validation Place between <head> tags - paste your own site-key where noted.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://www.google.com/recaptcha/api.js?render=your-site-key-here"></script>

HTML <body>

Place between <body> tags.

<!-- contact form demo container -->
<section style="margin: 50px 20px;">
  <div style="max-width: 768px; margin: auto;">
    
    <!-- contact form -->
    <div class="card">
      <h2 class="card-header">Contact Form</h2>
      <div class="card-body">
        <form class="contact_form" method="post" action="mail.php">

          <!-- form fields -->
          <div class="row">
            <div class="col-md-6 form-group">
              <input name="name" type="text" class="form-control" placeholder="Name" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="email" type="email" class="form-control" placeholder="Email" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="phone" type="text" class="form-control" placeholder="Phone" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="subject" type="text" class="form-control" placeholder="Subject" required>
            </div>
            <div class="col-12 form-group">
              <textarea name="message" class="form-control" rows="5" placeholder="Message" required></textarea>
            </div>

            <!-- form message prompt -->
            <div class="row">
              <div class="col-12">
                <div class="contact_msg" style="display: none">
                  <p>Your message was sent.</p>
                </div>
              </div>
            </div>

            <div class="col-12">
              <input type="submit" value="Submit Form" class="btn btn-success" name="post">
            </div>

            <!-- hidden reCaptcha token input -->
            <input type="hidden" id="token" name="token">
          </div>

        </form>
      </div>
    </div>

  </div>
</section>
<script>
  grecaptcha.ready(function() {
    grecaptcha.execute('your-site-key-here', {action: 'homepage'}).then(function(token) {
       // console.log(token);
       document.getElementById("token").value = token;
    });
    // refresh token every minute to prevent expiration
    setInterval(function(){
      grecaptcha.execute('your-site-key-here', {action: 'homepage'}).then(function(token) {
        console.log( 'refreshed token:', token );
        document.getElementById("token").value = token;
      });
    }, 60000);

  });
</script>

<!-- References for the optional jQuery function to enhance end-user prompts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="form.js"></script>

Optional jQuery function for enhanced UX (form.js):

(function ($) {
'use strict';

var form = $('.contact_form'),
  message = $('.contact_msg'),
  form_data;

// Success function
function done_func(response) {
  message.fadeIn()
  message.html(response);
  setTimeout(function () {
    message.fadeOut();
  }, 10000);
  form.find('input:not([type="submit"]), textarea').val('');
}

// fail function
function fail_func(data) {
  message.fadeIn()
  message.html(data.responseText);
  setTimeout(function () {
    message.fadeOut();
  }, 10000);
}

form.submit(function (e) {
  e.preventDefault();
  form_data = $(this).serialize();
  $.ajax({
    type: 'POST',
    url: form.attr('action'),
    data: form_data
  })
  .done(done_func)
  .fail(fail_func);
}); })(jQuery);

Creating a list of objects in Python

If I understand correctly your question, you ask a way to execute a deep copy of an object. What about using copy.deepcopy?

import copy

x = SimpleClass()

for count in range(0,4):
  y = copy.deepcopy(x)
  (...)
  y.attr1= '*Bob* '* count

A deepcopy is a recursive copy of the entire object. For more reference, you can have a look at the python documentation: https://docs.python.org/2/library/copy.html

Getting cursor position in Python

Use pygame

import pygame

mouse_pos = pygame.mouse.get_pos()

This returns the x and y position of the mouse.

See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos

Single controller with multiple GET methods in ASP.NET Web API

With the newer Web Api 2 it has become easier to have multiple get methods.

If the parameter passed to the GET methods are different enough for the attribute routing system to distinguish their types as is the case with ints and Guids you can specify the expected type in the [Route...] attribute

For example -

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{

    // GET api/values/7
    [Route("{id:int}")]
    public string Get(int id)
    {
       return $"You entered an int - {id}";
    }

    // GET api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D
    [Route("{id:Guid}")]
    public string Get(Guid id)
    {
       return $"You entered a GUID - {id}";
    }
} 

For more details about this approach, see here http://nodogmablog.bryanhogan.net/2017/02/web-api-2-controller-with-multiple-get-methods-part-2/

Another options is to give the GET methods different routes.

    [RoutePrefix("api/values")]
    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "simple get";
        }

        [Route("geta")]
        public string GetA()
        {
            return "A";
        }

        [Route("getb")]
        public string GetB()
        {
            return "B";
        }
   }

See here for more details - http://nodogmablog.bryanhogan.net/2016/10/web-api-2-controller-with-multiple-get-methods/

How do I dynamically assign properties to an object in TypeScript?

The best practice is use safe typing, I recommend you:

interface customObject extends MyObject {
   newProp: string;
   newProp2: number;
}

Swift error : signal SIGABRT how to solve it

In my case there was no log whatsoever.

My mistake was to push a view controller in a navigation stack that was already part of the navigation stack.

What is the difference between __str__ and __repr__?

From an (An Unofficial) Python Reference Wiki (archive copy) by effbot:

__str__ "computes the "informal" string representation of an object. This differs from __repr__ in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead."

How to disable an Android button?

In Java, once you have the reference of the button:

Button button = (Button) findviewById(R.id.button);

To enable/disable the button, you can use either:

button.setEnabled(false);
button.setEnabled(true);

Or:

button.setClickable(false);
button.setClickable(true);

Since you want to disable the button from the beginning, you can use button.setEnabled(false); in the onCreate method. Otherwise, from XML, you can directly use:

android:clickable = "false"

So:

<Button
        android:id="@+id/button"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/button_text"
        android:clickable = "false" />

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

How can I test that a variable is more than eight characters in PowerShell?

Use the length property of the [String] type:

if ($dbUserName.length -gt 8) {
    Write-Output "Please enter more than 8 characters."
    $dbUserName = Read-Host "Re-enter database username"
}

Please note that you have to use -gt instead of > in your if condition. PowerShell uses the following comparison operators to compare values and test conditions:

  • -eq = equals
  • -ne = not equals
  • -lt = less than
  • -gt = greater than
  • -le = less than or equals
  • -ge = greater than or equals

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

mysql query result in php variable

There are a couple of mysql functions you need to look into.

  • mysql_query("query string here") : returns a resource
  • mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:

    while ($row = mysql_fetch_array($query)){
        print_r $row;
    }

    Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.

Links:

In your case,

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
    die("BAD!");
}
if (mysql_num_rows($result)==1){
    $row = mysql_fetch_array($result);
    echo "user Id: " . $row['userid'];
}
else{
    echo "not found!";
}

How to do a num_rows() on COUNT query in codeigniter?

Doing a COUNT(*) will only give you a singular row containing the number of rows and not the results themselves.

To access COUNT(*) you would need to do

$result = $query->row_array();
$count = $result['COUNT(*)'];

The second option performs much better since it does not need to return a dataset to PHP but instead just a count and therefore is much more optimized.

Objects inside objects in javascript

You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:

{el1, el2, {el31, el32, el33}, {el41, el42}}

_x000D_
_x000D_
var MainObj = {_x000D_
_x000D_
  prop1: "prop1MainObj",_x000D_
  _x000D_
  Obj1: {_x000D_
    prop1: "prop1Obj1",_x000D_
    prop2: "prop2Obj1",    _x000D_
    Obj2: {_x000D_
      prop1: "hey you",_x000D_
      prop2: "prop2Obj2"_x000D_
    }_x000D_
  },_x000D_
    _x000D_
  Obj3: {_x000D_
    prop1: "prop1Obj3",_x000D_
    prop2: "prop2Obj3"_x000D_
  },_x000D_
  _x000D_
  Obj4: {_x000D_
    prop1: true,_x000D_
    prop2: 3_x000D_
  }  _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
_x000D_
_x000D_

Toolbar Navigation Hamburger Icon missing

in JetPack it work for me

NavigationUI.setupWithNavController(vb.toolbar, nav)
vb.toolbar.navigationIcon = ResourcesCompat.getDrawable(resources, R.drawable.icon_home, null)

jQuery to loop through elements with the same class

try this...

$('.testimonial').each(function(){
    //if statement here 
    // use $(this) to reference the current div in the loop
    //you can try something like...


    if(condition){

    }


 });

How do I add my bot to a channel?

As of now:

  • Only the creator of the channel can add a bot.
  • Other administrators can't add bots to channels.
  • Channel can be public or private (doesn't matter)
  • bots can be added only as admins, not members.*

To add the bot to your channel:

  • click on the channel name: enter image description here

  • click on admins: enter image description here

  • click on Add Admin: enter image description here

  • search for your bot like @your_bot_name, and click add:** enter image description here

* In some platforms like mac native telegram client it may look like that you can add bot as a member, but at the end it won't work.
** the bot doesn't need to be in your contact list.

How to use regex in String.contains() method in Java

String.contains

String.contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.

Note that String.contains does not check for word boundary; it simply checks for substring.

Regex solution

Regex is more powerful than String.contains, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.

Use String.matches with the following regex:

"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"

The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):

(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*

The \b checks for word boundary, so that you don't get a match for restores store products. Note that stores 3store_product is also rejected, since digit and _ are considered part of a word, but I doubt this case appear in natural text.

Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product will not match the regex above, since you are searching for the word store without s.

. normally match any character except a number of new line characters. (?s) at the beginning makes . matches any character without exception (thanks to Tim Pietzcker for pointing this out).

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

In my case, the error was in using angular2-notifications 0.9.8 instead of 0.9.7

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

I'm having the same issue here and I was a bit afraid of checking the last box, since I have no idea what the 3rd party SDK will do with the data collected and if they will respect the Limit Ad Settings.

But I found a post by a Google Admob programmer, Eric Leichtenschlag, on their forums:

The Google Mobile Ads SDK and the Google Conversion Tracking SDK utilize Apple's advertising identifier introduced in iOS 6 (IDFA). While each developer is responsible for how they access device data, the SDKs use IDFA under the guidelines laid out in the iOS developer program license agreement, including Limit Ad Tracking.

Including Limit Ad Tracking. This is what the last box is all about. So you must check the that box if you use AdMob. If you use other SDK I strongly recommend checking if they respect the guidelines as well.

Since I run only ads (Google AdMob), I checked the first (Serve ads...) and last box (I, ___, confirm...). App was approved and released, no issues.

Source: https://groups.google.com/forum/#!topic/google-admob-ads-sdk/BsGRSZ-gLmk

Using Java 8 to convert a list of objects into a string obtained from the toString() method

There is a collector joining in the API. It's a static method in Collectors.

list.stream().map(Object::toString).collect(Collectors.joining(","))

Not perfect because of the necessary call of toString, but works. Different delimiters are possible.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Finally, solved the problem above. I was receiving errors

  • Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service

Since I have not added WKWebView object on the view as a subview and tried to call -loadHTMLString:baseURL: on the top of it. And only after it was successfully loaded I was adding it to view's subviews - which was totally wrong. The correct solution for my problem is:

1. Add WKWebView object to view's subviews array

2. Call -loadHTMLString:baseURL: for recently added WKWebView

Android Endless List

Here is a solution that also makes it easy to show a loading view in the end of the ListView while it's loading.

You can see the classes here:

https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/helper/ListViewWithLoadingIndicatorHelper.java - Helper to make it possible to use the features without extending from SimpleListViewWithLoadingIndicator.

https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/listener/EndlessScrollListener.java - Listener that starts loading data when the user is about to reach the bottom of the ListView.

https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/view/SimpleListViewWithLoadingIndicator.java - The EndlessListView. You can use this class directly or extend from it.

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

How do I diff the same file between two different commits on the same branch?

If you have several files or directories and want to compare non continuous commits, you could do this:

Make a temporary branch ("revision" in this example)

git checkout -b revision

Rewind to the first commit target

git reset --hard <commit_target>

Cherry picking on those commit interested

git cherry-pick <commit_interested> ...

Apply diff

git diff <commit-target>^

When you done

git branch -D revision

How to get first and last element in an array in java?

This is the given array.

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// If you want print the last element in the array.

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// If you want to print the number of element in the array.

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// Second method to print the last element inside the array.

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

sh: 0: getcwd() failed: No such file or directory on cited drive

if some directory/folder does not exist but somehow you navigated to that directory in that case you can see this Error,

for example:

  • currently, you are in "mno" directory (path = abc/def/ghi/jkl/mno
  • run "sudo su" and delete mno
  • goto the "ghi" directory and delete "jkl" directory
  • now you are in "ghi" directory (path abc/def/ghi)
  • run "exit"
  • after running the "exit", you will get that Error
  • now you will be in "mno"(path = abc/def/ghi/jkl/mno) folder. that does not exist.

so, Generally this Error will show when Directory doesn't exist.

to fix this, simply run "cd;" or you can move to any other directory which exists.

nullable object must have a value

When using LINQ extension methods (e.g. Select, Where), the lambda function might be converted to SQL that might not behave identically to your C# code. For instance, C#'s short-circuit evaluated && and || are converted to SQL's eager AND and OR. This can cause problems when you're checking for null in your lambda.

Example:

MyEnum? type = null;
Entities.Table.Where(a => type == null || 
    a.type == (int)type).ToArray();  // Exception: Nullable object must have a value

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

Hiding elements in responsive layout?

New visible classes added to Bootstrap

Extra small devices Phones (<768px) (Class names : .visible-xs-block, hidden-xs)

Small devices Tablets (=768px) (Class names : .visible-sm-block, hidden-sm)

Medium devices Desktops (=992px) (Class names : .visible-md-block, hidden-md)

Large devices Desktops (=1200px) (Class names : .visible-lg-block, hidden-lg)

For more information : http://getbootstrap.com/css/#responsive-utilities


Below is deprecated as of v3.2.0


Extra small devices Phones (<768px) (Class names : .visible-xs, hidden-xs)

Small devices Tablets (=768px) (Class names : .visible-sm, hidden-sm)

Medium devices Desktops (=992px) (Class names : .visible-md, hidden-md)

Large devices Desktops (=1200px) (Class names : .visible-lg, hidden-lg)


Much older Bootstrap


.hidden-phone, .hidden-tablet etc. are unsupported/obsolete.

UPDATE:

In Bootstrap 4 there are 2 types of classes:

  • The hidden-*-up which hide the element when the viewport is at the given breakpoint or wider.
  • hidden-*-down which hide the element when the viewport is at the given breakpoint or smaller.

Also, the new xl viewport is added for devices that are more then 1200px width. For more information click here.

How do you comment an MS-access Query?

It is not possible to add comments to 'normal' Access queries, that is, a QueryDef in an mdb, which is why a number of people recommend storing the sql for queries in a table.

Rerender view on browser resize with React

I know this has been answered but just thought I'd share my solution as the top answer, although great, may now be a little outdated.

    constructor (props) {
      super(props)

      this.state = { width: '0', height: '0' }

      this.initUpdateWindowDimensions = this.updateWindowDimensions.bind(this)
      this.updateWindowDimensions = debounce(this.updateWindowDimensions.bind(this), 200)
    }

    componentDidMount () {
      this.initUpdateWindowDimensions()
      window.addEventListener('resize', this.updateWindowDimensions)
    }

    componentWillUnmount () {
      window.removeEventListener('resize', this.updateWindowDimensions)
    }

    updateWindowDimensions () {
      this.setState({ width: window.innerWidth, height: window.innerHeight })
    }

The only difference really is that I'm debouncing (only running every 200ms) the updateWindowDimensions on the resize event to increase performance a bit, BUT not debouncing it when it's called on ComponentDidMount.

I was finding the debounce made it quite laggy to mount sometimes if you have a situation where it's mounting often.

Just a minor optimisation but hope it helps someone!

What does Docker add to lxc-tools (the userspace LXC tools)?

Going to keep this pithier, this is already asked and answered above .

I'd step back however and answer it slightly differently, the docker engine itself adds orchestration as one of its extras and this is the disruptive part. Once you start running an app as a combination of containers running 'somewhere' across multiple container engines it gets really exciting. Robustness, Horizontal Scaling, complete abstraction from the underlying hardware, i could go on and on...

Its not just Docker that gives you this, in fact the de facto Container Orchestration standard is Kubernetes which comes in a lot of flavours, a Docker one, but also OpenShift, SuSe, Azure, AWS...

Then beneath K8S there are alternative container engines; the interesting ones are Docker and CRIO - recently built, daemonless, intended as a container engine specifically for Kubernetes but immature. Its the competition between these that I think will be the real long term choice for a container engine.

Xcode couldn't find any provisioning profiles matching

Requirements:

  1. Unique name (across all Apple Apps)
  2. Have to sign in while your phone is connected (mine had a large warning here)

Worked great without restart on Xcode 10

Settings

Best Way to do Columns in HTML/CSS

I would suggest you to either use <table> or CSS.

CSS is preferred for being more flexible. An example would be:

<!-- of course, you should move the inline CSS style to your stylesheet -->
<!-- main container, width = 70% of page, centered -->
<div id="contentBox" style="margin:0px auto; width:70%">

 <!-- columns divs, float left, no margin so there is no space between column, width=1/3 -->
    <div id="column1" style="float:left; margin:0; width:33%;">
     CONTENT
    </div>

    <div id="column2" style="float:left; margin:0;width:33%;">
     CONTENT
    </div>

    <div id="column3" style="float:left; margin:0;width:33%">
     CONTENT
    </div>
</div>

jsFiddle: http://jsfiddle.net/ndhqM/

Using float:left would make 3 columns stick to each other, coming in from left inside the centered div "content box".

Easiest way to toggle 2 classes in jQuery

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");

Using HTTPS with REST in Java

When you say "is there an easier way to... trust this cert", that's exactly what you're doing by adding the cert to your Java trust store. And this is very, very easy to do, and there's nothing you need to do within your client app to get that trust store recognized or utilized.

On your client machine, find where your cacerts file is (that's your default Java trust store, and is, by default, located at <java-home>/lib/security/certs/cacerts.

Then, type the following:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to cacerts>

That will import the cert into your trust store, and after this, your client app will be able to connect to your Grizzly HTTPS server without issue.

If you don't want to import the cert into your default trust store -- i.e., you just want it to be available to this one client app, but not to anything else you run on your JVM on that machine -- then you can create a new trust store just for your app. Instead of passing keytool the path to the existing, default cacerts file, pass keytool the path to your new trust store file:

keytool -import -alias <Name for the cert> -file <the .cer file> -keystore <path to new trust store>

You'll be asked to set and verify a new password for the trust store file. Then, when you start your client app, start it with the following parameters:

java -Djavax.net.ssl.trustStore=<path to new trust store> -Djavax.net.ssl.trustStorePassword=<trust store password>

Easy cheesy, really.

How to check for a Null value in VB.NET

If you are using a strongly-typed dataset then you should do this:

If Not ediTransactionRow.Ispay_id1Null Then
    'Do processing here
End If

You are getting the error because a strongly-typed data set retrieves the underlying value and exposes the conversion through the property. For instance, here is essentially what is happening:

Public Property pay_Id1 Then
   Get
     return DirectCast(me.GetValue("pay_Id1", short)
   End Get
   'Abbreviated for clarity
End Property

The GetValue method is returning DBNull which cannot be converted to a short.

How to split a string with angularJS

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];
        }
    });

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

How to configure the web.config to allow requests of any length

If you run into this issue when running an IIS 8.5 web server you can use the following method.

First, find the "Request Filtering" module in the IIS site you are working on, then double click it...

enter image description here

Next, you need to right click in the white area shown below then click the context menu option called "Edit Feature Settings".

enter image description here

Then the last thing to do is change the "Maximum query string (Bytes)" value from 2048 to something more appropriate such as 5000 for your needs.

enter image description here

using href links inside <option> tag

    <select name="career" id="career" onchange="location = this.value;">
        <option value="resume" selected> All Applications </option>
        <option value="resume&j=14">Seo Expert</option>
        <option value="resume&j=21">Project Manager</option>
        <option value="resume&j=33">Php Developer</option>
    </select>

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

How to center an element horizontally and vertically

to center the Div in a page check the fiddle link

_x000D_
_x000D_
#vh {_x000D_
    border-radius: 15px;_x000D_
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);_x000D_
    padding: 25px;_x000D_
    width: 200px;_x000D_
    height: 200px;_x000D_
    background: white;_x000D_
    text-align: center;_x000D_
    margin: auto;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    right: 0;_x000D_
}
_x000D_
<div id="vh">Div to be aligned vertically</div>
_x000D_
_x000D_
_x000D_

Update Another option is to use flex box check the fiddle link

_x000D_
_x000D_
.vh {_x000D_
    background-color: #ddd;_x000D_
    height: 200px;_x000D_
    align-items: center;_x000D_
    display: flex;_x000D_
}_x000D_
.vh > div {_x000D_
    width: 100%;_x000D_
    text-align: center;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<div class="vh">_x000D_
    <div>Div to be aligned vertically</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery & CSS - Remove/Add display:none

jQuery provides you with:

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

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

Lazy Method for Reading Big File in Python?

To write a lazy function, just use yield:

def read_in_chunks(file_object, chunk_size=1024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data


with open('really_big_file.dat') as f:
    for piece in read_in_chunks(f):
        process_data(piece)

Another option would be to use iter and a helper function:

f = open('really_big_file.dat')
def read1k():
    return f.read(1024)

for piece in iter(read1k, ''):
    process_data(piece)

If the file is line-based, the file object is already a lazy generator of lines:

for line in open('really_big_file.dat'):
    process_data(line)

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

I was facing the same problem. The following worked for me: Download the unoffical binaries file from Christoph Gohlke installers site as per the python version installed on your system. Navigate to the folder where you have installed the file and run

pip install filename

For me python_ldap-3.0.0-cp35-cp35m-win_amd64.whl worked as my machine is 64 bit and python version is 3.5. This successfully installed python-ldap on my windows machine. You can try the same for mysql-python

Java: Find .txt files in specified folder

import org.apache.commons.io.filefilter.WildcardFileFilter;

.........
.........

File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);

The code above works great for me

How to get just the parent directory name of a specific file

In Java 7 you have the new Paths api. The modern and cleanest solution is:

Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().getFileName();

Result would be:

C:/aaa/bbb/ccc/ddd

Edit Crystal report file without Crystal Report software

In case anyone else is looking for this... as of April 2013, you can still get the free Visual Studio edition of Crystal Reports from this web site: SAP Crystal Reports - Downloads (updated url).

It installs into Visual Studio 2010 or VS 2012, and you can edit and save RPT files with as much capability as the standard Crystal Reports editor.

How to perform case-insensitive sorting in JavaScript?

It is time to revisit this old question.

You should not use solutions relying on toLowerCase. They are inefficient and simply don't work in some languages (Turkish for instance). Prefer this:

['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))

Check the documentation for browser compatibility and all there is to know about the sensitivity option.

Need to find a max of three numbers in java

Two things: Change the variables x, y, z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.

In Summary, change below:

    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to

    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

Proper way to initialize C++ structs

From what you've told us it does appear to be a false positive in valgrind. The new syntax with () should value-initialize the object, assuming it is POD.

Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?

Alternately perhaps your compiler doesn't actually value-initialize POD structures.

In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.

If "0" then leave the cell blank

An accrual ledger should note zeroes, even if that is the hyphen displayed with an Accounting style number format. However, if you want to leave the line blank when there are no values to calculate use a formula like the following,

 =IF(COUNT(F16:G16), SUM(G16, INDEX(H$1:H15, MATCH(1e99, H$1:H15)), -F16), "")

That formula is a little tricky because you seem to have provided your sample formula from somewhere down into the entries of the ledger's item rows without showing any layout or sample data. The formula I provided should be able to be put into H16 and then copied or filled to other locations in column H but I offer no guarantees without seeing the layout.

If you post some sample data or a publicly available link to a screenshot showing your data layout more specific assistance could be offered. http://imgur.com/ is a good place to host a screenshot and it is likely that someone with more reputation will insert the image into your question for you.

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

For a minimum API level of 15, you'd want to use AppCompatActivity. So for example, your MainActivity would look like this:

public class MainActivity extends AppCompatActivity {
    ....
    ....
}

To use the AppCompatActivity, make sure you have the Google Support Library downloaded (you can check this in your Tools -> Android -> SDK manager). Then just include the gradle dependency in your app's gradle.build file:

compile 'com.android.support:appcompat-v7:22:2.0'

You can use this AppCompat as your main Activity, which can then be used to launch Fragments or other Activities (this depends on what kind of app you're building).

The BigNerdRanch book is a good resource, but yeah, it's outdated. Read it for general information on how Android works, but don't expect the specific classes they use to be up to date.

Call to getLayoutInflater() in places not in activity

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

bootstrap 3 - how do I place the brand in the center of the navbar?

Another option is to use nav-justified..

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav nav-justified">
      <li><a href="#" class="navbar-brand">Brand</a></li>
    </ul>
  </div>
</nav>

CSS

.navbar-brand {
    float:none;
}

Bootply

Alternate example

How to iterate over rows in a DataFrame in Pandas

I was looking for How to iterate on rows and columns and ended here so:

for i, row in df.iterrows():
    for j, column in row.iteritems():
        print(column)

Add a properties file to IntelliJ's classpath

I have the same problem and it annoys me tremendously!!

I have always thought I was surposed to do as answer 2. That used to work in Intellij 9 (now using 10).

However I figured out that by adding these line to my maven pom file helps:

<build>
  ...
  <resources>
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
  ...
</build>

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

From System Preferences, turn on the "Show Keyboard & Character Viewer in menu bar" setting.

Then, the "Character Viewer" menu will pop up a tool that will let you search for any unicode character (by name) and insert it ? you're all set.

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

"java.lang.OutOfMemoryError : unable to create new native Thread"

I encountered same issue during the load test, the reason is because of JVM is unable to create a new Java thread further. Below is the JVM source code

if (native_thread->osthread() == NULL) {    
// No one should hold a reference to the 'native_thread'.    
    delete native_thread;   
if (JvmtiExport::should_post_resource_exhausted()) {      
    JvmtiExport::post_resource_exhausted(        
        JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | 
        JVMTI_RESOURCE_EXHAUSTED_THREADS, 
        "unable to create new native thread");    
    } THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "unable to create new native thread");  
} Thread::start(native_thread);`

Root cause : JVM throws this exception when JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR (resources exhausted (means memory exhausted) ) or JVMTI_RESOURCE_EXHAUSTED_THREADS (Threads exhausted).

In my case Jboss is creating too many threads , to serve the request, but all the threads are blocked . Because of this, JVM is exhausted with threads as well with memory (each thread holds memory , which is not released , because each thread is blocked).

Analyzed the java thread dumps observed nearly 61K threads are blocked by one of our method, which is causing this issue . Below is the portion of Thread dump

"SimpleAsyncTaskExecutor-16562" #38070 prio=5 os_prio=0 tid=0x00007f9985440000 nid=0x2ca6 waiting for monitor entry [0x00007f9d58c2d000]
   java.lang.Thread.State: BLOCKED (on object monitor)

How to get the fragment instance from the FragmentActivity?

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

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

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

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

Given a filesystem path, is there a shorter way to extract the filename without its extension?

You can use Path API as follow:

 var filenNme = Path.GetFileNameWithoutExtension([File Path]);

More info: Path.GetFileNameWithoutExtension

tr:hover not working

Try it:

css code:

.list1 tr:hover td {
    background-color:#fefefe;
}

Same Navigation Drawer in different Activities

My answer is just a conceptual one without any source code. It might be useful for some readers like myself to understand.

It depends on your initial approach on how you architecture your app. There are basically two approaches.

  1. You create one activity (base activity) and all the other views and screens will be fragments. That base activity contains the implementation for Drawer and Coordinator Layouts. It is actually my preferred way of doing because having small self-contained fragments will make app development easier and smoother.

  2. If you have started your app development with activities, one for each screen , then you will probably create base activity, and all other activity extends from it. The base activity will contain the code for drawer and coordinator implementation. Any activity that needs drawer implementation can extend from base activity.

I would personally prefer avoiding to use fragments and activities mixed without any organizing. That makes the development more difficult and get you stuck eventually. If you have done it, refactor your code.

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Salt and hash a password in Python

Here's my proposition:

for i in range(len(rserver.keys())):
    salt = uuid.uuid4().hex
    print(salt)
    mdp_hash = rserver.get(rserver.keys()[i])
    rserver.set(rserver.keys()[i], hashlib.sha256(salt.encode() + mdp_hash.encode()).hexdigest() + salt)
    rsalt.set(rserver.keys()[i], salt)

No connection could be made because the target machine actively refused it 127.0.0.1

I had a similar issue, trying to run a WCF-based HttpSelfHostServer in Debug under my VisualStudio 2013. I tried every possible direction (turn off firewall, disabling IIS completely to eliminate the possibility localhost port is taken by some other service, etc.).

Eventually, what "did the trick" (solved the problem) was re-running VisualStudio 2013 as Administrator.

Amazing.

SQL Server principal "dbo" does not exist,

Also had this error when accidentally fed a database connection string to the readonly mirror - not the primary database in a HA setup.

Connection failed: SQLState: '01000' SQL Server Error: 10061

  1. Windows firewall blocks the sql server. Even if you open the 1433 port from exceptions, in the client machine it sets the connection point to dynamic port. Add also the sql server to the exceptions.

"C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn\Sqlservr.exe"

More info

  1. This page helped me to solve the problem. Especially

or if you feel brave, locate the alias in the registry and delete it there.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo\

Have a div cling to top of screen if scrolled down past it

The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.

Derived from the code viixii.com uses I ended up using this:

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top)
        $('#sticky-element').addClass('sticky');
    else
        $('#sticky-element').removeClass('sticky');
}

$(function() {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.

Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.

Just place an empty div with a class acting like an anchor just above the element you want to have fixed.

Like so:

<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>

All credit for the code goes to viixii.com

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

php timeout - set_time_limit(0); - don't work

This is an old thread, but I thought I would post this link, as it helped me quite a bit on this issue. Essentially what it's saying is the server configuration can override the php config. From the article:

For example mod_fastcgi has an option called "-idle-timeout" which controls the idle time of the script. So if the script does not output anything to the fastcgi handler for that many seconds then fastcgi would terminate it. The setup is somewhat like this:

Apache <-> mod_fastcgi <-> php processes

The article has other examples and further explanation. Hope this helps somebody else.

How to close current tab in a browser window?

Sorry for necroposting this, but I recently implemented a locally hosted site that had needed the ability to close the current browser tab and found some interesting workarounds that are not well documented anywhere I could find, so took it on myself to do so.

Note: These workarounds were done with a locally hosted site in mind, and (with the exception of Edge) require the browser to be specifically configured, so would not be ideal for publicly hosted sites.

Context: In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, modern browsers no longer support this script, potentially for security reasons.

Google Chrome:

Chrome does not allow the window.close() script to be to be run and nothing happens if you try to use it. By using the Chrome plugin TamperMonkey however we can use the window.close() method if you include the // @grant window.close in the UserScript header of TamperMonkey.

For example, my script (which is triggered when a button with id = 'close_page' is clicked and if 'yes' is pressed on the browser popup) looks like:

// ==UserScript==
// @name         Close Tab Script
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Closes current tab when triggered
// @author       Mackey Johnstone
// @match        http://localhost/index.php
// @grant        window.close
// @require      http://code.jquery.com/jquery-3.4.1.min.js
// ==/UserScript==

(function() {
    'use strict';
    $("#close_page").click(function() {
        var confirm_result = confirm("Are you sure you want to quit?");
        if (confirm_result == true) {
            window.close();
        }
    });
})();

Note: This solution can only close the tab if it is NOT the last tab open however. So effectively, it cannot close the tab if it would cause window to closes by being the last tab open.

Firefox:

Firefox has an advanced setting that you can enable to allow scripts to close windows, effectively enabling the window.close() method. To enable this setting go to about:config then search and find the dom.allow_scripts_to_close_windows preference and switch it from false to true.

This allows you to use the window.close() method directly in your jQuery file as you would any other script.

For example, this script works perfectly with the preference set to true:

<script>
  $("#close_page").click(function() {
    var confirm_result = confirm("Are you sure you want to quit?");
    if (confirm_result == true) {
      window.close();
    }
  });
</script>

This works much better than the Chrome workaround as it allows the user to close the current tab even if it is the only tab open, and doesn't require a third party plugin. The one downside however is that it also enables this script to be run by different websites (not just the one you are intending it to use on) so could potentially be a security hazard, although I cant imagine closing the current tab being particularly dangerous.

Edge:

Disappointingly Edge actually performed the best out of all 3 browsers I tried, and worked with the window.close() method without requiring any configuration. When the window.close() script is run, an additional popup alerts you that the page is trying to close the current tab and asks if you want to continue.

Edit: This was on the old version of Edge not based on chromium. I have not tested it, but imagine it will act similarly to Chrome on chromium based versions

enter image description here

Final Note: The solutions for both Chrome and Firefox are workarounds for something that the browsers intentionally disabled, potentially for security reasons. They also both require the user to configure their browsers up to be compatible before hand, so would likely not be viable for sites intended for public use, but are ideal for locally hosted solutions like mine.

Hope this helped! :)

How can one pull the (private) data of one's own Android app?

you can do:

adb pull /storage/emulated/0/Android/data//

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

how to make a specific text on TextView BOLD

You can use this code to set part of your text to bold. For whatever is in between the bold html tags, it will make it bold.

String myText = "make this <b>bold</b> and <b>this</b> too";
textView.setText(makeSpannable(myText, "<b>(.+?)</b>", "<b>", "</b>"));

public SpannableStringBuilder makeSpannable(String text, String regex, String startTag, String endTag) {

            StringBuffer sb = new StringBuffer();
            SpannableStringBuilder spannable = new SpannableStringBuilder();

            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                sb.setLength(0);
                String group = matcher.group();
                String spanText = group.substring(startTag.length(), group.length() - endTag.length());
                matcher.appendReplacement(sb, spanText);

                spannable.append(sb.toString());
                int start = spannable.length() - spanText.length();

                spannable.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), start, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            sb.setLength(0);
            matcher.appendTail(sb);
            spannable.append(sb.toString());
            return spannable;
        }

What to do with "Unexpected indent" in python?

Run the following command to get it solved :

autopep8 -i <filename>.py

This will update your code and solve all indentation Errors :)

Hope this will solve

Converting ArrayList to HashMap

The general methodology would be to iterate through the ArrayList, and insert the values into the HashMap. An example is as follows:

HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
   productMap.put(product.getProductCode(), product);
}

How do you change the colour of each category within a highcharts column chart?

Just add this...or you can change the colors as per your demand.

Highcharts.setOptions({
        colors: ['#811010', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
        plotOptions: {
            column: {
                colorByPoint: true
            }
        }

    });

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

Why does SSL handshake give 'Could not generate DH keypair' exception?

Here is my solution (java 1.6), also would be interested why I had to do this:

I noticed from the javax.security.debug=ssl, that sometimes the used cipher suite is TLS_DHE_... and sometime it is TLS_ECDHE_.... The later would happen if I added BouncyCastle. If TLS_ECDHE_ was selected, MOST OF the time it worked, but not ALWAYS, so adding even BouncyCastle provider was unreliable (failed with same error, every other time or so). I guess somewhere in the Sun SSL implementation sometimes it choose DHE, sometimes it choose ECDHE.

So the solution posted here relies on removing TLS_DHE_ ciphers completely. NOTE: BouncyCastle is NOT required for the solution.

So create the server certification file by:

echo |openssl s_client -connect example.org:443 2>&1 |sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

Save this as it will be referenced later, than here is the solution for an SSL http get, excluding the TLS_DHE_ cipher suites.

package org.example.security;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import org.apache.log4j.Logger;

public class SSLExcludeCipherConnectionHelper {

    private Logger logger = Logger.getLogger(SSLExcludeCipherConnectionHelper.class);

    private String[] exludedCipherSuites = {"_DHE_","_DH_"};

    private String trustCert = null;

    private TrustManagerFactory tmf;

    public void setExludedCipherSuites(String[] exludedCipherSuites) {
        this.exludedCipherSuites = exludedCipherSuites;
    }

    public SSLExcludeCipherConnectionHelper(String trustCert) {
        super();
        this.trustCert = trustCert;
        //Security.addProvider(new BouncyCastleProvider());
        try {
            this.initTrustManager();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void initTrustManager() throws Exception {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = new BufferedInputStream(new FileInputStream(trustCert));
        Certificate ca = null;
        try {
            ca = cf.generateCertificate(caInput);
            logger.debug("ca=" + ((X509Certificate) ca).getSubjectDN());
        } finally {
            caInput.close();
        }

        // Create a KeyStore containing our trusted CAs
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);
    }

    public String get(URL url) throws Exception {
        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);
        SSLParameters params = context.getSupportedSSLParameters();
        List<String> enabledCiphers = new ArrayList<String>();
        for (String cipher : params.getCipherSuites()) {
            boolean exclude = false;
            if (exludedCipherSuites != null) {
                for (int i=0; i<exludedCipherSuites.length && !exclude; i++) {
                    exclude = cipher.indexOf(exludedCipherSuites[i]) >= 0;
                }
            }
            if (!exclude) {
                enabledCiphers.add(cipher);
            }
        }
        String[] cArray = new String[enabledCiphers.size()];
        enabledCiphers.toArray(cArray);

        // Tell the URLConnection to use a SocketFactory from our SSLContext
        HttpsURLConnection urlConnection =
            (HttpsURLConnection)url.openConnection();
        SSLSocketFactory sf = context.getSocketFactory();
        sf = new DOSSLSocketFactory(sf, cArray);
        urlConnection.setSSLSocketFactory(sf);
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String inputLine;
        StringBuffer buffer = new StringBuffer();
        while ((inputLine = in.readLine()) != null) 
            buffer.append(inputLine);
        in.close();

        return buffer.toString();
    }

    private class DOSSLSocketFactory extends javax.net.ssl.SSLSocketFactory {

        private SSLSocketFactory sf = null;
        private String[] enabledCiphers = null;

        private DOSSLSocketFactory(SSLSocketFactory sf, String[] enabledCiphers) {
            super();
            this.sf = sf;
            this.enabledCiphers = enabledCiphers;
        }

        private Socket getSocketWithEnabledCiphers(Socket socket) {
            if (enabledCiphers != null && socket != null && socket instanceof SSLSocket)
                ((SSLSocket)socket).setEnabledCipherSuites(enabledCiphers);

            return socket;
        }

        @Override
        public Socket createSocket(Socket s, String host, int port,
                boolean autoClose) throws IOException {
            return getSocketWithEnabledCiphers(sf.createSocket(s, host, port, autoClose));
        }

        @Override
        public String[] getDefaultCipherSuites() {
            return sf.getDefaultCipherSuites();
        }

        @Override
        public String[] getSupportedCipherSuites() {
            if (enabledCiphers == null)
                return sf.getSupportedCipherSuites();
            else
                return enabledCiphers;
        }

        @Override
        public Socket createSocket(String host, int port) throws IOException,
                UnknownHostException {
            return getSocketWithEnabledCiphers(sf.createSocket(host, port));
        }

        @Override
        public Socket createSocket(InetAddress address, int port)
                throws IOException {
            return getSocketWithEnabledCiphers(sf.createSocket(address, port));
        }

        @Override
        public Socket createSocket(String host, int port, InetAddress localAddress,
                int localPort) throws IOException, UnknownHostException {
            return getSocketWithEnabledCiphers(sf.createSocket(host, port, localAddress, localPort));
        }

        @Override
        public Socket createSocket(InetAddress address, int port,
                InetAddress localaddress, int localport) throws IOException {
            return getSocketWithEnabledCiphers(sf.createSocket(address, port, localaddress, localport));
        }

    }
}

Finally here is how it is used (certFilePath if the path of the certificate saved from openssl):

try {
            URL url = new URL("https://www.example.org?q=somedata");            
            SSLExcludeCipherConnectionHelper sslExclHelper = new SSLExcludeCipherConnectionHelper(certFilePath);
            logger.debug(
                    sslExclHelper.get(url)
            );
        } catch (Exception ex) {
            ex.printStackTrace();
        }

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

MVC 4 Data Annotations "Display" Attribute

In addition to the other answers, there is a big benefit to using the DisplayAttribute when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.

Also, you can let MVC generate the templates for you by using Html.EditorForModel() and it will generate the correct label for you.

Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.

Using TortoiseSVN via the command line

TortoiseSVN has a command-line interface that can be used for TortoiseSVN GUI automation and it's different from the normal Subversion one.

You can find information about the command-line options of TortoiseSVN in the documentation: Appendix D. Automating TortoiseSVN. The main program to work with here is TortoiseProc.exe.

But a note pretty much at the top there already says:

Remember that TortoiseSVN is a GUI client, and this automation guide shows you how to make the TortoiseSVN dialogs appear to collect user input. If you want to write a script which requires no input, you should use the official Subversion command line client instead.

Another option would be that you install the Subversion binaries. Slik SVN is a nice build (and doesn't require a registration like Collabnet). Recent versions of TortoiseSVN also include the command-line client if you choose to install it.

How to calculate difference in hours (decimal) between two dates in SQL Server?

You are probably looking for the DATEDIFF function.

DATEDIFF ( datepart , startdate , enddate )

Where you code might look like this:

DATEDIFF ( hh , startdate , enddate )

Put request with simple string as request body

I solved this by overriding the default Content-Type:

const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
    ...
});

Based on m experience, the default Conent-Type is application/x-www-form-urlencoded for strings, and application/json for objects (including arrays). Your server probably expects JSON.

Android WSDL/SOAP service client

Android doesn't come with SOAP library. However, you can download 3rd party library here:
https://github.com/simpligility/ksoap2-android

If you need help using it, you might find this thread helpful:
How to call a .NET Webservice from Android using KSOAP2?

How to convert Rows to Columns in Oracle?

If you are using Oracle 10g, you can use the DECODE function to pivot the rows into columns:

CREATE TABLE doc_tab (
  loan_number VARCHAR2(20),
  document_type VARCHAR2(20),
  document_id VARCHAR2(20)
);

INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');

COMMIT;

SELECT
    loan_number,
    MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
    MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
    MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
  FROM
    doc_tab
GROUP BY loan_number
ORDER BY loan_number;

Output:

LOAN_NUMBER   VOTERS_ID            PAN_CARD             DRIVERS_LICENCE    
------------- -------------------- -------------------- --------------------
992452533663  XPD0355636           CHXPS5522D           DL-0420110141769     

You can achieve the same using Oracle PIVOT clause, introduced in 11g:

SELECT *
  FROM doc_tab
PIVOT (
  MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);

SQLFiddle example with both solutions: SQLFiddle example

Read more about pivoting here: Pivot In Oracle by Tim Hall

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?

Conditionally formatting cells if their value equals any value of another column

No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:

NOTE: remove any duplicates from the individual columns first!

  1. Select the columns to compare
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red

    • Bonus tip, you can filter each row by colour to either leave the unique values in the column, or leave just the duplicates.

enter image description here enter image description here

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

Excel compare two columns and highlight duplicates

A simple formula to use is

=COUNTIF($B:$B,A1)

Formula specified is for cell A1. Simply copy and paste special - format to the whole of column A

Html attributes for EditorFor() in ASP.NET MVC

Now ASP.Net MVC 5.1 got a built in support for it.

From Release Notes

We now allow passing in HTML attributes in EditorFor as an anonymous object.

For example:

@Html.EditorFor(model => model, 
              new { htmlAttributes = new { @class = "form-control" }, })

How to handle checkboxes in ASP.NET MVC forms?

Just do this on $(document).ready :

$('input:hidden').each(function(el) {
    var that = $(this)[0];
    if(that.id.length < 1 ) {

        console.log(that.id);
        that.parentElement.removeChild(that);

    }
});

jQuery $(this) keyword

$(this) returns a cached version of the element, hence improving performance since jQuery doesn't have to do a complete lookup in the DOM of the element again.

Understanding repr( ) function in Python

>>> x = 'foo'
>>> x
'foo'

So the name x is attached to 'foo' string. When you call for example repr(x) the interpreter puts 'foo' instead of x and then calls repr('foo').

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr actually calls a magic method __repr__ of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

>>> eval("'foo'")
'foo'

When we call eval("'foo'"), it's the same as we type 'foo' in the interpreter. It's as we directly type the contents of the outer string "" in the interpreter.

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

If we call eval('foo'), it's the same as we type foo in the interpreter. But there is no foo variable available and an exception is raised.

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>> 

str is just the string representation of the object (remember, x variable refers to 'foo'), so this function returns string.

>>> str(5)
'5'

String representation of integer 5 is '5'.

>>> str('foo')
'foo'

And string representation of string 'foo' is the same string 'foo'.

How do I choose grid and block dimensions for CUDA kernels?

The answers above point out how the block size can impact performance and suggest a common heuristic for its choice based on occupancy maximization. Without wanting to provide the criterion to choose the block size, it would be worth mentioning that CUDA 6.5 (now in Release Candidate version) includes several new runtime functions to aid in occupancy calculations and launch configuration, see

CUDA Pro Tip: Occupancy API Simplifies Launch Configuration

One of the useful functions is cudaOccupancyMaxPotentialBlockSize which heuristically calculates a block size that achieves the maximum occupancy. The values provided by that function could be then used as the starting point of a manual optimization of the launch parameters. Below is a little example.

#include <stdio.h>

/************************/
/* TEST KERNEL FUNCTION */
/************************/
__global__ void MyKernel(int *a, int *b, int *c, int N) 
{ 
    int idx = threadIdx.x + blockIdx.x * blockDim.x; 

    if (idx < N) { c[idx] = a[idx] + b[idx]; } 
} 

/********/
/* MAIN */
/********/
void main() 
{ 
    const int N = 1000000;

    int blockSize;      // The launch configurator returned block size 
    int minGridSize;    // The minimum grid size needed to achieve the maximum occupancy for a full device launch 
    int gridSize;       // The actual grid size needed, based on input size 

    int* h_vec1 = (int*) malloc(N*sizeof(int));
    int* h_vec2 = (int*) malloc(N*sizeof(int));
    int* h_vec3 = (int*) malloc(N*sizeof(int));
    int* h_vec4 = (int*) malloc(N*sizeof(int));

    int* d_vec1; cudaMalloc((void**)&d_vec1, N*sizeof(int));
    int* d_vec2; cudaMalloc((void**)&d_vec2, N*sizeof(int));
    int* d_vec3; cudaMalloc((void**)&d_vec3, N*sizeof(int));

    for (int i=0; i<N; i++) {
        h_vec1[i] = 10;
        h_vec2[i] = 20;
        h_vec4[i] = h_vec1[i] + h_vec2[i];
    }

    cudaMemcpy(d_vec1, h_vec1, N*sizeof(int), cudaMemcpyHostToDevice);
    cudaMemcpy(d_vec2, h_vec2, N*sizeof(int), cudaMemcpyHostToDevice);

    float time;
    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start, 0);

    cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, MyKernel, 0, N); 

    // Round up according to array size 
    gridSize = (N + blockSize - 1) / blockSize; 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Occupancy calculator elapsed time:  %3.3f ms \n", time);

    cudaEventRecord(start, 0);

    MyKernel<<<gridSize, blockSize>>>(d_vec1, d_vec2, d_vec3, N); 

    cudaEventRecord(stop, 0);
    cudaEventSynchronize(stop);
    cudaEventElapsedTime(&time, start, stop);
    printf("Kernel elapsed time:  %3.3f ms \n", time);

    printf("Blocksize %i\n", blockSize);

    cudaMemcpy(h_vec3, d_vec3, N*sizeof(int), cudaMemcpyDeviceToHost);

    for (int i=0; i<N; i++) {
        if (h_vec3[i] != h_vec4[i]) { printf("Error at i = %i! Host = %i; Device = %i\n", i, h_vec4[i], h_vec3[i]); return; };
    }

    printf("Test passed\n");

}

EDIT

The cudaOccupancyMaxPotentialBlockSize is defined in the cuda_runtime.h file and is defined as follows:

template<class T>
__inline__ __host__ CUDART_DEVICE cudaError_t cudaOccupancyMaxPotentialBlockSize(
    int    *minGridSize,
    int    *blockSize,
    T       func,
    size_t  dynamicSMemSize = 0,
    int     blockSizeLimit = 0)
{
    return cudaOccupancyMaxPotentialBlockSizeVariableSMem(minGridSize, blockSize, func, __cudaOccupancyB2DHelper(dynamicSMemSize), blockSizeLimit);
}

The meanings for the parameters is the following

minGridSize     = Suggested min grid size to achieve a full machine launch.
blockSize       = Suggested block size to achieve maximum occupancy.
func            = Kernel function.
dynamicSMemSize = Size of dynamically allocated shared memory. Of course, it is known at runtime before any kernel launch. The size of the statically allocated shared memory is not needed as it is inferred by the properties of func.
blockSizeLimit  = Maximum size for each block. In the case of 1D kernels, it can coincide with the number of input elements.

Note that, as of CUDA 6.5, one needs to compute one's own 2D/3D block dimensions from the 1D block size suggested by the API.

Note also that the CUDA driver API contains functionally equivalent APIs for occupancy calculation, so it is possible to use cuOccupancyMaxPotentialBlockSize in driver API code in the same way shown for the runtime API in the example above.

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

How can I check if a single character appears in a string?

package com;
public class _index {

    public static void main(String[] args) {
        String s1="be proud to be an indian";
        char ch=s1.charAt(s1.indexOf('e'));
        int count = 0; 
        for(int i=0;i<s1.length();i++) {
            if(s1.charAt(i)=='e'){
                System.out.println("number of E:=="+ch);
                count++;
            }
        }
        System.out.println("Total count of E:=="+count);
    }
}

SQL Server Error : String or binary data would be truncated

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.

In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

Python Checking a string's first and last character

When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1

Counting Chars in EditText Changed Listener

how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));

Rename multiple files in a directory in Python

What about this :

import re
p = re.compile(r'_')
p.split(filename, 1) #where filename is CHEESE_CHEESE_TYPE.***

Convert string to float?

Try this:

String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue(); 
System.out.println(a);

"Stack overflow in line 0" on Internet Explorer

Aha!

I had an OnError() event in some code that was setting the image source to a default image path if it wasn't found. Of course, if the default image path wasn't found it would trigger the error handler...

For people who have a similar problem but not the same, I guess the cause of this is most likely to be either an unterminated loop, an event handler that triggers itself or something similar that throws the JavaScript engine into a spin.

Python decorators in classes

This is one way to access(and have used) self from inside a decorator defined inside the same class:

class Thing(object):
    def __init__(self, name):
        self.name = name

    def debug_name(function):
        def debug_wrapper(*args):
            self = args[0]
            print 'self.name = ' + self.name
            print 'running function {}()'.format(function.__name__)
            function(*args)
            print 'self.name = ' + self.name
        return debug_wrapper

    @debug_name
    def set_name(self, new_name):
        self.name = new_name

Output (tested on Python 2.7.10):

>>> a = Thing('A')
>>> a.name
'A'
>>> a.set_name('B')
self.name = A
running function set_name()
self.name = B
>>> a.name
'B'

The example above is silly, but it works.

Sorting a vector of custom objects

A simple example using std::sort

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

struct less_than_key
{
    inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
    {
        return (struct1.key < struct2.key);
    }
};

std::vector < MyStruct > vec;

vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));

std::sort(vec.begin(), vec.end(), less_than_key());

Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the operator< for MyStruct:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator < (const MyStruct& str) const
    {
        return (key < str.key);
    }
};

Using this method means you can simply sort the vector as follows:

std::sort(vec.begin(), vec.end());

Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a > operator and changing call of sort a bit:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator > (const MyStruct& str) const
    {
        return (key > str.key);
    }
};

And you should call sort as:

std::sort(vec.begin(), vec.end(),greater<MyStruct>());

Convert a date format in epoch

tl;dr

ZonedDateTime.parse( 
                        "Jun 13 2003 23:11:52.454 UTC" , 
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" ) 
                    )
              .toInstant()
              .toEpochMilli()

1055545912454

java.time

This Answer expands on the Answer by Lockni.

DateTimeFormatter

First define a formatting pattern to match your input string by creating a DateTimeFormatter object.

String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );

ZonedDateTime

Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).

ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );

zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]

Table of types of date-time classes in modern java.time versus legacy.

Count-from-epoch

I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).

But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.

Instant instant = zdt.toInstant ();

instant.toString(): 2003-06-13T23:11:52.454Z

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Can't push to the heroku

If you are a python user -
Create a requirements.txt file preferably using pip freeze > requirements.txt.
Add, commit and try pushing it again.

If this doesn't work try deleting .git (beware this might remove the associated git history) and follow the above steps again.

Worked for me.

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

How to tar certain file types in all subdirectories?

This will handle paths with spaces:

find ./ -type f -name "*.php" -o -name "*.html" -exec tar uvf myarchives.tar {} +

Prevent cell numbers from incrementing in a formula in Excel

There is something called 'locked reference' in excel which you can use for this, and you use $ symbols to lock a range. For your example, you would use:

=IF(B4<>"",B4/B$1,"")

This locks the 1 in B1 so that when you copy it to rows below, 1 will remain the same.

If you use $B$1, the range will not change when you copy it down a row or across a column.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How to change maven logging level to display only warning and errors?

Answering your question

I made a small investigation because I am also interested in the solution.

Maven command line verbosity options

According to http://books.sonatype.com/mvnref-book/reference/running-sect-options.html#running-sect-verbose-option

  • -e for error
  • -X for debug
  • -q for only error

Maven logging config file

Currently maven 3.1.x uses SLF4J to log to the System.out . You can modify the logging settings at the file:

${MAVEN_HOME}/conf/logging/simplelogger.properties

According to the page : http://maven.apache.org/maven-logging.html

Command line setup

I think you should be able to setup the default Log level of the simple logger via a command line parameter, like this:

$ mvn clean package -Dorg.slf4j.simpleLogger.defaultLogLevel=debug

But I could not get it to work. I guess the only problem with this is, maven picks up the default level from the config file on the classpath. I also tried a couple of other settings via System.properties, but all of them were unsuccessful.

Appendix

You can find the source of slf4j on github here : slf4j github

The source of the simplelogger here : slf4j/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java

The plexus loader loads the simplelogger.properties.

Could not open input file: composer.phar

The composer.phar install is not working but without .phar this is working.

We need to enable the openssl module in php before installing the zendframe work.

We have to uncomment the line ;extension=php_openssl.dll from php.ini file.

composer use different php.ini file which is located at the wamp\bin\php\php-<version number>\php.ini

After enabling the openssl we need to restart the server.

The execute the following comments.

I can install successfully using these commands -

composer self-update
composer install --prefer-dist

enter image description here

Firebase TIMESTAMP to date and Time

Firebase.ServerValue.TIMESTAMP is not actual timestamp it is constant that will be replaced with actual value in server if you have it set into some variable.

mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.on('value', function(snapshot){ console.log(snapshot.val()) })
//{startedAt: 1452508763895}

if you want to get server time then you can use following code

  fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
    var offsetVal = offset.val() || 0;
    var serverTime = Date.now() + offsetVal;
  });

A select query selecting a select statement

Not sure if Access supports it, but in most engines (including SQL Server) this is called a correlated subquery and works fine:

SELECT  TypesAndBread.Type, TypesAndBread.TBName,
        (
        SELECT  Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM    Sandwiches
        WHERE   (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
                OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
        ) As SandwichCount
FROM    TypesAndBread

This can be made more efficient by indexing Type and Bread and distributing the subqueries over the UNION:

SELECT  [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
        )
FROM    [Sandwiches Types]
UNION ALL
SELECT  [Breads].[Bread] As TBName, "Bread" As Type,
        (
        SELECT  COUNT(*) As SandwichCount
        FROM    Sandwiches
        WHERE   Sandwiches.Bread = [Breads].[Bread]
        )
FROM    [Breads]

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

In order to use internet on emulator if you are setting behind a proxy server perform the following steps:

  1. Go to settings->Wireless & networks->mobile networks->Access Point Names.
  2. Press menu button. an option menu will appear.

  3. from the option menu select New APN.

  4. Click on Name. provide name to apn say My APN.
  5. Click on APN. Enter www.
  6. Click on Proxy. enter your proxy server IP. you can get it from internet explorers internet options menu.
  7. click on Port. enter port number in my case it was 8080. you can get it from internet explorers internet options menu.
  8. Click on User-name. provide user-name in format domain\user-name. generally it is your systems login.
  9. Click on password. provide your systems password.
  10. press menu button again. an option menu will appear.
  11. press save. try n run your browser. hope its work for you it worked for me. good luck.

Finding and removing non ascii characters from an Oracle Varchar2

I think this will do the trick:

SELECT REGEXP_REPLACE(COLUMN, '[^[:print:]]', '')

What does the shrink-to-fit viewport meta attribute do?

It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:

Viewport Changes

Viewport meta tags using "width=device-width" cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding "shrink-to-fit=no" to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.

<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">

In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.

Example

Here's a worked visual example which shows the difference upon loading the page in the two configurations.

The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw). Note how in the first example the page is zoomed to fit when shrink-to-fit=no is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.

The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.

Without shrink-to-fit specified

Without shrink-to-fit=no

With shrink-to-fit=no

With shrink-to-fit=no

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

Under dependencyServices nothing of the above helped me, i ended up doing like below:

    class Static_Toast_Android
    {
        private static Context _context
        {
            get { return Android.App.Application.Context; }
        }
        public static void StaticDisplayToast(string message)
        {
            Toast.MakeText(_context, message, ToastLength.Long).Show();
        }
    }
    public class Toast_Android : IToast
    {

        public void DisplayToast(string message)
        {
            Static_Toast_Android.StaticDisplayToast(message);
        }
    }

I must use the "double-class" because an interface cannot be static. L-

How to split a string literal across multiple lines in C / Objective-C?

GCC adds C++ multiline raw string literals as a C extension

C++11 has raw string literals as mentioned at: https://stackoverflow.com/a/44337236/895245

However, GCC also adds them as a C extension, you just have to use -std=gnu99 instead of -std=c99. E.g.:

main.c

#include <assert.h>
#include <string.h>

int main(void) {
    assert(strcmp(R"(
a
b
)", "\na\nb\n") == 0);
}

Compile and run:

gcc -o main -pedantic -std=gnu99 -Wall -Wextra main.c
./main

This can be used for example to insert multiline inline assembly into C code: How to write multiline inline assembly code in GCC C++?

Now you just have to lay back, and wait for it to be standardized on C20XY.

C++ was asked at: C++ multiline string literal

Tested on Ubuntu 16.04, GCC 6.4.0, binutils 2.26.1.

Add an object to a python list

while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy

How to change the color of an svg element?

Target the path within the svg:

<svg>
   <path>....
</svg>

You can do inline, like:

<path fill="#ccc">

Or

svg{
   path{
        fill: #ccc

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile

Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);

If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:

<a href="viewpdf.aspx" target="_blank">View PDF</a>

Get top most UIViewController

Based on Dianz answer, the Objective-C version

- (UIViewController *) topViewController {
   UIViewController *baseVC = UIApplication.sharedApplication.keyWindow.rootViewController;
   if ([baseVC isKindOfClass:[UINavigationController class]]) {
       return ((UINavigationController *)baseVC).visibleViewController;
   }

   if ([baseVC isKindOfClass:[UITabBarController class]]) {
       UIViewController *selectedTVC = ((UITabBarController*)baseVC).selectedViewController;
       if (selectedTVC) {
           return selectedTVC;
       }
   }

   if (baseVC.presentedViewController) {
       return baseVC.presentedViewController;
   }
   return baseVC;
}

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

RSpec: how to test if a method was called?

In the new rspec expect syntax this would be:

expect(subject).to receive(:bar).with("an argument I want")

How to enable ASP classic in IIS7.5

If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:

Add an 'Application Server' role:

  1. Click Start, point to Control Panel, click Programs, and then click Turn Windows features on or off.
  2. Right-click Server Manager, select Add Roles.
  3. On the Add Roles Wizard page, select Application Server, click Next three times, and then click Install. Windows Server installs the new role.

Then, add a 'Web Server' role:

  1. Web Server Role (IIS): in ServerManager, Roles, if the Web Server (IIS) role does not exist then add it.
  2. Under Web Server (IIS) role add role services for: ApplicationDevelopment:ASP, ApplicationDevelopment:ISAPI Exstensions, Security:Request Filtering.

More info: http://www.iis.net/learn/application-frameworks/running-classic-asp-applications-on-iis-7-and-iis-8/classic-asp-not-installed-by-default-on-iis

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

How to listen to route changes in react router v4?

import { useHistory } from 'react-router-dom';

const Scroll = () => {
  const history = useHistory();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [history.location.pathname]);

  return null;
}

How do I get the AM/PM value from a DateTime?

Very simple by using the string format

on .ToString("") :

  • if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.

  • if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.

  • if you add "tt" ->> The Am/Pm designator.

exemple converting from 23:12 to 11:12 Pm :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
var res2 = d.ToString("HH:mm");  // this show  23:12

Console.WriteLine(res);
Console.WriteLine(res2);

Console.Read();

wait a second that is not all you need to care about something else is the system Culture because the same code executed on windows with other langage especialy with difrent culture langage will generate difrent result with the same code

exemple of windows set to Arabic langage culture will show like that :

// 23:12 ?

? means Evening (first leter of ????) .

in another system culture depend on what is set on the windows regional and language option, it will show // 23:12 du.

you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it do a rebuild (execute) of your app and watch what iam talking about.

so who can I force showing Am and Pm Words in English event if the culture of the >current system isn't set to English ?

easy just by adding two lines : ->

the first step add using System.Globalization; on top of your code

and modifing the Previous code to be like this :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm

InvariantCulture => using default English Format.

another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?

Soution for Arabic Exemple :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 

this will show // 23:12 ?

event if my system is set to an English region format. you can change "ar-AE" if you want to another language format. there is a list of each language and its format.

exemples :

ar          ar-SA       Arabic
ar-BH       ar-BH       Arabic (Bahrain)
ar-DZ       ar-DZ       Arabic (Algeria)
ar-EG       ar-EG       Arabic (Egypt)

big list...

make me know if you have another question .

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

Visual Studio 2013 License Product Key

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

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

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

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

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

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

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

    • Exit the registry

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

    Visual Studio Repair button

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

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


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

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

How to use Session attributes in Spring-mvc

The below annotated code would set "value" to "name"

@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
    request.getSession().setAttribute("name", "value");
    return "testJsp";
  }
}

To access the same in JSP use ${sessionScope.name}.

For the @ModelAttribute see this link

Getting a HeadlessException: No X11 DISPLAY variable was set

I assume you're trying to tunnel into some unix box.

Make sure X11 forwarding is enabled in your PuTTY settings.

enter image description here

adding onclick event to dynamically added button?

Try this:

var inputTag = document.createElement("div");              
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
document.body.appendChild(inputTag);

This creates a button inside a DIV which works perfectly!

Define an <img>'s src attribute in CSS

just this as img tag is a content element

img {
    content:url(http://example.com/image.png);
}

Use of "this" keyword in C++

Yes. unless, there is an ambiguity.

How to add icon inside EditText view in Android ?

If you want to use Android's default drawable, you can use @android:drawable/ic_menu_search like this:

<EditText android:id="@+id/inputSearch"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawableLeft="@android:drawable/ic_menu_search"
    android:hint="Search product.."
    android:inputType="textVisiblePassword"/>

WAMP/XAMPP is responding very slow over localhost

This is caused by IPV6. Here is how you make MYSQL not use it. (so, without disabling IPV6)

edit mysql file 'my.ini'

under [wampmysqld] or [mysqld] add the following:

bind-address = ::

Save file and restart mysql service

enjoy!

iPhone - Get Position of UIView within entire UIWindow

Swift 3, with extension:

extension UIView{
    var globalPoint :CGPoint? {
        return self.superview?.convert(self.frame.origin, to: nil)
    }

    var globalFrame :CGRect? {
        return self.superview?.convert(self.frame, to: nil)
    }
}

How do you fix the "element not interactable" exception?

A possibility is that the element is currently unclickable because it is not visible. Reasons for this may be that another element is covering it up or it is not in view, i.e. it is outside the currently view-able area.

Try this

from selenium.webdriver.common.action_chains import ActionChains

button = driver.find_element_by_class_name(u"infoDismiss")
driver.implicitly_wait(10)
ActionChains(driver).move_to_element(button).click(button).perform()

Passing javascript variable to html textbox

This was a problem for me, too. One reason for doing this (in my case) was that I needed to convert a client-side event (a javascript variable being modified) to a server-side variable (for that variable to be used in php). Hence populating a form with a javascript variable (eg a sessionStorage key/value) and converting it to a $_POST variable.

<form name='formName'>
<input name='inputName'>
</form>

<script>
document.formName.inputName.value=var
</script>

WPF chart controls

Visifire supports wide range of 2D and 3D charts with zooming and panning functionality.

Visifire Line chart with zooming

Full Disclosure: I have been involved in the development of Visifire.

Unused arguments in R

One approach (which I can't imagine is good programming practice) is to add the ... which is traditionally used to pass arguments specified in one function to another.

> multiply <- function(a,b) a*b
> multiply(a = 2,b = 4,c = 8)
Error in multiply(a = 2, b = 4, c = 8) : unused argument(s) (c = 8)
> multiply2 <- function(a,b,...) a*b
> multiply2(a = 2,b = 4,c = 8)
[1] 8

You can read more about ... is intended to be used here

CSS grid wrapping

You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Enter image description here

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Enter image description here

String replace a Backslash

s.replaceAll ("\\\\", "");

You need to mask a backslash in your source, and for regex, you need to mask it again, so for every backslash you need two, which ends in 4.

But

s = "http://www.example.com\\/value";

needs two backslashes in source as well.

Can't connect to MySQL server error 111

111 means connection refused, which in turn means that your mysqld only listens to the localhost interface.

To alter it you may want to look at the bind-address value in the mysqld section of your my.cnf file.

Angular2 equivalent of $document.ready()

You can fire an event yourself in ngOnInit() of your Angular root component and then listen for this event outside of Angular.

This is Dart code (I don't know TypeScript) but should't be to hard to translate

@Component(selector: 'app-element')
@View(
    templateUrl: 'app_element.html',
)
class AppElement implements OnInit {
  ElementRef elementRef;
  AppElement(this.elementRef);

  void ngOnInit() {
    DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
  }
}

Delete all data in SQL Server database

It is usually much faster to script out all the objects in the database, and create an empty one, that to delete from or truncate tables.

How to check if a string in Python is in ASCII?

A sting (str-type) in Python is a series of bytes. There is no way of telling just from looking at the string whether this series of bytes represent an ascii string, a string in a 8-bit charset like ISO-8859-1 or a string encoded with UTF-8 or UTF-16 or whatever.

However if you know the encoding used, then you can decode the str into a unicode string and then use a regular expression (or a loop) to check if it contains characters outside of the range you are concerned about.

How to show multiline text in a table cell

Hi I needed to do the same thing! Don't ask why but I was generating a html using python and needed a way to loop through items in a list and have each item take on a row of its own WITHIN A SINGLE CELL of a table.

I found that the br tag worked well for me. For example:

<!DOCTYPE html>
<HTML>
    <HEAD>
        <TITLE></TITLE>
    </HEAD>
    <BODY>
  <TABLE>
            <TR>
                <TD>
                    item 1 <BR>
                    item 2 <BR>
                    item 3 <BR>
                    item 4 <BR>
                </TD>
            </TR>
        </TABLE>
  </BODY>

This will produce the output that I wanted.

How to fix committing to the wrong Git branch?

If you already pushed your changes, you will need to force your next push after resetting the HEAD.

git reset --hard HEAD^
git merge COMMIT_SHA1
git push --force

Warning: a hard reset will undo any uncommitted modifications in your working copy, while a force push will completely overwrite the state of the remote branch with the current state of the local branch.

Just in case, on Windows (using the Windows command line, not Bash) it's actually four ^^^^ instead of one, so it's

git reset --hard HEAD^^^^

How do I find the time difference between two datetime objects in python?

New at Python 2.7 is the timedelta instance method .total_seconds(). From the Python docs, this is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6.

Reference: http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds

>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds

How to sort a NSArray alphabetically?

Another easy method to sort an array of strings consists by using the NSString description property this way:

NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES];
arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]];

C# declare empty string array

Arrays' constructors are different. Here are some ways to make an empty string array:

var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()

(sorry, on mobile)

How to pass prepareForSegue: an object

I've implemented a library with a category on UIViewController that simplifies this operation. Basically, you set the parameters you want to pass over in a NSDictionary associated to the UI item that is performing the segue. It works with manual segues too.

For example, you can do

[self performSegueWithIdentifier:@"yourIdentifier" parameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

for a manual segue or create a button with a segue and use

[button setSegueParameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

If destination view controller is not key-value coding compliant for a key, nothing happens. It works with key-values too (useful for unwind segues). Check it out here https://github.com/stefanomondino/SMQuickSegue

Hadoop: «ERROR : JAVA_HOME is not set»

You can add in your .bashrc file:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

Invalid column name sql error

Code To insert Data in Access Db using c#

Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace access_db_csharp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   public SqlConnection con = new SqlConnection(@"Place Your connection string");
            
           private void Savebutton_Click(object sender, EventArgs e)
    {
         SqlCommand cmd = new SqlCommand("insert into  Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
                cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
                cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
                cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
                cmd.ExecuteNonQuery();

                }

    private void Form1_Load(object sender, EventArgs e)
    {
        con.ConnectionString = connectionstring;
        con.Open();
    }
}
}

Python glob multiple filetypes

files = glob.glob('*.txt')
files.extend(glob.glob('*.dat'))

How to trim white space from all elements in array?

In Java 8, Arrays.parallelSetAll seems ready made for this purpose:

import java.util.Arrays;

Arrays.parallelSetAll(array, (i) -> array[i].trim());

This will modify the original array in place, replacing each element with the result of the lambda expression.

Select values of checkbox group with jQuery

Use .map() (adapted from the example at http://api.jquery.com/map/):

var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
    return $(domElement).val();
});

The right way of setting <a href=""> when it's a local file

Try swapping your colon : for a bar |. that should do it

<a href="file://C|/path/to/file/file.html">Link Anchor</a>

SVN upgrade working copy

You can upgrade to Subversion 1.7. In order to update to Subversion 1.7 you have to launch existing project in Xcode 5 or above. This will prompt an warning ‘The working copy ProjectName should be upgraded to Subversion 1.7’ (shown in below screenshot).

Screenshot for warning

You should select ‘Upgrade’ button to upgrade to Subversion 1.7. This will take a bit of time.

If you are using terminal then you can upgrade to Subversion 1.7 by running below command in your project directory: svn upgrade

Note that once you have upgraded to Subversion 1.7 you cannot go back to Subversion 1.6.

Refer Apple docs for more details.

What is the difference between background and background-color

background is the shortcut for background-color and few other background related stuffs as below:

background-color
background-image
background-repeat
background-attachment
background-position 

Read the statement below from W3C:

Background - Shorthand property

To shorten the code, it is also possible to specify all the background properties in one single property. This is called a shorthand property.

The shorthand property for background is background:

body {
  background: white url("img_tree.png") no-repeat right top;
}

When using the shorthand property the order of the property values is:

background-color
background-image
background-repeat
background-attachment
background-position

It does not matter if one of the property values is missing, as long as the other ones are in this order.

LISTAGG function: "result of string concatenation is too long"

A new feature added in 12cR2 is the ON OVERFLOW clause of LISTAGG. The query including this clause would look like:

SELECT pid, LISTAGG(Desc, ' ' ON OVERFLOW TRUNCATE ) WITHIN GROUP (ORDER BY seq) AS desc
FROM B GROUP BY pid;

The above will restrict the output to 4000 characters but will not throw the ORA-01489 error.

These are some of the additional options of ON OVERFLOW clause:

  • ON OVERFLOW TRUNCATE 'Contd..' : This will display 'Contd..' at the end of string (Default is ... )
  • ON OVERFLOW TRUNCATE '' : This will display the 4000 characters without any terminating string.
  • ON OVERFLOW TRUNCATE WITH COUNT : This will display the total number of characters at the end after the terminating characters. Eg:- '...(5512)'
  • ON OVERFLOW ERROR : If you expect the LISTAGG to fail with the ORA-01489 error ( Which is default anyway ).

LISTAGG Enhancements in 12c R2

Bad Gateway 502 error with Apache mod_proxy and Tomcat

So, answering my own question here. We ultimately determined that we were seeing 502 and 503 errors in the load balancer due to Tomcat threads timing out. In the short term we increased the timeout. In the longer term, we fixed the app problems that were causing the timeouts in the first place. Why Tomcat timeouts were being perceived as 502 and 503 errors at the load balancer is still a bit of a mystery.

Working Copy Locked

I have experienced the same issues as you described. It appears to be a bug on Tortoise 1.7.3. I have reverted back to 1.7.2, executed a cleanup and an update. Now my SVN/Tortoise is working fine again

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

Why does modulus division (%) only work with integers?

I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

How to add text at the end of each line in Vim?

I have <M-DOWN>(alt down arrow) mapped to <DOWN>. so that I can repeat the last command on a series of lines very quickly. with this mapping I can:

A,<ESC>

And then hold alt while pressing down repeatedly to append the comma to the end of each line.
This works well for me because it allows very good control over what lines do and do not get the change.
(I also have the other arrows mapped similarly to allow for easy repeating of .)

Here's the mapping line to paste into your vimrc:

map <M-DOWN> <DOWN>.

Send and receive messages through NSNotificationCenter in Objective-C?

This one helped me:

// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(showMainMenu:) 
                                                 name:@"loginComplete" object:nil];


// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginComplete" object:nil];


// the function specified in the same class where we defined the addObserver
- (void)showMainMenu:(NSNotification *)note {
    NSLog(@"Received Notification - Someone seems to have logged in"); 
}

Source: http://www.smipple.net/snippet/Sounden/Simple%20NSNotificationCenter%20example

How to vertically align text with icon font?

vertical-align can take a unit value so you can resort to that when needed:

{
  display:inline-block;
  vertical-align: 5px;
}

{
  display:inline-block;
  vertical-align: -5px;
}

How do I declare a namespace in JavaScript?

We can use it independently in this way:

var A = A|| {};
A.B = {};

A.B = {
    itemOne: null,
    itemTwo: null,
};

A.B.itemOne = function () {
    //..
}

A.B.itemTwo = function () {
    //..
}

Passing a variable from node.js to html

What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:

  1. npm install --save pug - to add it to the project and package.json file
  2. app.set('view engine', 'pug'); - register it as a view engine in express
  3. create a ./views folder and add a simple .pug file like so:
html
  head
    title= title
  body
    h1= message

note that the spacing is very important!

  1. create a route that returns the processed html:
app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});
});

This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html

For more info on pug you can also check: https://github.com/pugjs/pug

Handling Enter Key in Vue.js

In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:

https://vuejs.org/v2/guide/events.html#Key-Modifiers

I leave a very simple example:

_x000D_
_x000D_
var vm = new Vue({_x000D_
  el: '#app',_x000D_
  data: {msg: ''},_x000D_
  methods: {_x000D_
    onEnter: function() {_x000D_
       this.msg = 'on enter event';_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/vue"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input v-on:keyup.enter="onEnter" />_x000D_
  <h1>{{ msg }}</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good luck

Can HTML be embedded inside PHP "if" statement?

So if condition equals the value you want then the php document will run "include" and include will add that document to the current window for example:

`

<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>

`

"Strict Standards: Only variables should be passed by reference" error

array_shift the only parameter is an array passed by reference. The return value of explode(".", $value) does not have any reference. Hence the error.

You should store the return value to a variable first.

    $arr = explode(".", $value);
    $extension = strtolower(array_pop($arr));   
    $fileName = array_shift($arr);

From PHP.net

The following things can be passed by reference:

- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- [References returned from functions][2]

No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Different version similar to the one offered by Maxim Shoustin

I liked the answer but the part that bothered me was the use of <script id="..."> as a container for the modal's template.

I wanted to place the modal's template in a hidden <div> and bind the inner html with a scope variable called modal_html_template mainly because i think it more correct (and more comfortable to process in WebStorm/PyCharm) to place the template's html inside a <div> instead of <script id="...">

this variable will be used when calling $modal({... 'template': $scope.modal_html_template, ...})

in order to bind the inner html, i created inner-html-bind which is a simple directive

check out the example plunker

<div ng-controller="ModalDemoCtrl">

    <div inner-html-bind inner-html="modal_html_template" class="hidden">
        <div class="modal-header">
            <h3>I'm a modal!</h3>
        </div>
        <div class="modal-body">
            <ul>
                <li ng-repeat="item in items">
                    <a ng-click="selected.item = item">{{ item }}</a>
                </li>
            </ul>
            Selected: <b>{{ selected.item }}</b>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </div>

    <button class="btn" ng-click="open()">Open me!</button>
    <div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>

inner-html-bind directive:

app.directive('innerHtmlBind', function() {
  return {
    restrict: 'A',
    scope: {
      inner_html: '=innerHtml'
    },
    link: function(scope, element, attrs) {
      scope.inner_html = element.html();
    }
  }
});

How to make type="number" to positive numbers only

You can use the following to make type="number" accept positive numbers only:

input type="number" step="1" pattern="\d+"

Setting the User-Agent header for a WebClient request

You can check the WebClient documentation for a C# sample that adds a User-Agent to your WebClient and here for a sample for Windows Phone.

This is the sample for C#:

WebClient client = new WebClient ();

// Add a user agent header in case the 
// requested URI contains a query.

client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; " + 
                                  "Windows NT 5.2; .NET CLR 1.0.3705;)");

This is a sample for Windows Phone (Silverlight):

request.Headers["UserAgent"] = "appname";
// OR
request.UserAgent = "appname";

Rails 4 Authenticity Token

Add authenticity_token: true to the form tag

Initialising an array of fixed size in python

Do this:

>>> d = [ [ None for y in range( 2 ) ] for x in range( 2 ) ]
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [None, None]]

The other solutions will lead to this kind of problem:

>>> d = [ [ None ] * 2 ] * 2
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [1, None]]

How to get the xml node value in string

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    Console.WriteLine(n[0].InnerText); //Will output '08:29:57'
}

or you could wrap in foreach loop to print each value

XmlDocument d = new XmlDocument();
d.Load(@"D:\Work_Time_Calculator\10-07-2013.xml");
XmlNodeList n = d.GetElementsByTagName("Short_Fall");
if(n != null) {
    foreach(XmlNode curr in n) {
        Console.WriteLine(curr.InnerText);
    }
}

Using an integer as a key in an associative array in JavaScript

As people say, JavaScript will convert a string of number to integer, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.

You can create your object:

var object = {};

And add the values as array works:

object[1] = value;
object[2] = value;

This will give you:

{
  '1': value,
  '2': value
}

After that you can access it like an array in other languages getting the key:

for(key in object)
{
   value = object[key] ;
}

I have tested and works.

How to clear an ImageView in Android?

I know this is old, but I was able to accomplish this with

viewToUse.setImageResource(0);

Doesn't seem like it should work, but I tried it on a whim, and it worked perfectly.

Set Session variable using javascript in PHP

Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.

S3 limit to objects in a bucket

It looks like the limit has changed. You can store 5TB for a single object.

The total volume of data and number of objects you can store are unlimited. Individual Amazon S3 objects can range in size from a minimum of 0 bytes to a maximum of 5 terabytes. The largest object that can be uploaded in a single PUT is 5 gigabytes. For objects larger than 100 megabytes, customers should consider using the Multipart Upload capability.

http://aws.amazon.com/s3/faqs/#How_much_data_can_I_store

How do you store Java objects in HttpSession?

You are not adding the object to the session, instead you are adding it to the request.
What you need is:

HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);

In Servlets you have 4 scopes where you can store data.

  1. Application
  2. Session
  3. Request
  4. Page

Make sure you understand these. For more look here

html5 input for money/currency

Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.

_x000D_
_x000D_
span.gbp {_x000D_
    float: left;_x000D_
    text-align: left;_x000D_
}_x000D_
_x000D_
span.gbp::before {_x000D_
    float: left;_x000D_
    content: "\00a3"; /* £ */_x000D_
    padding: 3px 4px 3px 3px;_x000D_
}_x000D_
_x000D_
span.gbp input {_x000D_
     width: 280px !important;_x000D_
}
_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
    <input type="number" placeholder="Enter whole GBP (&pound;) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.

I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?

How to order citations by appearance using BibTeX?

Add this if you want the number of citations to appear in order in the document they will only be unsorted in the reference page:

\bibliographystyle{unsrt}

How to send HTML-formatted email?

Setting isBodyHtml to true allows you to use HTML tags in the message body:

msg = new MailMessage("[email protected]",
                "[email protected]", "Message from PSSP System",
                "This email sent by the PSSP system<br />" +
                "<b>this is bold text!</b>");

msg.IsBodyHtml = true;

WCF error - There was no endpoint listening at

I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.

How can I use modulo operator (%) in JavaScript?

It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:

10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.

Apparently it is not the same as the modulo operator entirely.

GET URL parameter in PHP

As Alvaro said, $_GET is not a function but an array containing the parameters So you can retrieve one element from that array using

<?php
$link = $_GET['link'];
echo $link;
?>

Expected OP:

www.google.com

What are Runtime.getRuntime().totalMemory() and freeMemory()?

JVM heap size can be growable and shrinkable by the Garbage-Collection mechanism. But, it can't allocate over maximum memory size: Runtime.maxMemory. This is the meaning of maximum memory. Total memory means the allocated heap size. And free memory means the available size in total memory.

example) java -Xms20M -Xmn10M -Xmx50M ~~~. This means that jvm should allocate heap 20M on start(ms). In this case, total memory is 20M. free memory is 20M-used size. If more heap is needed, JVM allocate more but can't over 50M(mx). In the case of maximum, total memory is 50M, and free size is 50M-used size. As for minumum size(mn), if heap is not used much, jvm can shrink heap size to 10M.

This mechanism is for efficiency of memory. If small java program run on huge fixed size heap memory, so much memory may be wasteful.