Programs & Examples On #K

K is an array processing language used in the Kdb database

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

I figured out myself.

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

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

Monitoring the Full Disclosure mailinglist

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

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

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

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

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

You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.

You will probably also need the .classpath file in the project directory that contains the test class.

Like the run configurations, they're XML files (even if they don't have an xml extension).

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

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

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

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

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

I am receiving warning in Facebook Application using PHP SDK

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

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

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

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

How much should a function trust another function

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

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

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

PHP array value passes to next row

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

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

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

programming a servo thru a barometer

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

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

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

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

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

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

need to add a class to an element

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

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

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

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

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

Uninitialized Constant MessagesController

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

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

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

rails g migration ChangeMessagesToMessage 

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

rake db:migrate 

And your app should be fine since then.

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

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

enter image description here enter image description here

How to implement a simple scenario the OO way

The Chapter object should have reference to the book it came from so I would suggest something like chapter.getBook().getTitle();

Your database table structure should have a books table and a chapters table with columns like:

books

  • id
  • book specific info
  • etc

chapters

  • id
  • book_id
  • chapter specific info
  • etc

Then to reduce the number of queries use a join table in your search query.

Embed ruby within URL : Middleman Blog

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

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

How to make a variable accessible outside a function?

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

How to use a global array in C#?

Your class shoud look something like this:

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

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

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

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

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

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

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

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

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

How can I tell if an algorithm is efficient?

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

Better solution without exluding fields from Binding

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

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

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

How to correctly write async method?

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

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

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

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

this in equals method

this is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.

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

I would suggest the following:

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

Titlecase all entries into a form_for text field

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

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

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


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

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

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

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

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

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

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

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

How to do perspective fixing?

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

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

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

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.

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

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

This will be a JRE and JDK package.

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

Passing multiple values for same variable in stored procedure

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

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

Gradle - Move a folder from ABC to XYZ

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

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

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

Implement specialization in ER diagram

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

concat yesterdays date with a specific time

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

should work.

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

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

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

or

if 'List contents' in UserInput: 

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

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

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

I think you missed a equal sign at:

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

Change to:

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

Accessing AppDelegate from framework?

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

Empty brackets '[]' appearing when using .where

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

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

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

Xml Parsing in C#

First add an Enrty and Category class:

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

Then use LINQ to XML

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

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

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)

It's really a matter of opinion. In your example, System.out.println(5) would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.

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.

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

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

Do this for each date parameter:

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

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

How to create a showdown.js markdown extension

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

EDIT

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

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

I submitted a pull request to update this.

Difference between opening a file in binary vs text

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


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

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

And in §7.19.3/2

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

About use of fseek, in §7.19.9.2/4:

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

About use of ftell, in §17.19.9.4:

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

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

Parse error: syntax error, unexpected [

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

Please help me convert this script to a simple image slider

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

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

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

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

CSS:

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

JavaScript:

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

http://jsfiddle.net/RmF57/

java doesn't run if structure inside of onclick listener

both your conditions are the same:

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

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Autoresize View When SubViews are Added

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

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

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

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 can offer you a jquery solution

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

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

add this after </ul>

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

Warp \ bend effect on a UIView?

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

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

Why there is this "clear" class before footer?

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:

Calling another method java GUI

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

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

Use NSInteger as array index

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

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

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

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

Does this give you a hint?

Summing radio input values

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

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

EDIT: This code works for me

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

Removing "http://" from a string

$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0); 

This would remove everything before the '//'.

EDIT

This one is tested. Using strrpos() instead or strpos().

Zipping a file in bash fails

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

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

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

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

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

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

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

is it possible to add colors to python output?

IDLE's console does not support ANSI escape sequences, or any other form of escapes for coloring your output.

You can learn how to talk to IDLE's console directly instead of just treating it like normal stdout and printing to it (which is how it does things like color-coding your syntax), but that's pretty complicated. The idle documentation just tells you the basics of using IDLE itself, and its idlelib library has no documentation (well, there is a single line of documentation—"(New in 2.3) Support library for the IDLE development environment."—if you know where to find it, but that isn't very helpful). So, you need to either read the source, or do a whole lot of trial and error, to even get started.


Alternatively, you can run your script from the command line instead of from IDLE, in which case you can use whatever escape sequences your terminal handles. Most modern terminals will handle at least basic 16/8-color ANSI. Many will handle 16/16, or the expanded xterm-256 color sequences, or even full 24-bit colors. (I believe gnome-terminal is the default for Ubuntu, and in its default configuration it will handle xterm-256, but that's really a question for SuperUser or AskUbuntu.)

Learning to read the termcap entries to know which codes to enter is complicated… but if you only care about a single console—or are willing to just assume "almost everything handles basic 16/8-color ANSI, and anything that doesn't, I don't care about", you can ignore that part and just hardcode them based on, e.g., this page.

Once you know what you want to emit, it's just a matter of putting the codes in the strings before printing them.

But there are libraries that can make this all easier for you. One really nice library, which comes built in with Python, is curses. This lets you take over the terminal and do a full-screen GUI, with colors and spinning cursors and anything else you want. It is a little heavy-weight for simple uses, of course. Other libraries can be found by searching PyPI, as usual.

Read input from a JOptionPane.showInputDialog box

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

if (operationType.equalsIgnoreCase("Q")) 

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

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

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

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

Cannot retrieve string(s) from preferences (settings)

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

strange error in my Animation Drawable

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

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

How to execute an action before close metro app WinJS

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

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

Two Page Login with Spring Security 3.2.x

There should be three pages here:

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

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

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

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

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

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

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

javascript, for loop defines a dynamic variable name

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

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

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

How 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?

Instead of adding the line breaks with nl2br() and then removing the line breaks with explode(), try using the line break character '\r' or '\n' or '\r\n'.

<?php     $options= file_get_contents("employees.txt");     $options=explode("\n",$options);        // try \r as well.      foreach ($options as $singleOption){         echo "<option value='".$singleOption."'>".$singleOption."</option>";     }   ?> 

This could also fix the issue if the problem was due to Google Spreadsheets reading the line breaks.

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

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

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

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

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

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

Access And/Or exclusions

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

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

Querying date field in MongoDB with Mongoose

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

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

Uploading into folder in FTP?

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

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

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.

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

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

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

Call japplet from jframe

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

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

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

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

Updated

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

Within the constructor of GalzyTable2 you are doing...

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

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

Case in point...

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

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

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

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

Take the time to read through Creating a GUI with Swing

Updated with example

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

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

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

FragmentActivity to Fragment

first of all;

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

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

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

here is an example:

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

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


for the FragmentActivity part:

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

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

as for the inflation part

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


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

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

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

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

Real time face detection OpenCV, Python

Your line:

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

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

Try

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

vagrant primary box defined but commands still run against all boxes

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

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

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

500 Error on AppHarbor but downloaded build works on my machine

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

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

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

Are these methods thread safe?

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

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

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

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

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

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

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

Drag and drop menuitems

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

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Rails 2.3.4 Persisting Model on Validation Failure

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

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

From the docs:

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

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

Edit: Further reading led me here:

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

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

php & mysql query not echoing in html with tags?

<td class="first"> <?php echo $proxy ?> </td> is inside a literal string that you are echoing. End the string, or concatenate it correctly:

<td class="first">' . $proxy . '</td>

Comparing two joda DateTime instances

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

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

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

How do I show a message in the foreach loop?

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

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

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

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

This is version problem, install the right dependant version

npm uninstall node-sass
npm install [email protected]

Target class controller does not exist - Laravel 8

You are using Laravel 8. In a fresh install of Laravel 8, there is no namespace prefix being applied to your route groups that your routes are loaded into.

"In previous releases of Laravel, the RouteServiceProvider contained a $namespace property. This property's value would automatically be prefixed onto controller route definitions and calls to the action helper / URL::action method. In Laravel 8.x, this property is null by default. This means that no automatic namespace prefixing will be done by Laravel." Laravel 8.x Docs - Release Notes

You would have to use the Fully Qualified Class Name for your Controllers when referring to them in your routes when not using the namespace prefixing.

use App\Http\Controllers\UserController;

Route::get('/users', [UserController::class, 'index']);
// or
Route::get('/users', 'App\Http\Controllers\UserController@index');

If you prefer the old way:

App\Providers\RouteServiceProvider:

public function boot()
{
    ...

    Route::prefix('api')
        ->middleware('api')
        ->namespace('App\Http\Controllers') // <---------
        ->group(base_path('routes/api.php'));

    ...
}

Do this for any route groups you want a declared namespace for.

The $namespace property:

Though there is a mention of a $namespace property to be set on your RouteServiceProvider in the Release notes and commented in your RouteServiceProvider this does not have any effect on your routes. It is currently only for adding a namespace prefix for generating URLs to actions. So you can set this variable, but it by itself won't add these namespace prefixes, you would still have to make sure you would be using this variable when adding the namespace to the route groups.

This information is now in the Upgrade Guide

Laravel 8.x Docs - Upgrade Guide - Routing

With what the Upgrade Guide is showing the important part is that you are defining a namespace on your routes groups. Setting the $namespace variable by itself only helps in generating URLs to actions.

Again, and I can't stress this enough, the important part is setting the namespace for the route groups, which they just happen to be doing by referencing the member variable $namespace directly in the example.

Update:

If you have installed a fresh copy of Laravel 8 since version 8.0.2 of laravel/laravel you can uncomment the protected $namespace member variable in the RouteServiceProvider to go back to the old way, as the route groups are setup to use this member variable for the namespace for the groups.

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

The only reason uncommenting that would add the namespace prefix to the Controllers assigned to the routes is because the route groups are setup to use this variable as the namespace:

...
->namespace($this->namespace)
...

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

In you xxx.framework podspec file add follow config avoid pod package contains arm64 similator archs

s.pod_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }
s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' }

iPhone is not available. Please reconnect the device

Developers who are using Xcode 11.5 and trying to install their app in iOS 13.6 device will also see this message. It's a very confusing message.

All you need to do is Download Device support files of iOS 13.6 from this link

filsv/iPhoneOSDeviceSupport

  • Close Xcode

  • Unzip and paste it in this location:

    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/

  • Reopen Xcode.

Now you can install the app on the iOS 13.6 device using Xcode 11.5.

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

That's because Chrome added support for source maps.

Go to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings.

Then, look for Sources, and disable the options: "Enable javascript source maps" "Enable CSS source maps"

If you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning.

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

This worked for me

Deactivate AdBlock.

Go to inspect -> settings gear -> Uncheck 'enable javascript source maps' and 'enable css source map'.

Refresh.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

The case when your Chrome is in the middle of its update also causes this exception. In my case chromedriver was already updated, while the chrome itself was v81 instead of v83.

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

Restarting your server may not work always. I have got this error when I imported MatFormFieldModule.

In app.module.ts, I have imported MatFormField instead of MatFormFieldModule which lead to this error.

Now change it and restart the server, Hope this answer helps you.

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

I've also faced this problem and figure out it by upgrading the react-scripts package from "react-scripts": "3.x.x" to "react-scripts": "^3.4.1" (or the latest available version).

  1. Delete node_modules\ folder
  2. Delete package-lock.json file
  3. Rewrite the package.json file from "react-scripts": "3.x.x" to "react-scripts": "^3.4.1"
  4. Install node packages again npm i
  5. Now, start the project npm start

And it works!!

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

I had this problem but didn't have a version conflict in my package.json.

My package-lock.json was somehow out of sync with package json though. Deleting and regenerating it worked for me.

TS1086: An accessor cannot be declared in ambient context

The best way to overcome on this issue is that, just remove node_modules and package-lock.json file and further install npm with npm i it solved my problem

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

I solved this another way. First of all I installed cuda 10.1 toolkit from this link

Where i selected installer type(exe(local)) and installed 10.1 in custom mode means (without visual studio integration, NVIDIA PhysX because previously I installed CUDA 10.2 so required dependencies were installed automatically)

After installation, From the Following Path (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin) , in my case, I copied 'cudart64_101.dll' file and pasted in (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin).

Then importing Tensorflow worked smoothly.

N.B. Sorry for Bad English

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

I add the following code to my pom.xml file. It solved my problem.

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

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

After using this command:

yarn global upgrade create-react-app

I then tried:

yarn create-react-app my-app but it didn't work for me.

This worked though:

npx 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

You don't need to downgrade you can:

Either disable undefined symbol diagnostics in the settings -- "intelephense.diagnostics.undefinedSymbols": false .

Or use an ide helper that adds stubs for laravel facades. See https://github.com/barryvdh/laravel-ide-helper

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

Switch to an older openssl package

brew switch openssl 1.0.2s

Or, depending on your exact system configuration, you may need to switch to a different version. Check the output of ls -al /usr/local/Cellar/openssl for the version number to switch to.

brew switch openssl 1.0.2q
# or
brew switch openssl 1.0.2r
# or 
brew switch openssl 1.0.2s
# or
brew switch openssl 1.0.2t
# etc...

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

npm install --silent

Seems to suppress the funding issue.

SyntaxError: Cannot use import statement outside a module

in the package.json write { "type": "module" }

it fixed my problem, I had the same problem

SameSite warning Chrome 77

I had to disable this in chrome://flags

enter image description here

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.

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

Just add .pack between the name and the extension in the <script> tag in src. i.e.:

<script src="name.pack.js">
// code here
</script>

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

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

JavaScript Cookie

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

JAVA Cookie (set proxy_cookie_path in Nginx)

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

Check result in Firefox enter image description here

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

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

I have run into this issue When I recently upgraded my IntelliJ version to 2020.3. I had to disable a plugin to solve this issue. The name of the plugin is Thrift Support.

Steps to disable the plugin is following:

  1. Open the Preferences of IntelliJ. You can do so by clicking on Command + , in mac.
  2. Navigate to plugins.
  3. Search for the Thrift Support plugin in the search window. Click on the tick box icon to deselect it.
  4. Click on the Apply icon.
  5. See this image for reference Disable_Thrift_support_plugin

For more detail please refer to this link java.lang.UnsupportedClassVersionError 2020.3 version intellij. I found this comment in the above link which has worked for me.

bin zhao commented 31 Dec 2020 08:00 @Lejia Chen @Tobias Schulmann Workflow My IDEA3.X didn't installed Erlang plugin, I disabled Thrift Support 1.4.0 and it worked. Both IDEA 3.0 and 3.1 have the same problem.

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

A PR with a fix has been merged in the metro repository. Now we just need to wait until the next release. For now the best option is to downgrade to NodeJS v12.10.0. As Brandon pointed out, modifying anything in node_modules/ isa really bad practice and will not be a final solution.

Why powershell does not run Angular commands?

Remove ng.ps1 from the directory C:\Users\%username%\AppData\Roaming\npm\ then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\

Server Discovery And Monitoring engine is deprecated

If your code includes createConnetion for some reason (In my case I'm using GridFsStorage), try adding the following to your code:

    options: {
        useUnifiedTopology: true,
    }

just after file, like this:

    const storage = new GridFsStorage({
    url: mongodbUrl,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err);
                }
                const filename = buf.toString('hex') + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'uploads'
                };
                resolve(fileInfo);
            });
        });
    },
    options: {
        useUnifiedTopology: true,
    }
})

If your case looks like mine, this will surely solve your issue. Regards

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

I know this might not be a complete or exact solution, but for those who are still facing issues even after doing what is given on this thread, check for your files in value folder. For me there was a typo and some missing values. Once i fixed them this error stopped.

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

Delete node_module directory and run below in command line

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

If still not working, try below

npm install webpack --save

Unable to allocate array with shape and data type

This is likely due to your system's overcommit handling mode.

In the default mode, 0,

Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slightly more memory in this mode. This is the default.

The exact heuristic used is not well explained here, but this is discussed more on Linux over commit heuristic and on this page.

You can check your current overcommit mode by running

$ cat /proc/sys/vm/overcommit_memory
0

In this case you're allocating

>>> 156816 * 36 * 53806 / 1024.0**3
282.8939827680588

~282 GB, and the kernel is saying well obviously there's no way I'm going to be able to commit that many physical pages to this, and it refuses the allocation.

If (as root) you run:

$ echo 1 > /proc/sys/vm/overcommit_memory

This will enable "always overcommit" mode, and you'll find that indeed the system will allow you to make the allocation no matter how large it is (within 64-bit memory addressing at least).

I tested this myself on a machine with 32 GB of RAM. With overcommit mode 0 I also got a MemoryError, but after changing it back to 1 it works:

>>> import numpy as np
>>> a = np.zeros((156816, 36, 53806), dtype='uint8')
>>> a.nbytes
303755101056

You can then go ahead and write to any location within the array, and the system will only allocate physical pages when you explicitly write to that page. So you can use this, with care, for sparse arrays.

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?

I don't believe the JavaScript solutions work anymore. I was doing it from within my notebook with:

    from IPython.display import display, HTML
    js = ('<script>function ConnectButton(){ '
           'console.log("Connect pushed"); '
           'document.querySelector("#connect").click()} '
           'setInterval(ConnectButton,3000);</script>')
    display(HTML(js))

When you first do a Run all (before the JavaScript or Python code has started), the console displays:

Connected to 
wss://colab.research.google.com/api/kernels/0e1ce105-0127-4758-90e48cf801ce01a3/channels?session_id=5d8...

However, ever time the JavaScript runs, you see the console.log portion, but the click portion simply gives:

Connect pushed

Uncaught TypeError: Cannot read property 'click' of null
 at ConnectButton (<anonymous>:1:92)

Others suggested the button name has changed to #colab-connect-button, but that gives same error.

After the runtime is started, the button is changed to show RAM/DISK, and a drop down is presented. Clicking on the drop down creates a new <DIV class=goog menu...> that was not shown in the DOM previously, with 2 options "Connect to hosted runtime" and "Connect to local runtime". If the console window is open and showing elements, you can see this DIV appear when you click the dropdown element. Simply moving the mouse focus between the two options in the new window that appears adds additional elements to the DOM, as soon as the mouse looses focus, they are removed from the DOM completely, even without clicking.

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

I use this:

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

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

If you use the optional property in your object:

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

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

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

dotnet ef not found in .NET Core 3

EDIT: If you are using a Dockerfile for deployments these are the steps you need to take to resolve this issue.

Change your Dockerfile to include the following:

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
ENV PATH $PATH:/root/.dotnet/tools
RUN dotnet tool install -g dotnet-ef --version 3.1.1

Also change your dotnet ef commands to be dotnet-ef

"Permission Denied" trying to run Python on Windows 10

Simple answer: replace python with PY everything will work as expected

Adding Git-Bash to the new Windows Terminal

This is the complete answer (GitBash + color scheme + icon + context menu)

1) Set default profile:

"globals" : 
{
    "defaultProfile" : "{00000000-0000-0000-0000-000000000001}",
    ...

2) Add GitBash profile

"profiles" : 
[
    {
        "guid": "{00000000-0000-0000-0000-000000000001}",
        "acrylicOpacity" : 0.75,
        "closeOnExit" : true,
        "colorScheme" : "GitBash",
        "commandline" : "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" --login -i -l",
        "cursorColor" : "#FFFFFF",
        "cursorShape" : "bar",
        "fontFace" : "Consolas",
        "fontSize" : 10,
        "historySize" : 9001,
        "icon" : "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico", 
        "name" : "GitBash",
        "padding" : "0, 0, 0, 0",
        "snapOnInput" : true,
        "startingDirectory" : "%USERPROFILE%",
        "useAcrylic" : false        
    },

3) Add GitBash color scheme

"schemes" : 
[
    {
        "background" : "#000000",
        "black" : "#0C0C0C",
        "blue" : "#6060ff",
        "brightBlack" : "#767676",
        "brightBlue" : "#3B78FF",
        "brightCyan" : "#61D6D6",
        "brightGreen" : "#16C60C",
        "brightPurple" : "#B4009E",
        "brightRed" : "#E74856",
        "brightWhite" : "#F2F2F2",
        "brightYellow" : "#F9F1A5",
        "cyan" : "#3A96DD",
        "foreground" : "#bfbfbf",
        "green" : "#00a400",
        "name" : "GitBash",
        "purple" : "#bf00bf",
        "red" : "#bf0000",
        "white" : "#ffffff",
        "yellow" : "#bfbf00",
        "grey" : "#bfbfbf"
    },  

4) To add a right-click context menu "Windows Terminal Here"

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt]
@="Windows terminal here"
"Icon"="C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\{YOUR_ICONS_FOLDER}\\icon.ico"

[HKEY_CLASSES_ROOT\Directory\Background\shell\wt\command]
@="\"C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\wt.exe\""
  • replace {YOUR_WINDOWS_USERNAME}
  • create icon folder, put the icon there and replace {YOUR_ICONS_FOLDER}
  • save this in a whatever_filename.reg file and run it.

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

Try this in angular 8.0:

@ViewChild('result',{static: false}) resultElement: ElementRef;

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

For me , the error was calling the function useState outside the function default exported

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

I too had this issue in PyCharm. This issue is because you don't have tkinter module in your machine.

To install follow the steps given below (select your appropriate os)

For ubuntu users

 sudo apt-get install python-tk

or

 sudo apt-get install python3-tk

For Centos users

 sudo yum install python-tkinter

or

 sudo yum install python3-tkinter

For Windows, use pip to install tk

After installing tkinter restart your Pycharm and run your code, it will work

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

This was what I did to solve my related problem

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

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

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

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

  1. Opened package.json
  2. Changed "@angular-devkit/build-angular": "^0.800.0" to "@angular-devkit/build-angular": "^0.10.0" or changed Changing from "@angular-devkit/build-angular": "^0.802.1" to "@angular-devkit/build-angular": "^0.13.9"
  3. Run npm install
  4. Run ng serve

The original version can be diferent, but is necessary change it at 0.10.0 or 0.13.9 version that fix the problem

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

Swift 5

Two ways to switch dark to light mode:

1- info.plist

    <key>UIUserInterfaceStyle</key>
    <string>Light</string>

2- Programmatically or Runtime

  @IBAction private func switchToDark(_ sender: UIButton){
        UIApplication.shared.windows.forEach { window in
            //here you can switch between the dark and light
            window.overrideUserInterfaceStyle = .dark
        }
    }

Make a VStack fill the width of the screen in SwiftUI

You can do it by using GeometryReader

GeometryReader

Code:

struct ContentView : View {
    var body: some View {
        GeometryReader { geometry in
            VStack {
               Text("Turtle Rock").frame(width: geometry.size.width, height: geometry.size.height, alignment: .topLeading).background(Color.red)
            }
        }
    }
}

Your output like:

enter image description here

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

CORS headers should be sent from the server. If you use PHP it will be like this:

header('Access-Control-Allow-Origin: your-host');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: your-methods like POST,GET');
header('Access-Control-Allow-Headers: content-type or other');
header('Content-Type: application/json');

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

You can Simply Change Background Color of a View:

var body : some View{


    VStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

and You can also use ZStack :

var body : some View{


    ZStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

Presenting modal in iOS 13 fullscreen

Here is an easy solution without coding a single line.

  • Select View Controller in Storyboard
  • Select attribute Inspector
  • Set presentation "Automatic" to "FullScreen" as per below image

This change makes iPad app behavior as expected otherwise the new screen is displaying in the center of the screen as a popup.

enter image description here

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

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

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

I did this change in package.json file, then it works.

"@angular-devkit/build-angular": "^0.803.23"

to

"@angular-devkit/build-angular": "^0.13.9"

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

For .NET CORE 3.1

I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them

What i mean is:

change this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseHttpsRedirection();  

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

      ...

     }

to this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseHttpsRedirection(); 

      ...

     }

By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.

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?

For me I changed in the parent tag of the pom.xml and it solved it change 2.1.5 to 2.1.4 then Maven-> Update Project

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

Here's a trick to force imdb.load_data to allow pickle by, in your notebook, replacing this line:

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

by this:

import numpy as np
# save np.load
np_load_old = np.load

# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)

# call load_data with allow_pickle implicitly set to true
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

# restore np.load for future normal usage
np.load = np_load_old

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'

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

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

In JSX, the lower-case tag name is considered as html native component. In order to react recognise the function as React component, need to Capitalized the name.

Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.

https://reactjs.org/docs/jsx-in-depth.html#html-tags-vs.-react-components

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

Well if you want to look into this differently, you just need to know what are options does the React has that non exhaustive-deps? One of the reason you should not use a closure function inside the effect is on every render, it will be re-created/destroy again.

So there are multiple React methods in hooks that is considered stable and non-exhausted where you do not have to apply to the useEffect dependencies, and in turn will not break the rules engagement of react-hooks/exhaustive-deps. For example the second return variable of useReducer or useState which is a function.

const [,dispatch] = useReducer(reducer, {});

useEffect(() => {
    dispatch(); // non-exhausted, eslint won't nag about this
}, []);

So in turn you can have all your external dependencies together with your current dependencies coexist together within your reducer function.

const [,dispatch] = useReducer((current, update) => {
    const { foobar } = update;
    // logic

    return { ...current, ...update };
}), {});

const [foobar, setFoobar] = useState(false);

useEffect(() => {
    dispatch({ foobar }); // non-exhausted `dispatch` function
}, [foobar]);

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

I solved this issue by using sudo ie

sudo yarn start

or

sudo npm start

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

How about reinstalling the node module? Go to the root directory of the project and remove the current node modules and install again.

These are the commands : rm -rf node_modules npm install

OR

npm uninstall -g react-native-cli and

npm install -g react-native-cli

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

Cracked it. Just @Damnum steps and then follow the path to run xcode. Bad way but running like a charm.

Double click to /Applications/Xcode102.app/Contents/MacOS/Xcode

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

In Some Cases You Might Want To Close the port Of React-native bundler and Rerun the App With the same process

1.sudo kill -9 $(sudo lsof -t -i:9001)

2.npm start inside the project

3. react-native run-android

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

ls /bin/python*

Identify the highest version of python listed. If the highest version is something like python2.7 then install python2-pip If its something like python3.8 then install python3-pip

Example for python3.8:

sudo apt-get install python3-pip

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

Updating Anaconda fails: Environment Not Writable Error

this line of code on your terminal, solves the problem

$ sudo chown -R $USER:$USER anaconda 3

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

Try this.

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

setValue() and patchValue()

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

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

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

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

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

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

You must link an event in your onClick. Additionally, the click function must receive the event. See the example

export default function Component(props) {

    function clickEvent (event, variable){
        console.log(variable);
    }

    return (
        <div>
            <IconButton
                key="close"
                aria-label="Close"
                color="inherit"
                onClick={e => clickEvent(e, 10)}
            >
        </div>
    )
}

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

I had the same error, but it was caused by the package manager process port being already used (port 8081).

To fix, I just ran the react-native by specifying a different port, see below.

react-native run-ios --port 8090

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

I just ran into the same kind of error using RSelenium::rsDriver()'s default chromever = "latest" setting which resulted in the failed attempt to combine chromedriver 75.0.3770.8 with latest google-chrome-stable 74.0.3729.157:

session not created: This version of ChromeDriver only supports Chrome version 75

Since this obviously seems to be a recurring and pretty annoying issue, I have come up with the following workaround to always use the latest compatible ChromeDriver version:

rD <- RSelenium::rsDriver(browser = "chrome",
                          chromever =
                                  system2(command = "google-chrome-stable",
                                          args = "--version",
                                          stdout = TRUE,
                                          stderr = TRUE) %>%
                                  stringr::str_extract(pattern = "(?<=Chrome )\\d+\\.\\d+\\.\\d+\\.") %>%
                                  magrittr::extract(!is.na(.)) %>%
                                  stringr::str_replace_all(pattern = "\\.",
                                                           replacement = "\\\\.") %>%
                                  paste0("^",  .) %>%
                                  stringr::str_subset(string =
                                                              binman::list_versions(appname = "chromedriver") %>%
                                                              dplyr::last()) %>%
                                  as.numeric_version() %>%
                                  max() %>%
                                  as.character())

The above code is only tested under Linux and makes use of some tidyverse packages (install them beforehand or rewrite it in base R). For other operating systems you might have to adapt it a bit, particularly replace command = "google-chrome-stable" with the system-specific command to launch Google Chrome:

  • On macOS it should be enough to replace command = "google-chrome-stable" with command = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".

  • On Windows a plattform-specific bug prevents us from calling the Google Chrome binary directly to get its version number. Instead do the following:

    rD <- RSelenium::rsDriver(browser = "chrome",
                              chromever =
                                system2(command = "wmic",
                                        args = 'datafile where name="C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe" get Version /value',
                                        stdout = TRUE,
                                        stderr = TRUE) %>%
                                stringr::str_extract(pattern = "(?<=Version=)\\d+\\.\\d+\\.\\d+\\.") %>%
                                magrittr::extract(!is.na(.)) %>%
                                stringr::str_replace_all(pattern = "\\.",
                                                         replacement = "\\\\.") %>%
                                paste0("^",  .) %>%
                                stringr::str_subset(string =
                                                            binman::list_versions(appname = "chromedriver") %>%
                                                            dplyr::last()) 
                                as.numeric_version() %>%
                                max() %>%
                                as.character())
    

Basically, the code just ensures the latest ChromeDriver version matching the major-minor-patch version number of the system's stable Google Chrome browser is passed as chromever argument. This procedure should adhere to the official ChromeDriver versioning scheme. Quote:

  • ChromeDriver uses the same version number scheme as Chrome (...)
  • Each version of ChromeDriver supports Chrome with matching major, minor, and build version numbers. For example, ChromeDriver 73.0.3683.20 supports all Chrome versions that start with 73.0.3683.

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

The easy way to fix this is to add this to your form.

{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT">

then the update method will be like this :

public function update(Request $request, $id)
{
    $project = Project::findOrFail($id);
    $project->name = $request->name;
    $project->description = $request->description;

    $post->save();
}

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

import tensorflow as tf
sess = tf.Session()

this code will show an Attribute error on version 2.x

to use version 1.x code in version 2.x

try this

import tensorflow.compat.v1 as tf
sess = tf.Session()

react hooks useEffect() cleanup for only componentWillUnmount?

you can use more than one useEffect

for example if my variable is data1 i can use all of this in my component

useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );

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

The easiest way I found is this:

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

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

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

How to use callback with useState hook in react

Another way to achieve this:

_x000D_
_x000D_
const [Name, setName] = useState({val:"", callback: null});_x000D_
React.useEffect(()=>{_x000D_
  console.log(Name)_x000D_
  const {callback} = Name;_x000D_
  callback && callback();_x000D_
}, [Name]);_x000D_
setName({val:'foo', callback: ()=>setName({val: 'then bar'})})
_x000D_
_x000D_
_x000D_

Cannot edit in read-only editor VS Code

If your code takes input from a user you can't just use output tab. You have to use any terminal as Jordan Stefanelli have said.

  1. just go to terminal tab and select powershell or default terminal
  2. type python Nameoffile.py
  3. you will be able to input

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

in my case i have used both npm install and yarn install that is why i got this issue so to solve this i have removed package-lock.json and node_modules and then i did

yarn install
cd ios
pod install

it worked for me

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?

I installed pip3 using

python3.7 -m pip install pip

But upon using pip3 to install other dependencies, it was using python3.6.
You can check the by typing pip3 --version

Hence, I used pip3 like this (stated in one of the above answers):

python3.7 -m pip install <module>

or use it like this:

python3.7 -m pip install -r requirements.txt

I made a bash alias for later use in ~/.bashrc file as alias pip3='python3.7 -m pip'. If you use alias, don't forget to source ~/.bashrc after making the changes and saving it.

Flutter Countdown Timer

Here is an example using Timer.periodic :

Countdown starts from 10 to 0 on button click :

import 'dart:async';

[...]

Timer _timer;
int _start = 10;

void startTimer() {
  const oneSec = const Duration(seconds: 1);
  _timer = new Timer.periodic(
    oneSec,
    (Timer timer) {
      if (_start == 0) {
        setState(() {
          timer.cancel();
        });
      } else {
        setState(() {
          _start--;
        });
      }
    },
  );
}

@override
void dispose() {
  _timer.cancel();
  super.dispose();
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_start")
      ],
    ),
  );
}

Result :

Flutter countdown timer example

You can also use the CountdownTimer class from the quiver.async library, usage is even simpler :

import 'package:quiver/async.dart';

[...]

int _start = 10;
int _current = 10;

void startTimer() {
  CountdownTimer countDownTimer = new CountdownTimer(
    new Duration(seconds: _start),
    new Duration(seconds: 1),
  );

  var sub = countDownTimer.listen(null);
  sub.onData((duration) {
    setState(() { _current = _start - duration.elapsed.inSeconds; });
  });

  sub.onDone(() {
    print("Done");
    sub.cancel();
  });
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_current")
      ],
    ),
  );
}

EDIT : For the question in comments about button click behavior

With the above code which uses Timer.periodic, a new timer will indeed be started on each button click, and all these timers will update the same _start variable, resulting in a faster decreasing counter.

There are multiple solutions to change this behavior, depending on what you want to achieve :

  • disable the button once clicked so that the user could not disturb the countdown anymore (maybe enable it back once timer is cancelled)
  • wrap the Timer.periodic creation with a non null condition so that clicking the button multiple times has no effect
if (_timer != null) {
  _timer = new Timer.periodic(...);
}
  • cancel the timer and reset the countdown if you want to restart the timer on each click :
if (_timer != null) {
  _timer.cancel();
  _start = 10;
}
_timer = new Timer.periodic(...);
  • if you want the button to act like a play/pause button :
if (_timer != null) {
  _timer.cancel();
  _timer = null;
} else {
  _timer = new Timer.periodic(...);
}

You could also use this official async package which provides a RestartableTimer class which extends from Timer and adds the reset method.

So just call _timer.reset(); on each button click.

Finally, Codepen now supports Flutter ! So here is a live example so that everyone can play with it : https://codepen.io/Yann39/pen/oNjrVOb

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

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

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

You can now use the non-null assertion operator that is here exactly for your use case.

It tells TypeScript that even though something looks like it could be null, it can trust you that it's not:

let name1:string = person.name!; 
//                            ^ note the exclamation mark here  

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

This error could also be because you are not subscribing to the Observable.

Example, instead of:

this.products = this.productService.getProducts();

do this:

   this.productService.getProducts().subscribe({
    next: products=>this.products = products,
    error: err=>this.errorMessage = err
   });

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

One thing that hasn't been pointed out, is that there is little to no difference between not having an active environment and and activating the base environment, if you just want to run applications from Conda's (Python's) scripts directory (as @DryLabRebel wants).

You can install and uninstall via conda and conda shows the base environment as active - which essentially it is:

> echo $Env:CONDA_DEFAULT_ENV
> conda env list
# conda environments:
#
base                  *  F:\scoop\apps\miniconda3\current

> conda activate
> echo $Env:CONDA_DEFAULT_ENV
base
> conda env list
# conda environments:
#
base                  *  F:\scoop\apps\miniconda3\current

Gradle: Could not determine java version from '11.0.2'

I've had the same issue. Upgrading to gradle 5.0 did the trick for me.

This link provides detailed steps on how install gradle 5.0: https://linuxize.com/post/how-to-install-gradle-on-ubuntu-18-04/

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

Global events are also deprecated.

Here's a patch, which fixes the browser and event issues:

--- jquery.fancybox-1.3.4.js.orig   2010-11-11 23:31:54.000000000 +0100
+++ jquery.fancybox-1.3.4.js    2013-03-22 23:25:29.996796800 +0100
@@ -26,7 +26,9 @@

        titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }),

-       isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
+       isIE = !+"\v1",
+       
+       isIE6 = isIE && window.XMLHttpRequest === undefined,

        /*
         * Private methods 
@@ -322,7 +324,7 @@
            loading.hide();

            if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
-               $.event.trigger('fancybox-cancel');
+               $('.fancybox-inline-tmp').trigger('fancybox-cancel');

                busy = false;
                return;
@@ -389,7 +391,7 @@
                        content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish);
                    };

-                   $.event.trigger('fancybox-change');
+                   $('.fancybox-inline-tmp').trigger('fancybox-change');

                    content
                        .empty()
@@ -612,7 +614,7 @@
            }

            if (currentOpts.type == 'iframe') {
-               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
+               $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + (isIE ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content);
            }

            wrap.show();
@@ -912,7 +914,7 @@

        busy = true;

-       $.event.trigger('fancybox-cancel');
+       $('.fancybox-inline-tmp').trigger('fancybox-cancel');

        _abort();

@@ -957,7 +959,7 @@
            title.empty().hide();
            wrap.hide();

-           $.event.trigger('fancybox-cleanup');
+           $('.fancybox-inline-tmp, select:not(#fancybox-tmp select)').trigger('fancybox-cleanup');

            content.empty();

Bootstrap full-width text-input within inline-form

have a look at something like this:

<form role="form">  
    <div class="row">
      <div class="col-xs-12">
        <div class="input-group input-group-lg">
            <input type="text" class="form-control" />
          <div class="input-group-btn">
            <button type="submit" class="btn">Search</button>
          </div><!-- /btn-group -->
        </div><!-- /input-group -->
      </div><!-- /.col-xs-12 -->
    </div><!-- /.row -->
</form>

http://jsfiddle.net/n6c7v/1/

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

But here's the rub, sometimes you can't or don't want to wait. For example I want to use the new support for RubyMotion which includes RubyMotion project structure support, setup of rake files, setup of configurations that are hooked to iOS Simulator etc.

RubyMine has all of these now, IDEA does not. So I would have to generate a RubyMotion project outside of IDEA, then setup an IDEA project and hook up to that source folder etc and God knows what else.

What JetBrains should do is have a licensing model that would allow me, with the purchase of IDEA to use any of other IDEs, as opposed to just relying on IDEAs plugins.

I would be willing to pay more for that i.e. say 50 bucks more for said flexibility.

The funny thing is, I was originally a RubyMine customer that upgraded to IDEA, because I did want that polyglot setup. Now I'm contemplating paying for the upgrade of RubyMine, just because I need to do RubyMotion now. Also there are other potential areas where this out of sync issue might bite me again . For example torque box workflow / deployment support.

JetBrains has good IDEs but I guess I'm a bit annoyed.

Less than or equal to

There is no => for if.
Use if %energy% GEQ %m2enc%

See if /? for some other details.

Java Date cut off time information

Might be a late response but here is a way to do it in one line without using any libraries:

new SimpleDateFormat("yyyy-MM-dd").parse(new SimpleDateFormat("yyyy-MM-dd").format(YOUR_TIMESTAMP))

Is it possible to get a history of queries made in postgres

pgBadger is another option - also listed here: https://github.com/dhamaniasad/awesome-postgres#utilities

Requires some additional setup in advance to capture the necessary data in the postgres logs though, see the official website.

Git: How to remove file from index without deleting files from any repository

Had the very same issue this week when I accidentally committed, then tried to remove a build file from a shared repository, and this:

http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html

has worked fine for me and not mentioned so far.

git update-index --assume-unchanged <file>

To remove the file you're interested in from version control, then use all your other commands as normal.

git update-index --no-assume-unchanged <file>

If you ever wanted to put it back in.

Edit: please see comments from Chris Johnsen and KPM, this only works locally and the file remains under version control for other users if they don't also do it. The accepted answer gives more complete/correct methods for dealing with this. Also some notes from the link if using this method:

Obviously there’s quite a few caveats that come into play with this. If you git add the file directly, it will be added to the index. Merging a commit with this flag on will cause the merge to fail gracefully so you can handle it manually.

Change the background color of CardView programmatically

I was having a similar issue with formatting CardViews in a recylerView.

I got this simple solution working, not sure if it's the best solution, but it worked for me.

mv_cardView.getBackground().setTint(Color.BLUE)

It gets the background Drawable of the cardView and tints it.

Ways to eliminate switch in code

Switch-statements are not an antipattern per se, but if you're coding object oriented you should consider if the use of a switch is better solved with polymorphism instead of using a switch statement.

With polymorphism, this:

foreach (var animal in zoo) {
    switch (typeof(animal)) {
        case "dog":
            echo animal.bark();
            break;

        case "cat":
            echo animal.meow();
            break;
    }
}

becomes this:

foreach (var animal in zoo) {
    echo animal.speak();
}

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I tried above answers and they didn't help in my case.

I solved it with this link help: http://vjscrazzy.blogspot.co.il/2016/02/failed-to-sync-gradle-project.html

step 1) file>Setttings>appearance and behaviour> system setttings>HTTP proxy> set No Proxy

step 2) build,execution and deployment> Build tools > gradle> now under project level settings > select local gradle distribution> gradle home = F:/Program Files/Android/Android Studio/gradle/gradle-2.4

After that, I did these changes(because it still wrote me some other errors)

Android Studio asked me:

  1. Android Studio asked me to update my Gradle version (which he didn't before)

  2. Enable - Tools> Android> Enable ADB integration.

Also, if your working in a team with repositories, it's important to check that the version of the Andorid Studio is the same.

'Syntax Error: invalid syntax' for no apparent reason

For problems where it seems to be an error on a line you think is correct, you can often remove/comment the line where the error appears to be and, if the error moves to the next line, there are two possibilities.

Either both lines have a problem or the previous line has a problem which is being carried forward. The most likely case is the second option (even more so if you remove another line and it moves again).

For example, the following Python program twisty_passages.py:

xyzzy = (1 +
plugh = 7

generates the error:

  File "twisty_passages.py", line 2
    plugh = 7
          ^
SyntaxError: invalid syntax

despite the problem clearly being on line 1.


In your particular case, that is the problem. The parentheses in the line before your error line is unmatched, as per the following snippet:

# open parentheses: 1  2             3
#                   v  v             v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
#                               ^             ^
# close parentheses:            1             2

Depending on what you're trying to achieve, the solution may be as simple as just adding another closing parenthesis at the end, to close off the sqrt function.

I can't say for certain since I don't recognise the expression off the top of my head. Hardly surprising if (assuming PSAT is the enzyme, and the use of the typeMolecule identifier) it's to do with molecular biology - I seem to recall failing Biology consistently in my youth :-)

With Spring can I make an optional path variable?

You could use a :

@RequestParam(value="somvalue",required=false)

for optional params rather than a pathVariable

Java default constructor

Neither of them. If you define it, it's not the default.

The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:

public Module()
{
  super();
  this.name = null;
  this.credits = 0;
  this.hours = 0;
}

This is exactly the same as

public Module()
{}

And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.

Reference: Java Language Specification

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

Clarification

Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because

  • the question got the defaults wrong, and
  • the constructor has exactly the same effect whether they are included or not.

SELECT with a Replace()

Don't use the alias (P) in your WHERE clause directly.

You can either use the same REPLACE logic again in the WHERE clause:

SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'

Or use an aliased sub query as described in Nick's answers.

Is there a C# String.Format() equivalent in JavaScript?

I created it a long time ago, related question

String.Format = function (b) {
    var a = arguments;
    return b.replace(/(\{\{\d\}\}|\{\d\})/g, function (b) {
        if (b.substring(0, 2) == "{{") return b;
        var c = parseInt(b.match(/\d/)[0]);
        return a[c + 1]
    })
};

Jquery: Find Text and replace

try this,

$('#id1').html($('#id1').html().replace('dogsss','dollsss'));

working sample

How does C compute sin() and other math functions?

OK kiddies, time for the pros.... This is one of my biggest complaints with inexperienced software engineers. They come in calculating transcendental functions from scratch (using Taylor's series) as if nobody had ever done these calculations before in their lives. Not true. This is a well defined problem and has been approached thousands of times by very clever software and hardware engineers and has a well defined solution. Basically, most of the transcendental functions use Chebyshev Polynomials to calculate them. As to which polynomials are used depends on the circumstances. First, the bible on this matter is a book called "Computer Approximations" by Hart and Cheney. In that book, you can decide if you have a hardware adder, multiplier, divider, etc, and decide which operations are fastest. e.g. If you had a really fast divider, the fastest way to calculate sine might be P1(x)/P2(x) where P1, P2 are Chebyshev polynomials. Without the fast divider, it might be just P(x), where P has much more terms than P1 or P2....so it'd be slower. So, first step is to determine your hardware and what it can do. Then you choose the appropriate combination of Chebyshev polynomials (is usually of the form cos(ax) = aP(x) for cosine for example, again where P is a Chebyshev polynomial). Then you decide what decimal precision you want. e.g. if you want 7 digits precision, you look that up in the appropriate table in the book I mentioned, and it will give you (for precision = 7.33) a number N = 4 and a polynomial number 3502. N is the order of the polynomial (so it's p4.x^4 + p3.x^3 + p2.x^2 + p1.x + p0), because N=4. Then you look up the actual value of the p4,p3,p2,p1,p0 values in the back of the book under 3502 (they'll be in floating point). Then you implement your algorithm in software in the form: (((p4.x + p3).x + p2).x + p1).x + p0 ....and this is how you'd calculate cosine to 7 decimal places on that hardware.

Note that most hardware implementations of transcendental operations in an FPU usually involve some microcode and operations like this (depends on the hardware). Chebyshev polynomials are used for most transcendentals but not all. e.g. Square root is faster to use a double iteration of Newton raphson method using a lookup table first. Again, that book "Computer Approximations" will tell you that.

If you plan on implmementing these functions, I'd recommend to anyone that they get a copy of that book. It really is the bible for these kinds of algorithms. Note that there are bunches of alternative means for calculating these values like cordics, etc, but these tend to be best for specific algorithms where you only need low precision. To guarantee the precision every time, the chebyshev polynomials are the way to go. Like I said, well defined problem. Has been solved for 50 years now.....and thats how it's done.

Now, that being said, there are techniques whereby the Chebyshev polynomials can be used to get a single precision result with a low degree polynomial (like the example for cosine above). Then, there are other techniques to interpolate between values to increase the accuracy without having to go to a much larger polynomial, such as "Gal's Accurate Tables Method". This latter technique is what the post referring to the ACM literature is referring to. But ultimately, the Chebyshev Polynomials are what are used to get 90% of the way there.

Enjoy.

pull out p-values and r-squared from a linear regression

While both of the answers above are good, the procedure for extracting parts of objects is more general.

In many cases, functions return lists, and the individual components can be accessed using str() which will print the components along with their names. You can then access them using the $ operator, i.e. myobject$componentname.

In the case of lm objects, there are a number of predefined methods one can use such as coef(), resid(), summary() etc, but you won't always be so lucky.

Function Pointers in Java

This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.

How do I use IValidatableObject?

Quote from Jeff Handley's Blog Post on Validation Objects and Properties with Validator:

When validating an object, the following process is applied in Validator.ValidateObject:

  1. Validate property-level attributes
  2. If any validators are invalid, abort validation returning the failure(s)
  3. Validate the object-level attributes
  4. If any validators are invalid, abort validation returning the failure(s)
  5. If on the desktop framework and the object implements IValidatableObject, then call its Validate method and return any failure(s)

This indicates that what you are attempting to do won't work out-of-the-box because the validation will abort at step #2. You could try to create attributes that inherit from the built-in ones and specifically check for the presence of an enabled property (via an interface) before performing their normal validation. Alternatively, you could put all of the logic for validating the entity in the Validate method.

You also could take a look a the exact implemenation of Validator class here

Python: Find in list

Instead of using list.index(x) which returns the index of x if it is found in list or returns a #ValueError message if x is not found, you could use list.count(x) which returns the number of occurrences of x in list (validation that x is indeed in the list) or it returns 0 otherwise (in the absence of x). The cool thing about count() is that it doesn't break your code or require you to throw an exception for when x is not found

Update R using RStudio

If you're using a Mac computer, you can use the new updateR package to update the R version from RStudio: http://www.andreacirillo.com/2018/02/10/updater-package-update-r-version-with-a-function-on-mac-osx/

In summary, you need to perform this:

To update your R version from within Rstudio using updateR you just have to run these five lines of code:

install.packages('devtools') #assuming it is not already installed
library(devtools)
install_github('andreacirilloac/updateR')
library(updateR)
updateR(admin_password = 'Admin user password')

at the end of installation process a message is going to confirm you the happy end:

everything went smoothly
open a Terminal session and run 'R' to assert that latest version was installed

How to Generate a random number of fixed length using JavaScript?

Based on link you've provided, right answer should be

Math.floor(Math.random()*899999+100000);

Math.random() returns float between 0 and 1, so minimum number will be 100000, max - 999999. Exactly 6 digits, as you wanted :)

Laravel 5 call a model function in a blade view

You can pass it to view but first query it in controller, and then after that add this :

return view('yourview', COMPACT('variabelnametobepassedtoview'));

how to use "tab space" while writing in text file

use \t instead of space.

bw.write("\t"); 

How do I write a bash script to restart a process if it dies?

In-line:

while true; do <your-bash-snippet> && break; done

e.g.

while true; do openconnect x.x.x.x:xxxx && break; done

What is the cleanest way to get the progress of JQuery ajax request?

Follow the steps to display Progress of Ajax Request:

  1. Create a Spinner using Html & CSS or use Bootstrap Spinner.
  2. Display the Spinner when the end-user is requesting for the AJAX Data for infinite loop or for threshold limit time.
  3. So, after a SUCCESS / ERROR result of AJAX Request, remove the Spinner which is currently displayed and show your results.

To make it easy I recommend you using JS Classes for dynamically Displaying & Hiding the spinner for this purpose.

I Hope this helps!

PHP Warning: PHP Startup: ????????: Unable to initialize module

Looks like you haven't upgraded PHP modules, they are not compatible.

Check extension_dir directive in your php.ini. It should point to folder with 5.2 modules.

Create and open a phpinfo file and search for extension_dir to find the path.

Since you did upgrade, there is a chance that you are using old php.ini that is pointing to 5.1 modules

JavaScript set object key by variable

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var key = "name";_x000D_
    var person = {[key]:"John"};_x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var person = {};_x000D_
    var key = "name";_x000D_
    _x000D_
    person[key] /* this is same as person.name */ = "John";_x000D_
    _x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Function for C++ struct

Yes, a struct is identical to a class except for the default access level (member-wise and inheritance-wise). (and the extra meaning class carries when used with a template)

Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.

struct foo {
  int bar;
  foo() : bar(3) {}   //look, a constructor
  int getBar() 
  { 
    return bar; 
  }
};

foo f;
int y = f.getBar(); // y is 3

Is there a command to undo git init?

I'm running Windows 7 with git bash console. The above commands wouldn't work for me.

So I did it via Windows Explorer. I checked show hidden files, went to my projects directory and manually deleted the .git folder. Then back in the command line I checked by running git status.

Which returned...

fatal: Not a git repository (or any of the parent directories): .git

Which is exactly the result I wanted. It returned that the directory is not a git repository (anymore!).

Check if an element has event listener on it. No jQuery

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

How to open the second form?

If you want to open Form2 modally (meaning you can't click on Form1 while Form2 is open), you can do this:

using (Form2 f2 = new Form2()) 
{
    f2.ShowDialog(this);
}

If you want to open Form2 non-modally (meaning you can still click on Form1 while Form2 is open), you can create a form-level reference to Form2 like this:

private Form2 _f2;

public void openForm2()
{
    _f2 = new Form2();
    _f2.Show(this); // the "this" is important, as this will keep Form2 open above 
                    // Form1.
}

public void closeForm2()
{
    _f2.Close();
    _f2.Dispose();
}

Correct way to work with vector of arrays

Every element of your vector is a float[4], so when you resize every element needs to default initialized from a float[4]. I take it you tried to initialize with an int value like 0?

Try:

static float zeros[4] = {0.0, 0.0, 0.0, 0.0};
myvector.resize(newsize, zeros);

Can an XSLT insert the current date?

Do you have control over running the transformation? If so, you could pass in the current date to the XSL and use $current-date from inside your XSL. Below is how you declare the incoming parameter, but with knowing how you are running the transformation, I can't tell you how to pass in the value.

<xsl:param name="current-date" />

For example, from the bash script, use:

xsltproc --stringparam current-date `date +%Y-%m-%d` -o output.html path-to.xsl path-to.xml

Then, in the xsl you can use:

<xsl:value-of select="$current-date"/>

String date to xmlgregoriancalendar conversion

GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

What's the console.log() of java?

console.log() in java is System.out.println(); to put text on the next line

And System.out.print(); puts text on the same line.

MongoDB inserts float when trying to insert integer

db.data.update({'name': 'zero'}, {'$set': {'value': NumberInt(0)}})

You can also use NumberLong.

Uncaught TypeError: (intermediate value)(...) is not a function

  **Error Case:**

var handler = function(parameters) {
  console.log(parameters);
}

(function() {     //IIFE
 // some code
})();

Output: TypeError: (intermediate value)(intermediate value) is not a function *How to Fix IT -> because you are missing semi colan(;) to separate expressions;

 **Fixed**


var handler = function(parameters) {
  console.log(parameters);
}; // <--- Add this semicolon(if you miss that semi colan .. 
   //error will occurs )

(function() {     //IIFE
 // some code
})();

why this error comes?? Reason : specific rules for automatic semicolon insertion which is given ES6 stanards

Difference between text and varchar (character varying)

character varying(n), varchar(n) - (Both the same). value will be truncated to n characters without raising an error.

character(n), char(n) - (Both the same). fixed-length and will pad with blanks till the end of the length.

text - Unlimited length.

Example:

Table test:
   a character(7)
   b varchar(7)

insert "ok    " to a
insert "ok    " to b

We get the results:

a        | (a)char_length | b     | (b)char_length
----------+----------------+-------+----------------
"ok     "| 7              | "ok"  | 2

How to use \n new line in VB msgbox() ...?

This work for me: MessageBox.Show("YourString" & vbcrlf & "YourNewLineString")

How do I drop a function if it already exists?

IF EXISTS 
(SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'functionName') 
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))

DROP FUNCTION functionName
GO

How to concatenate two MP4 files using FFmpeg?

Here is a script (works for an arbitrary number of specified files (not just all in the working directory), without additional files, also works for .mov; tested on macOS):

#!/bin/bash

if [ $# -lt 1 ]; then
    echo "Usage: `basename $0` input_1.mp4 input_2.mp4 ... output.mp4"
    exit 0
fi

ARGS=("$@") # determine all arguments
output=${ARGS[${#ARGS[@]}-1]} # get the last argument (output file)
unset ARGS[${#ARGS[@]}-1] # drop it from the array
(for f in "${ARGS[@]}"; do echo "file '$f'"; done) | ffmpeg -protocol_whitelist file,pipe -f concat -safe 0 -i pipe: -vcodec copy -acodec copy $output

Confirm deletion using Bootstrap 3 modal box

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/modal/

What is the difference between require_relative and require in Ruby?

The top answers are correct, but deeply technical. For those newer to Ruby:

  • require_relative will most likely be used to bring in code from another file that you wrote.

for example, what if you have data in ~/my-project/data.rb and you want to include that in ~/my-project/solution.rb? in solution.rb you would add require_relative 'data'.

it is important to note these files do not need to be in the same directory. require_relative '../../folder1/folder2/data' is also valid.

  • require will most likely be used to bring in code from a library someone else wrote.

for example, what if you want to use one of the helper functions provided in the active_support library? you'll need to install the gem with gem install activesupport and then in the file require 'active_support'.

require 'active_support/all'
"FooBar".underscore

Said differently--

  • require_relative requires a file specifically pointed to relative to the file that calls it.

  • require requires a file included in the $LOAD_PATH.

How to display HTML in TextView?

Simple use Html.fromHtml("html string"). This will work. If the string has tags like <h1> then spaces will come. But we cannot eliminate those spaces. If you still want to remove the spaces, then you can remove the tags in the string and then pass the string to the method Html.fromHtml("html string"); . Also generally these strings come from server(dynamic) but not often, if it is the case better to pass the string as it is to the method than try to remove the tags from the string.

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

In my case it was due to the Access Protection feature of my anti-virus (McAfee). It was obviously blocking access to this file, as of such the error.

I disabled it and the solution ran. You might want to check any utility application you might have running that could be affecting access to some files.

How to check whether the user uploaded a file in PHP?

In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully. https://www.php.net/manual/en/reserved.variables.files.php#109648

if ( boolval( $_FILES['image']['error'] === 0 ) ) {
    // ...
}

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

In my case this error occured when I set up my environment adb path as ~/.android-sdk/platform-tools (which happens when e.g. android-platform-tools is installed via homebrew), which version was 36, but Android Studio project has Android SDK next path ~/Library/Android/sdk which adb version was 39.

I have changed my PATH to platform-tools to ~/Library/Android/sdk/platform-tools and error was solved

How do I get the key at a specific index from a Dictionary in Swift?

That's because keys returns LazyMapCollection<[Key : Value], Key>, which can't be subscripted with an Int. One way to handle this is to advance the dictionary's startIndex by the integer that you wanted to subscript by, for example:

let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]

Another possible solution would be to initialize an array with keys as input, then you can use integer subscripts on the result:

let firstKey = Array(myDictionary.keys)[0] // or .first

Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

Encountered this issue in chrome. Resolved by cleaning up related cookies. Note that you don't have to cleanup ALL your cookies.

Difference between single and double quotes in Bash

Since this is the de facto answer when dealing with quotes in bash, I'll add upon one more point missed in the answers above, when dealing with the arithmetic operators in the shell.

The bash shell supports two ways do arithmetic operation, one defined by the built-in let command and the $((..)) operator. The former evaluates an arithmetic expression while the latter is more of a compound statement.

It is important to understand that the arithmetic expression used with let undergoes word-splitting, pathname expansion just like any other shell commands. So proper quoting and escaping needs to be done.

See this example when using let

let 'foo = 2 + 1'
echo $foo
3

Using single quotes here is absolutely fine here, as there is no need for variable expansions here, consider a case of

bar=1
let 'foo = $bar + 1'

would fail miserably, as the $bar under single quotes would not expand and needs to be double-quoted as

let 'foo = '"$bar"' + 1'

This should be one of the reasons, the $((..)) should always be considered over using let. Because inside it, the contents aren't subject to word-splitting. The previous example using let can be simply written as

(( bar=1, foo = bar + 1 ))

Always remember to use $((..)) without single quotes

Though the $((..)) can be used with double-quotes, there is no purpose to it as the result of it cannot contain a content that would need the double-quote. Just ensure it is not single quoted.

printf '%d\n' '$((1+1))'
-bash: printf: $((1+1)): invalid number
printf '%d\n' $((1+1))
2
printf '%d\n' "$((1+1))"
2

May be in some special cases of using the $((..)) operator inside a single quoted string, you need to interpolate quotes in a way that the operator either is left unquoted or under double quotes. E.g. consider a case, when you are tying to use the operator inside a curl statement to pass a counter every time a request is made, do

curl http://myurl.com --data-binary '{"requestCounter":'"$((reqcnt++))"'}'

Notice the use of nested double-quotes inside, without which the literal string $((reqcnt++)) is passed to requestCounter field.

Express.js: how to get remote client address

This is just additional information for this answer.

If you are using nginx, you would add proxy_set_header X-Real-IP $remote_addr; to the location block for the site. /etc/nginx/sites-available/www.example.com for example. Here is a example server block.

server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;

    location / {
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_pass http://127.0.1.1:3080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

After restarting nginx, you will be able to access the ip in your node/express application routes with req.headers['x-real-ip'] || req.connection.remoteAddress;

How to set the value for Radio Buttons When edit?

just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:

<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female

in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.

applying css to specific li class

I only see one color being specified (albeit you specify it in two different places.) Either you've omitted some of your style rules, or you simply didn't specify another color.

How does the bitwise complement operator (~ tilde) work?

This operation is a complement, not a negation.

Consider that ~0 = -1, and work from there.

The algorithm for negation is, "complement, increment".

Did you know? There is also "one's complement" where the inverse numbers are symmetrical, and it has both a 0 and a -0.

how to fetch data from database in Hibernate

try the class-name

Query query = session.createQuery("from Employee");

instead of the table name

Query query = session.createQuery("from EMPLOYEE");

Difference between npx and npm?

Here's an example of NPX in action: npx cowsay hello

If you type that into your bash terminal you'll see the result. The benefit of this is that npx has temporarily installed cowsay. There is no package pollution since cowsay is not permanently installed. This is great for one off packages where you want to avoid package pollution.

As mentioned in other answers, npx is also very useful in cases where (with npm) the package needs to be installed then configured before running. E.g. instead of using npm to install and then configure the json.package file and then call the configured run command just use npx instead. A real example: npx create-react-app my-app

DB2 Date format

This isn't straightforward, but

SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1

returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.

SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1

Convert time span value to format "hh:mm Am/Pm" using C#

Doing some piggybacking off existing answers here:

public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
    return new DateTime().Add(timeSpan).ToShortTimeString();
} 

public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
    return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}

importing go files in same folder

I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.

My GOPATH workspace is c:\work\go and under that I have

/src/pg/main.go      (package main)
/src/pg/dbtypes.go   (pakage dbtypes)

in main.go I import "/pg/dbtypes"

C# Linq Where Date Between 2 Dates

So you are scrolling down because the Answers do not work:

This works like magic (but they say it has efficiency issues for big data, And you do not care just like me)

1- Data Type in Database is "datetime" and "nullable" in my case.

Example data format in DB is like:

2018-11-06 15:33:43.640

An in C# when converted to string is like:

2019-01-03 4:45:16 PM

So the format is :

yyyy/MM/dd hh:mm:ss tt

2- So you need to prepare your datetime variables in the proper format first:

Example 1

yourDate.ToString("yyyy/MM/dd hh:mm:ss tt")

Example 2 - Datetime range for the last 30 days

    DateTime dateStart = DateTime.Now.AddDays(-30);
    DateTime dateEnd = DateTime.Now.AddDays(1).AddTicks(-1);

3- Finally the linq query you lost your day trying to find (Requires EF 6)

using System.Data.Entity;

_dbContext.Shipments.Where(s => (DbFunctions.TruncateTime(s.Created_at.Value) >= dateStart && DbFunctions.TruncateTime(s.Created_at.Value) <= dateEnd)).Count();

To take time comparison into account as well :

(DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) >= dateStart && DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) <= dateEnd)

Note the following method mentioned on other stackoverflow questions and answers will not work correctly:

....
&&
(
    s.Created_at.Value.Day >= dateStart.Day && s.Created_at.Value.Day <= dateEnd.Day &&
    s.Created_at.Value.Month >= dateStart.Month && s.Created_at.Value.Month <= dateEnd.Month &&
    s.Created_at.Value.Year >= dateStart.Year && s.Created_at.Value.Year <= dateEnd.Year
)).count();

if the start day was in this month for example and the end day is on the next month, the query will return false and no results, for example:

DatabaseCreatedAtItemThatWeWant = 2018/12/05

startDate = 2018/12/01

EndDate = 2019/01/04

the query will always search for days between 01 and 04 without taking the "month" into account, so "s.Created_at.Value.Day <= dateEnd.Day" will fail

And in case you have really big data you would execute Native SQL Query rather than linq

...
    ... where Shipments.Created_at BETWEEN CAST(@Created_at_from as datetime) AND CAST(@Created_at_to as datetime))
    ....

Thanks

The APK file does not exist on disk

In my case the problem was that debugging configuration become invalid somehow, even that the test method name, class or package has not changed.

I deleted the configurations from Run->Edit Configurations, at here:

enter image description here

Android studio will create a new one automatically.

Print a div content using Jquery

I update this function
now you can print any tag or any part of the page with its full style
must include jquery.js file

HTML

<div id='DivIdToPrint'>
    <p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >

JavaScript

        function printtag(tagid) {
            var hashid = "#"+ tagid;
            var tagname =  $(hashid).prop("tagName").toLowerCase() ;
            var attributes = ""; 
            var attrs = document.getElementById(tagid).attributes;
              $.each(attrs,function(i,elem){
                attributes +=  " "+  elem.name+" ='"+elem.value+"' " ;
              })
            var divToPrint= $(hashid).html() ;
            var head = "<html><head>"+ $("head").html() + "</head>" ;
            var allcontent = head + "<body  onload='window.print()' >"+ "<" + tagname + attributes + ">" +  divToPrint + "</" + tagname + ">" +  "</body></html>"  ;
            var newWin=window.open('','Print-Window');
            newWin.document.open();
            newWin.document.write(allcontent);
            newWin.document.close();
           // setTimeout(function(){newWin.close();},10);
        }

command/usr/bin/codesign failed with exit code 1- code sign error

Rebooting didn't work for me.

Just try with downloading and adding the Certificate again to keyChain. That worked for me. When I checked Keychain Access the respective certificate was missing. Got the problem solve when I reinstalled the certificate.

Laravel 5.5 ajax call 419 (unknown status)

Even though you have a csrf_token, if you are authenticate your controller actions using Laravel Policies you can have 419 response as well. In that case you should add necessary policy functions in your Policy class.

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

On macOS High Sierra, this solved my issue:

sudo gem update --system -n /usr/local/bin/gem

How to parse a String containing XML in Java and retrieve the value of the root node?

I think you would be look at String class, there are multiple ways to do it. What about substring(int,int) and indexOf(int) lastIndexOf(int)?

How can I listen for a click-and-hold in jQuery?

    var _timeoutId = 0;

    var _startHoldEvent = function(e) {
      _timeoutId = setInterval(function() {
         myFunction.call(e.target);
      }, 1000);
    };

    var _stopHoldEvent = function() {
      clearInterval(_timeoutId );
    };

    $('#myElement').on('mousedown', _startHoldEvent).on('mouseup mouseleave', _stopHoldEvent);

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

"/tmp/mysql.sock" will be created automatically when you start the MySQL server. So remember to do that before starting the rails server.

How to solve a timeout error in Laravel 5

Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page

otherwise in htaccess php_value max_execution_time 360

How do I keep the screen on in my App?

You can simply use setKeepScreenOn() from the View class.

XSL substring and indexOf

The following is the complete example containing both XML and XSLT where substring-before and substring-after are used

<?xml version="1.0" encoding="UTF-8"?>
<persons name="Group_SOEM">
    <person>
        <first>Joe Smith</first>
        <last>Joe Smith</last>
        <address>123 Main St, Anycity</address>
    </person>
</persons>    

The following is XSLT which changes value of first/last name by separating the value by space so that after applying this XSL the first name element will have value "Joe" and last "Smith".

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="first">
    <first>
        <xsl:value-of select="substring-before(.,' ')" />
    </first>
</xsl:template> 
<xsl:template match="last">
    <last>
        <xsl:value-of select="substring-after(.,' ')" />
    </last>
</xsl:template> 
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>   

Best way to unselect a <select> in jQuery?

Another simple way:

$("#selectedID")[0].selectedIndex = -1

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

An unwanted single quote was my problem. Checking the connection string from the location of the index mentioned in the error string helped me spot the issue.

How to iterate over each string in a list of strings and operate on it's elements

for i,j in enumerate(words): # i---index of word----j
     #now you got index of your words (present in i)
     print(i) 

How can I give access to a private GitHub repository?

Two steps:
1. Login and click "Invite someone" in the right column under "People". Enter and select persons github id.
2. It will then give you the option to "Invite Username to some teams" at which point you simply check off which teams you want to add them to then click "Send Invitation"

Alternatively:
1. Get the persons github id (not their email)
2. Navigate to the repository you would like to add the user to
3. Click "Settings" in the right column (not the gearbox settings along the top)
4. Click Collaborators long the left column
5. Select the repository name
6. Where it reads "Invite or add users to team" add the persons github id
7. An invitation will then be e-mailed.

Please let me know how this worked for you!

how to make label visible/invisible?

You are looking for display:

document.getElementById("endTimeLabel").style.display = 'none';
document.getElementById("endTimeLabel").style.display = 'block';

Edit: You could also easily reuse your validation function.

HTML:

<span id="startDateLabel">Start date/time: </span>
<input id="startDateStr" name="startDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="startDateCalendarTrigger">...</button>
<input id="startDateTime" type="text" size="8" name="startTime" value="12:00 AM" onchange="validateHHMM(this.value, 'startTimeLabel');"/>
<label id="startTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label><br />

<span id="endDateLabel">End date/time: </span>
<input id="endDateStr" name="endDateStr" size="8" onchange="if (!formatDate(this,'USA')) {this.value = '';}" />
<button id="endDateCalendarTrigger">...</button>

<input id="endDateTime" type="text" size="8" name="endTime" value="12:00 AM" onchange="validateHHMM(this.value, 'endTimeLabel');"/>
<label id="endTimeLabel" class="errorMsg">Time must be entered in the format HH:MM AM/PM</label>

Javascript:

function validateHHMM(value, message) {
    var isValid = /^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/.test(value);

    if (isValid) {
        document.getElementById(message).style.display = "none";
    }else {
        document.getElementById(message).style.display= "inline";
    }

    return isValid;
}

Live DEMO

Global keyboard capture in C# application

private void buttonHook_Click(object sender, EventArgs e)
{
    // Hooks only into specified Keys (here "A" and "B").
    // (***) Use this constructor

    _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

    // Hooks into all keys.
    // (***) Or this - not both

    _globalKeyboardHook = new GlobalKeyboardHook();
    _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}

And then is working fine.

Trying to embed newline in a variable in bash

Summary

  1. Inserting \n

    p="${var1}\n${var2}"
    echo -e "${p}"
    
  2. Inserting a new line in the source code

    p="${var1}
    ${var2}"
    echo "${p}"
    
  3. Using $'\n' (only and )

    p="${var1}"$'\n'"${var2}"
    echo "${p}"
    

Details

1. Inserting \n

p="${var1}\n${var2}"
echo -e "${p}"

echo -e interprets the two characters "\n" as a new line.

var="a b c"
first_loop=true
for i in $var
do
   p="$p\n$i"            # Append
   unset first_loop
done
echo -e "$p"             # Use -e

Avoid extra leading newline

var="a b c"
first_loop=1
for i in $var
do
   (( $first_loop )) &&  # "((...))" is bash specific
   p="$i"            ||  # First -> Set
   p="$p\n$i"            # After -> Append
   unset first_loop
done
echo -e "$p"             # Use -e

Using a function

embed_newline()
{
   local p="$1"
   shift
   for i in "$@"
   do
      p="$p\n$i"         # Append
   done
   echo -e "$p"          # Use -e
}

var="a b c"
p=$( embed_newline $var )  # Do not use double quotes "$var"
echo "$p"

2. Inserting a new line in the source code

var="a b c"
for i in $var
do
   p="$p
$i"       # New line directly in the source code
done
echo "$p" # Double quotes required
          # But -e not required

Avoid extra leading newline

var="a b c"
first_loop=1
for i in $var
do
   (( $first_loop )) &&  # "((...))" is bash specific
   p="$i"            ||  # First -> Set
   p="$p
$i"                      # After -> Append
   unset first_loop
done
echo "$p"                # No need -e

Using a function

embed_newline()
{
   local p="$1"
   shift
   for i in "$@"
   do
      p="$p
$i"                      # Append
   done
   echo "$p"             # No need -e
}

var="a b c"
p=$( embed_newline $var )  # Do not use double quotes "$var"
echo "$p"

3. Using $'\n' (less portable)

and interprets $'\n' as a new line.

var="a b c"
for i in $var
do
   p="$p"$'\n'"$i"
done
echo "$p" # Double quotes required
          # But -e not required

Avoid extra leading newline

var="a b c"
first_loop=1
for i in $var
do
   (( $first_loop )) &&  # "((...))" is bash specific
   p="$i"            ||  # First -> Set
   p="$p"$'\n'"$i"       # After -> Append
   unset first_loop
done
echo "$p"                # No need -e

Using a function

embed_newline()
{
   local p="$1"
   shift
   for i in "$@"
   do
      p="$p"$'\n'"$i"    # Append
   done
   echo "$p"             # No need -e
}

var="a b c"
p=$( embed_newline $var )  # Do not use double quotes "$var"
echo "$p"

Output is the same for all

a
b
c

Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.


EDIT

How do I serialize a Python dictionary into a string, and then back to a dictionary?

It depends on what you're wanting to use it for. If you're just trying to save it, you should use pickle (or, if you’re using CPython 2.x, cPickle, which is faster).

>>> import pickle
>>> pickle.dumps({'foo': 'bar'})
b'\x80\x03}q\x00X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02s.'
>>> pickle.loads(_)
{'foo': 'bar'}

If you want it to be readable, you could use json:

>>> import json
>>> json.dumps({'foo': 'bar'})
'{"foo": "bar"}'
>>> json.loads(_)
{'foo': 'bar'}

json is, however, very limited in what it will support, while pickle can be used for arbitrary objects (if it doesn't work automatically, the class can define __getstate__ to specify precisely how it should be pickled).

>>> pickle.dumps(object())
b'\x80\x03cbuiltins\nobject\nq\x00)\x81q\x01.'
>>> json.dumps(object())
Traceback (most recent call last):
  ...
TypeError: <object object at 0x7fa0348230c0> is not JSON serializable

Best way to check if MySQL results returned in PHP?

if (mysql_num_rows($result)==0) { PERFORM ACTION }

For PHP 5 and 7 and above use mysqli:

if (mysqli_num_rows($result)==0) { PERFORM ACTION }

This gets my vote.

OP assuming query is not returning any error, so this should be one of the way

Rails Model find where not equal

The only way you can get it fancier is with MetaWhere.

MetaWhere has a newer cousin which is called Squeel which allows code like this:

GroupUser.where{user_id != me}

It goes without saying, that if this is the only refactor you are going to make, it is not worth using a gem and I would just stick with what you got. Squeel is useful in situations where you have many complex queries interacting with Ruby code.

Python match a string with regex

One Liner implementation:

a=[1,3]
b=[1,2,3,4]
all(i in b for i in a)

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

Python integer division yields float

Oops, immediately found 2//2.

How to find the Vagrant IP?

Terminating a connection open with vagrant ssh will show the address, so a dummy or empty command can be executed:

$ vagrant ssh -c ''
Connection to 192.168.121.155 closed.

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

How to test if list element exists?

Here is a performance comparison of the proposed methods in other answers.

> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo), 
                                 is.null(foo[['k']]), 
                                 exists('k', where = foo))
Unit: nanoseconds
                     expr  min   lq    mean median   uq   max neval cld
      "k" %in% names(foo)  467  933 1064.31    934  934 10730   100  a 
      is.null(foo[["k"]])    0    0  168.50      1  467  3266   100  a 
 exists("k", where = foo) 6532 6998 7940.78   7232 7465 56917   100   b

If you are planing to use the list as a fast dictionary accessed many times, then the is.null approach might be the only viable option. I assume it is O(1), while the %in% approach is O(n)?

Can I change the checkbox size using CSS?

I found this CSS-only library to be very helpful: https://lokesh-coder.github.io/pretty-checkbox/

Or, you could roll your own with this same basic concept, similar to what @Sharcoux posted. It's basically:

  • Hide the normal checkbox (opacity 0 and placed where it would go)
  • Add a css-based fake checkbox
  • Use input:checked~div label for the checked style
  • make sure your <label> is clickable using for=yourinputID

_x000D_
_x000D_
.pretty {_x000D_
  position: relative;_x000D_
  margin: 1em;_x000D_
}_x000D_
.pretty input {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  min-width: 1em;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index: 2;_x000D_
  opacity: 0;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  cursor: pointer;_x000D_
}_x000D_
.pretty-inner {_x000D_
  box-sizing: border-box;_x000D_
  position: relative;_x000D_
}_x000D_
.pretty-inner label {_x000D_
  position: initial;_x000D_
  display: inline-block;_x000D_
  font-weight: 400;_x000D_
  margin: 0;_x000D_
  text-indent: 1.5em;_x000D_
  min-width: calc(1em + 2px);_x000D_
}_x000D_
.pretty-inner label:after,_x000D_
.pretty-inner label:before {_x000D_
  content: '';_x000D_
  width: calc(1em + 2px);_x000D_
  height: calc(1em + 2px);_x000D_
  display: block;_x000D_
  box-sizing: border-box;_x000D_
  border-radius: 0;_x000D_
  border: 1px solid transparent;_x000D_
  z-index: 0;_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  background-color: transparent;_x000D_
}_x000D_
.pretty-inner label:before {_x000D_
  border-color: #bdc3c7;_x000D_
}_x000D_
.pretty input:checked~.pretty-inner label:after {_x000D_
  background-color: #00bb82;_x000D_
  width: calc(1em - 6px);_x000D_
  height: calc(1em - 6px);_x000D_
  top: 4px;_x000D_
  left: 4px;_x000D_
}_x000D_
_x000D_
_x000D_
/* Add checkmark character style */_x000D_
.pretty input:checked~.pretty-inner.checkmark:after {_x000D_
  content: '\2713';_x000D_
  color: #fff;_x000D_
  position: absolute;_x000D_
  font-size: 0.65em;_x000D_
  left: 6px;_x000D_
  top: 3px;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
body {_x000D_
  font-size: 20px;_x000D_
  font-family: sans-serif;_x000D_
}
_x000D_
<div class="pretty">_x000D_
 <input type="checkbox" id="demo" name="demo">_x000D_
 <div class="pretty-inner"><label for="demo">I agree.</label></div>_x000D_
</div>_x000D_
_x000D_
<div class="pretty">_x000D_
 <input type="checkbox" id="demo" name="demo">_x000D_
 <div class="pretty-inner checkmark"><label for="demo">Please check the box.</label></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

convert pfx format to p12

I had trouble with a .pfx file with openconnect. Renaming didn't solve the problem. I used keytool to convert it to .p12 and it worked.

keytool -importkeystore -destkeystore new.p12 -deststoretype pkcs12 -srckeystore original.pfx

In my case the password for the new file (new.p12) had to be the same as the password for the .pfx file.

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Typically, boolean values that are used in branches immediately after they're calculated like this are never actually stored in variables. Instead, the compiler just branches directly off the condition codes that were set from the preceding comparison. For example,

int a = SomeFunction();
bool result = --a >= 0; // use subtraction as example computation
if ( result ) 
{
   foo(); 
}
else
{
   bar();
}
return;

Usually compiles to something like:

call .SomeFunction  ; calls to SomeFunction(), which stores its return value in eax
sub eax, 1 ; subtract 1 from eax and store in eax, set S (sign) flag if result is negative
jl ELSEBLOCK ; GOTO label "ELSEBLOCK" if S flag is set
call .foo ; this is the "if" black, call foo()
j FINISH ; GOTO FINISH; skip over the "else" block
ELSEBLOCK: ; label this location to the assembler
call .bar
FINISH: ; both paths end up here
ret ; return

Notice how the "bool" is never actually stored anywhere.

Validation error: "No validator could be found for type: java.lang.Integer"

As per the javadoc of NotEmpty, Integer is not a valid type for it to check. It's for Strings and collections. If you just want to make sure an Integer has some value, javax.validation.constraints.NotNull is all you need.

public @interface NotEmpty

Asserts that the annotated string, collection, map or array is not null or empty.

Asus Zenfone 5 not detected by computer

To enable USB Debugging first you need to enable Developer Options.

  1. Open Zenfone Settings and scroll down and tap About.

  2. Scroll down and select Software Information.

  3. Under Software information you will see Build Number.

  4. Tap Build Number 7 times to enable Developer Options.

  5. Come back to Settings and scroll down to find Developer Options.

  6. Tap on Developer Options and it will open upto give you option to enable USB Debugging

How do you underline a text in Android XML?

<resource>
    <string name="your_string_here">This is an <u>underline</u>.</string>
</resources>

If it does not work then

<resource>
<string name="your_string_here">This is an &lt;u>underline&lt;/u>.</string>

Because "<" could be a keyword at some time.

And for Displaying

TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(Html.fromHtml(getString(R.string.your_string_here)));

How can I merge the columns from two tables into one output?

SELECT col1,
  col2
FROM
  (SELECT rownum X,col_table1 FROM table1) T1
INNER JOIN
  (SELECT rownum Y, col_table2 FROM table2) T2
ON T1.X=T2.Y;

Error occurred during initialization of boot layer FindException: Module not found

I just encountered the same issue after adding the bin folder to .gitignore, not sure if that caused the issue.

I solved it by going to Project/Properties/Build Path and I removed the scr folder and added it again.

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

How can I include null values in a MIN or MAX?

I try to use a union to combine two queries to format the returns you want:

SELECT recordid, startdate, enddate FROM tmp Where enddate is null UNION SELECT recordid, MIN(startdate), MAX(enddate) FROM tmp GROUP BY recordid

But I have no idea if the Union would have great impact on the performance

Split a string into array in Perl

I found this one to be very simple!

my $line = "file1.gz file2.gz file3.gz";

my @abc =  ($line =~ /(\w+[.]\w+)/g);

print $abc[0],"\n";
print $abc[1],"\n";
print $abc[2],"\n";

output:

file1.gz 
file2.gz 
file3.gz

Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.

How to select unique records by SQL

If you only need to remove duplicates then use DISTINCT. GROUP BY should be used to apply aggregate operators to each group

GROUP BY v DISTINCT

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

Building on the excellent answers by rafx and Sina, here is a snippet that only targets Firefox and replaces the default button with a down-caret copied from Bootstrap's icon theme.

Before:

default select

After:

styled select

@-moz-document url-prefix() {
  select.form-control {
    padding-right: 25px;
    background-image: url("data:image/svg+xml,\
      <svg version='1.1' xmlns='http://www.w3.org/2000/svg' width='14px'\
           height='14px' viewBox='0 0 1200 1000' fill='rgb(51,51,51)'>\
        <path d='M1100 411l-198 -199l-353 353l-353 -353l-197 199l551 551z'/>\
      </svg>");
    background-repeat: no-repeat;
    background-position: calc(100% - 7px) 50%;
    -moz-appearance: none;
    appearance: none;
  }
}

(The inline SVG has backslashes and newlines for readability. Remove them if they cause trouble in your asset pipeline.)

Here is the JSFiddle

How to allow users to check for the latest app version from inside the app?

To save time writing for check new version update for android app, I written it as library and open source at https://github.com/winsontan520/Android-WVersionManager

How to add leading zeros for for-loop in shell?

Use the following syntax:

$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05

Disclaimer: Leading zeros only work in >=bash-4.

If you want to use printf, nothing prevents you from putting its result in a variable for further use:

$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05

Javascript Error Null is not an Object

Try loading your javascript after.

Try this:

<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="submit" id="myButton" value="Go" />
</form>

<script src="js/script.js" type="text/javascript"></script>

Adding a y-axis label to secondary y-axis in matplotlib

The best way is to interact with the axes object directly

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

example graph

Node / Express: EADDRINUSE, Address already in use - Kill server

Reasons for this issues are:

  1. Any one application may be running on this port like Skype.
  2. Node may have crashed and port may not have been freed.
  3. You may have tried to start server more than one. To solve this problem, one can maintain a boolean to check whether server have been started or not. It should be started only if boolean return false or undefined;

OpenJDK availability for Windows OS

Red Hat announces they will distribute an OpenJDK for Windows platform: http://developers.redhat.com/blog/2016/06/27/openjdk-now-available-for-windows/

EDITED (thx to CaseyB comment): there is no PRODUCTION support on Windows. From the documentation:

All Red Hat distributions of OpenJDK 8 on Windows are supported for development of applications that work in conjunction with JBoss Middleware, so that you have the convenience and confidence to develop and test in Windows or Linux-based environments and deploy your solution to a 100% compatible, fully supported, OpenJDK 8 on Red Hat Enterprise Linux.

Compiling and Running Java Code in Sublime Text 2

Refer the solution at: http://www.compilr.org/compile-and-run-java-programs/

Hope that solves, for both compiling and running the classes within sublime..... You can see my script in the comments section to try it out in case of mac...

EDIT: Unfortunately, the above link is broken now. It detailed all the steps required for comiling and running java within sublime text. Anyways, for mac or linux systems, the below should work:

modify javac.sublime-build file to:


#!/bin/sh

classesDir="/Users/$USER/Desktop/java/classes/"
codeDir="/Users/$USER/Desktop/java/code/"
[ -f "$classesDir/$1.class" ] && rm $classesDir/$1.class
for file in $1.java
do
echo "Compiling $file........"
javac -d $classesDir $codeDir/$file
done
if [ -f "$classesDir/$1.class" ]
then
echo "-----------OUTPUT-----------"
java -cp $classesDir $1
else
echo " "
fi

Here, I have made a folder named "java" on the Desktop and subfolders "classes" and "code" for maintaining the .class and .java files respectively, you can modify in your own way.

How to change the order of DataFrame columns?

Simply do,

df = df[['mean'] + df.columns[:-1].tolist()]

Getting the class of the element that fired an event using JQuery

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("a").click(function(event) {_x000D_
    var myClass = $(this).attr("class");_x000D_
    var myId = $(this).attr('id');_x000D_
    alert(myClass + " " + myId);_x000D_
  });_x000D_
})
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
  <a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

This works for me. There is no event.target.class function in jQuery.

How do I check that a number is float or integer?

YourJS provides the following two functions which work for all numbers including returning false for -Infinity and Infinity:

function isFloat(x) {
  return typeOf(x, 'Number') && !!(x % 1);
}

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

Due to the fact that typeOf() is a YourJS internal function, if you wanted to use these definitions you can download the version for just these functions here: http://yourjs.com/snippets/build/34

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

hibernate could not get next sequence value

I seem to recall having to use @GeneratedValue(strategy = GenerationType.IDENTITY) to get Hibernate to use 'serial' columns on PostgreSQL.

Android - running a method periodically using postDelayed() call

Why don't you create service and put logic in onCreate(). In this case even if you press back button service will keep on executing. and once you enter into application it will not call onCreate() again. Rather it will call onStart()

How to declare a constant in Java

final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

WebSphere Application Server V7 does support Java Platform, Standard Edition (Java SE) 6 (see Specifications and API documentation in the Network Deployment (All operating systems), Version 7.0 Information Center) and it's since the release V8.5 when Java 7 has been supported.

I couldn't find the Java 6 SDK documentation, and could only consult IBM JVM Messages in Java 7 Windows documentation. Alas, I couldn't find the error message in the documentation either.

Since java.lang.UnsupportedClassVersionError is "Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.", you ran into an issue of building the application with more recent version of Java than the one supported by the runtime environment, i.e. WebSphere Application Server 7.0.

I may be mistaken, but I think that offset=6 in the message is to let you know what position caused the incompatibility issue to occur. It's irrelevant for you, for me, and for many other people, but some might find it useful, esp. when they generate bytecode themselves.

Run the versionInfo command to find out about the Installed Features of WebSphere Application Server V7, e.g.

C:\IBM\WebSphere\AppServer>.\bin\versionInfo.bat
WVER0010I: Copyright (c) IBM Corporation 2002, 2005, 2008; All rights reserved.
WVER0012I: VersionInfo reporter version 1.15.1.47, dated 10/18/11

--------------------------------------------------------------------------------
IBM WebSphere Product Installation Status Report
--------------------------------------------------------------------------------

Report at date and time February 19, 2013 8:07:20 AM EST

Installation
--------------------------------------------------------------------------------
Product Directory        C:\IBM\WebSphere\AppServer
Version Directory        C:\IBM\WebSphere\AppServer\properties\version
DTD Directory            C:\IBM\WebSphere\AppServer\properties\version\dtd
Log Directory            C:\ProgramData\IBM\Installation Manager\logs

Product List
--------------------------------------------------------------------------------
BPMPC                    installed
ND                       installed
WBM                      installed

Installed Product
--------------------------------------------------------------------------------
Name                  IBM Business Process Manager Advanced V8.0
Version               8.0.1.0
ID                    BPMPC
Build Level           20121102-1733
Build Date            11/2/12
Package               com.ibm.bpm.ADV.V80_8.0.1000.20121102_2136
Architecture          x86-64 (64 bit)
Installed Features    Non-production
                      Business Process Manager Advanced - Client (always installed)
Optional Languages    German
                      Russian
                      Korean
                      Brazilian Portuguese
                      Italian
                      French
                      Hungarian
                      Simplified Chinese
                      Spanish
                      Czech
                      Traditional Chinese
                      Japanese
                      Polish
                      Romanian

Installed Product
--------------------------------------------------------------------------------
Name                  IBM WebSphere Application Server Network Deployment
Version               8.0.0.5
ID                    ND
Build Level           cf051243.01
Build Date            10/22/12
Package               com.ibm.websphere.ND.v80_8.0.5.20121022_1902
Architecture          x86-64 (64 bit)
Installed Features    IBM 64-bit SDK for Java, Version 6
                      EJBDeploy tool for pre-EJB 3.0 modules
                      Embeddable EJB container
                      Sample applications
                      Stand-alone thin clients and resource adapters
Optional Languages    German
                      Russian
                      Korean
                      Brazilian Portuguese
                      Italian
                      French
                      Hungarian
                      Simplified Chinese
                      Spanish
                      Czech
                      Traditional Chinese
                      Japanese
                      Polish
                      Romanian

Installed Product
--------------------------------------------------------------------------------
Name                  IBM Business Monitor
Version               8.0.1.0
ID                    WBM
Build Level           20121102-1733
Build Date            11/2/12
Package               com.ibm.websphere.MON.V80_8.0.1000.20121102_2222
Architecture          x86-64 (64 bit)
Optional Languages    German
                      Russian
                      Korean
                      Brazilian Portuguese
                      Italian
                      French
                      Hungarian
                      Simplified Chinese
                      Spanish
                      Czech
                      Traditional Chinese
                      Japanese
                      Polish
                      Romanian

--------------------------------------------------------------------------------
End Installation Status Report
--------------------------------------------------------------------------------

Excel: the Incredible Shrinking and Expanding Controls

Grouping the controls appears to work for me. I would upvote or comment but SO won't let me. Note that this issue comes up often if you use W8 display scaling and have a high resolution laptop and older monitor.

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Best practices for API versioning?

There are a few places you can do versioning in a REST API:

  1. As noted, in the URI. This can be tractable and even esthetically pleasing if redirects and the like are used well.

  2. In the Accepts: header, so the version is in the filetype. Like 'mp3' vs 'mp4'. This will also work, though IMO it works a bit less nicely than...

  3. In the resource itself. Many file formats have their version numbers embedded in them, typically in the header; this allows newer software to 'just work' by understanding all existing versions of the filetype while older software can punt if an unsupported (newer) version is specified. In the context of a REST API, it means that your URIs never have to change, just your response to the particular version of data you were handed.

I can see reasons to use all three approaches:

  1. if you like doing 'clean sweep' new APIs, or for major version changes where you want such an approach.
  2. if you want the client to know before it does a PUT/POST whether it's going to work or not.
  3. if it's okay if the client has to do its PUT/POST to find out if it's going to work.

Responsive css styles on mobile devices ONLY

What's you've got there should be fine to work, but there is no actual "Is Mobile/Tablet" media query so you're always going to be stuck.

There are media queries for common breakpoints , but with the ever changing range of devices they're not guaranteed to work moving forwards.

The idea is that your site maintains the same brand across all sizes, so you should want the styles to cascade across the breakpoints and only update the widths and positioning to best suit that viewport.

To further the answer above, using Modernizr with a no-touch test will allow you to target touch devices which are most likely tablets and smart phones, however with the new releases of touch based screens that is not as good an option as it once was.

ASP.NET Bundles how to disable minification

If you set the following property to false then it will disable both bundling and minification.

In Global.asax.cs file, add the line as mentioned below

protected void Application_Start()
{
    System.Web.Optimization.BundleTable.EnableOptimizations = false;
}

No 'Access-Control-Allow-Origin' header in Angular 2 app

I got the same error and here how I solved it, by adding the following to your spring controller:

@CrossOrigin(origins = {"http://localhost:3000"})

Process with an ID #### is not running in visual studio professional 2013 update 3

Deleting the hidden .vs folder didn't work for me since the port specified in my app was being used by another app. Doing the following worked for me:

  1. Went to properties and then click the web tab.
  2. Changed the port number in the Start Url and the Project URL.
  3. Clicked Create Virtual Directory.
  4. Save and Press F5.

What is Java String interning?

String interning is an optimization technique by the compiler. If you have two identical string literals in one compilation unit then the code generated ensures that there is only one string object created for all the instance of that literal(characters enclosed in double quotes) within the assembly.

I am from C# background, so i can explain by giving a example from that:

object obj = "Int32";
string str1 = "Int32";
string str2 = typeof(int).Name;

output of the following comparisons:

Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true    
Console.WriteLine(obj == str2); // false !?

Note1:Objects are compared by reference.

Note2:typeof(int).Name is evaluated by reflection method so it does not gets evaluated at compile time. Here these comparisons are made at compile time.

Analysis of the Results: 1) true because they both contain same literal and so the code generated will have only one object referencing "Int32". See Note 1.

2) true because the content of both the value is checked which is same.

3) FALSE because str2 and obj does not have the same literal. See Note 2.

How to make a Java thread wait for another thread's output?

You could do it using an Exchanger object shared between the two threads:

private Exchanger<String> myDataExchanger = new Exchanger<String>();

// Wait for thread's output
String data;
try {
  data = myDataExchanger.exchange("");
} catch (InterruptedException e1) {
  // Handle Exceptions
}

And in the second thread:

try {
    myDataExchanger.exchange(data)
} catch (InterruptedException e) {

}

As others have said, do not take this light-hearted and just copy-paste code. Do some reading first.

Can an AJAX response set a cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

Forward declaring an enum in C++

I'd do it this way:

[in the public header]

typedef unsigned long E;

void Foo(E e);

[in the internal header]

enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,
  FORCE_32BIT = 0xFFFFFFFF };

By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.

What are the git concepts of HEAD, master, origin?

I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.

HEAD: the current commit your repo is on. Most of the time HEAD points to the latest commit in your current branch, but that doesn't have to be the case. HEAD really just means "what is my repo currently pointing at".

In the event that the commit HEAD refers to is not the tip of any branch, this is called a "detached head".

master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.

origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.

HEAD is an official notion in git. HEAD always has a well-defined meaning. master and origin are common names usually used in git, but they don't have to be.

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

Android Studio: Gradle: error: cannot find symbol variable

If you are using multiple flavors?

-make sure the resource file is not declared/added both in only one of the flavors and in main.

Example: a_layout_file.xml file containing the symbol variable(s)

src:

flavor1/res/layout/(no file)

flavor2/res/layout/a_layout_file.xml

main/res/layout/a_layout_file.xml

This setup will give the error: cannot find symbol variable, this is because the resource file can only be in both flavors or only in the main.

How to send data in request body with a GET when using jQuery $.ajax()

we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.

1.GET use of Query string as. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.

2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.

3.GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

How to split() a delimited string to a List<String>

string[] thisArray = myString.Split('/');//<string1/string2/string3/--->     
List<string> myList = new List<string>(); //make a new string list    
myList.AddRange(thisArray);    

Use AddRange to pass string[] and get a string list.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

function setDate(){
    var now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    var timeToSet = now.toISOString().slice(0,16);

    /*
        If you have an element called "eventDate" like the following:

        <input type="datetime-local" name="eventdate" id="eventdate" />

        and you would like to  set the current and minimum time then use the following:
    */

    var elem = document.getElementById("eventDate");
    elem.value = timeToSet;
    elem.min = timeToSet;
}

Convert.ToDateTime: how to set format

You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;

var result = Convert.ToDateTime("12/01/2011", usDtfi)

SQL Update Multiple Fields FROM via a SELECT Statement

You should be able to do something along the lines of the following

UPDATE s
SET
    OrgAddress1 = bd.OrgAddress1,
    OrgAddress2 = bd.OrgAddress2,
    ...
    DestZip = bd.DestZip
FROM
    Shipment s, ProfilerTest.dbo.BookingDetails bd
WHERE
    bd.MyID = @MyId AND s.MyID2 = @MyID2

FROM statement can be made more optimial (using more specific joins), but the above should do the trick. Also, a nice side benefit to writing it this way, to see a preview of the UPDATE change UPDATE s SET to read SELECT! You will then see that data as it would appear if the update had taken place.

How to compare 2 dataTables

The OP, MAW74656, originally posted this answer in the question body in response to the accepted answer, as explained in this comment:

I used this and wrote a public method to call the code and return the boolean.

The OP's answer:

Code Used:

public bool tablesAreTheSame(DataTable table1, DataTable table2)
{
    DataTable dt;
    dt = getDifferentRecords(table1, table2);

    if (dt.Rows.Count == 0)
        return true;
    else
        return false;
}

//Found at http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html
private DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
    //Create Empty Table     
    DataTable ResultDataTable = new DataTable("ResultDataTable");

    //use a Dataset to make use of a DataRelation object     
    using (DataSet ds = new DataSet())
    {
        //Add tables     
        ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });

        //Get Columns for DataRelation     
        DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
        for (int i = 0; i < firstColumns.Length; i++)
        {
            firstColumns[i] = ds.Tables[0].Columns[i];
        }

        DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
        for (int i = 0; i < secondColumns.Length; i++)
        {
            secondColumns[i] = ds.Tables[1].Columns[i];
        }

        //Create DataRelation     
        DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
        ds.Relations.Add(r1);

        DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
        ds.Relations.Add(r2);

        //Create columns for return table     
        for (int i = 0; i < FirstDataTable.Columns.Count; i++)
        {
            ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
        }

        //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.     
        ResultDataTable.BeginLoadData();
        foreach (DataRow parentrow in ds.Tables[0].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r1);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }

        //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.     
        foreach (DataRow parentrow in ds.Tables[1].Rows)
        {
            DataRow[] childrows = parentrow.GetChildRows(r2);
            if (childrows == null || childrows.Length == 0)
                ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
        }
        ResultDataTable.EndLoadData();
    }

    return ResultDataTable;
}

Deleting an SVN branch

Sure: svn rm the unwanted folder, and commit.

To avoid this situation in the future, I would follow the recommended layout for SVN projects:

  • Put your code in the /someproject/trunk folder (or just /trunk if you want to put only one project in the repository)
  • Created branches as /someproject/branches/somebranch
  • Put tags under /someproject/tags

Now when you check out a working copy, be sure to check out only trunk or some individual branch. Don't check everything out in one huge working copy containing all branches.1

1Unless you know what you're doing, in which case you know how to create shallow working copies.

display data from SQL database into php/ html table

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}

UPDATED FUNCTION BELOW

Hi Jack,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

You can avoid that by moving the if condition above the second foreach loop like this:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

See :hover state in Chrome Developer Tools

I wanted to see the hover state on my Bootstrap tooltips. Forcing the the :hover state in Chrome dev Tools did not create the required output, yet triggering the mouseenter event via console did the trick in Chrome. If jQuery exists on the page you can run:

$('.YOUR-TOOL-TIP-CLASS').trigger('mouseenter');

Forcing hover or mouseenter for Bootstrap Tooltips

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

How do I vertically align text in a paragraph?

So personally I'm not sure of the best-method way, but one thing I have found works well for vertical alignment is using Flex, as you can justify it's content!

Let's say you have the following HTML and CSS:

_x000D_
_x000D_
.paragraph { 
      font-weight: light;
      color: gray;
      min-height: 6rem;
      background: lightblue;
  }
_x000D_
<h1 class="heading"> Nice to meet you! </h1>
<p class="paragraph"> This is a paragraph </p>
_x000D_
_x000D_
_x000D_

We end up with a paragraph that isn't vertically centered, now if we use a Flex Column and apply the min height + BG to that we get the following:

_x000D_
_x000D_
.myflexbox {
    min-height: 6rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background: lightblue;
}

.paragraph { 
      font-weight: light;
      color: gray;
  }
_x000D_
<h1 class="heading"> Nice to meet you! </h1>
<div class="myflexbox">
    <p class="paragraph"> This is a paragraph </p>
</div>
_x000D_
_x000D_
_x000D_

However, in some situations you can't just wrap the P tag in a div so easily, well using Flexbox on the P tag is perfectly fine even if it's not the nicest practice.

_x000D_
_x000D_
.myflexparagraph {
    min-height: 6rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background: lightblue;
}

.paragraph { 
      font-weight: light;
      color: gray;
  }
_x000D_
<h1 class="heading"> Nice to meet you! </h1>
<p class="paragraph myflexparagraph"> This is a paragraph </p>
_x000D_
_x000D_
_x000D_

I have no clue if this is good or bad but if this helps only one person somewhere that's still one more then naught!

Is there a way to make mv create the directory to be moved to if it doesn't exist?

I frequently stumble upon this issue while bulk moving files to new subdirectories. Ideally, I want to do this:

mv * newdir/  

Most of the answers in this thread propose to mkdir and then mv, but this results in:

mkdir newdir && mv * newdir 
mv: cannot move 'newdir/' to a subdirectory of itself

The problem I face is slightly different in that I want to blanket move everything, and, if I create the new directory before moving then it also tries to move the new directory to itself. So, I work around this by using the parent directory:

mkdir ../newdir && mv * ../newdir && mv ../newdir .

Caveats: Does not work in the root folder (/).

error 1265. Data truncated for column when trying to load data from txt file

I have met this problem with a column that has ENUM values('0','1').
When I was trying to save a new record, I was assigning value 0 for the ENUM variable.

For the solution: I have changed ENUM variable value from 0 to 1, and 1 to 2.

Bootstrap carousel resizing image

I had the same problem. You have to use all the images with same height and width. you can simply change it using paint application from windows using the resize option in the home section and then use CSS to resize the image. Maybe this problem occurs because the the width and height attribute inside the tag is not responding.

Detect element content changes with jQuery

Try to bind to the DOMSubtreeModified event seeign as test is also just part of the DOM.

see this post here on SO:

how-do-i-monitor-the-dom-for-changes

What does $@ mean in a shell script?

Meaning.

In brief, $@ expands to the positional arguments passed from the caller to either a function or a script. Its meaning is context-dependent: Inside a function, it expands to the arguments passed to such function. If used in a script (not inside the scope a function), it expands to the arguments passed to such script.

$ cat my-sh
#! /bin/sh
echo "$@"

$ ./my-sh "Hi!"
Hi!
$ put () ( echo "$@" )
$ put "Hi!"
Hi!

Word splitting.

Now, another topic that is of paramount importance when understanding how $@ behaves in the shell is word splitting. The shell splits tokens based on the contents of the IFS variable. Its default value is \t\n; i.e., whitespace, tab, and newline.

Expanding "$@" gives you a pristine copy of the arguments passed. However, expanding $@ will not always. More specifically, if the arguments contain characters from IFS, they will split.


Most of the time what you will want to use is "$@", not $@.

Compare DATETIME and DATE ignoring time portion

For Compare two date like MM/DD/YYYY to MM/DD/YYYY . Remember First thing column type of Field must be dateTime. Example : columnName : payment_date dataType : DateTime .

after that you can easily compare it. Query is :

select  *  from demo_date where date >= '3/1/2015' and date <=  '3/31/2015'.

It very simple ...... It tested it.....

How to Batch Rename Files in a macOS Terminal?

In your specific case you can use the following bash command (bash is the default shell on macOS):

for f in *.png; do echo mv "$f" "${f/_*_/_}"; done

Note: If there's a chance that your filenames start with -, place -- before them[1]:
mv -- "$f" "${f/_*_/_}"

Note: echo is prepended to mv so as to perform a dry run. Remove it to perform actual renaming.

You can run it from the command line or use it in a script.

  • "${f/_*_/_}" is an application of bash parameter expansion: the (first) substring matching pattern _*_ is replaced with literal _, effectively cutting the middle token from the name.
  • Note that _*_ is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, run man bash and search for Pattern Matching).

If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based rename utility. On macOS you can install it using popular package manager Homebrew as follows:

brew install rename

Here's the equivalent of the command at the top using rename:

rename -n -e 's/_.*_/_/'  *.png

Again, this command performs a dry run; remove -n to perform actual renaming.

  • Similar to the bash solution, s/.../.../ performs text substitution, but - unlike in bash - true regular expressions are used.

[1] The purpose of special argument --, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with -, as Jacob C. notes.

Handling back button in Android Navigation Component

I written in main activity like this,

override fun onSupportNavigateUp(): Boolean {
        return findNavController(R.id.my_nav_host_fragment).navigateUp(appBarConfiguration)
    }   

Semi-transparent color layer over background-image?

You can use a semitransparent pixel, which you can generate for example here, even in base64 Here is an example with white 50%:

background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8Xw8AAoMBgDTD2qgAAAAASUVORK5CYII=),
url(../img/leftpanel/intro1.png);
background-size: cover, cover;
  • without uploading

  • without extra html

  • i guess the loading should be quicker than box-shadow or linear gradient

Set CSS property in Javascript?

if you want to add a global property, you can use:

    var styleEl = document.createElement('style'), styleSheet;
            document.head.appendChild(styleEl);
            styleSheet = styleEl.sheet;
            styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);

! [rejected] master -> master (fetch first)

Its Simple use this command:

git push -f origin master

and it will get your work done

Generate MD5 hash string with T-SQL

CONVERT(VARCHAR(32), HashBytes('MD5', '[email protected]'), 2)

What is the difference between __init__ and __call__?

__init__ would be treated as Constructor where as __call__ methods can be called with objects any number of times. Both __init__ and __call__ functions do take default arguments.

This could be due to the service endpoint binding not using the HTTP protocol

If you have a database(working in visual studio), make sure there are no foreign keys in the tables, I had foreign keys and it gave me this error and when I removed them it ran smoothly

How do I find the current machine's full hostname in C (hostname and domain information)?

The easy way, try uname()

If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()

The h_name of hostent{} should be your FQDN

how to make a div to wrap two float divs inside?

Here's another, I found helpful. It works even for Responsive CSS design too.

#wrap
{
   display: table;
   table-layout: fixed; /* it'll enable the div to be responsive */
   width: 100%; /* as display table will shrink the div to content-wide */
}

WARNING: But this theory won't work for holder contains inner elements with absolute positions. And it will create problem for fixed-width layout. But for responsive design, it's just excellent. :)

ADDITION TO Meep3D's ANSWER

With CSS3, in a dynamic portion, you can add clear float to the last element by:

#wrap [class*='my-div-class']:last-of-type {
  display: block;
  clear: both;
}

Where your divs are:

<div id="wrap">
<?php for( $i = 0; $i < 3; $i++ ) {
   <div class="my-div-class-<?php echo $i ?>>
      <p>content</p>
   </div> <!-- .my-div-class-<?php echo $i ?> -->
}
</div>

Reference:

Centering the image in Bootstrap

.img-responsive {
     margin: 0 auto;
 }

you can write like above code in your document so no need to add one another class in image tag.

Android Studio installation on Windows 7 fails, no JDK found

If you have a 64 bit windows OS, pointing the JAVA_HOME system variable to

C:\Program Files (x86)\Java\jdk1.7.0_21

Will work when

C:\Program Files\Java\jdk1.7.0_21

fails to work.

How to change line width in IntelliJ (from 120 character)

Be aware that need to change both location:

File > Settings... > Editor > Code Style > "Hard Wrap at"

and

File > Settings... > Editor > Code Style > (your language) > Wrapping and Braces > Hard wrap at

formGroup expects a FormGroup instance

I was facing this issue and fixed by putting a check in form attribute. This issue can happen when the FormGroup is not initialized.

<form [formGroup]="loginForm" *ngIf="loginForm">
OR
<form [formGroup]="loginForm" *ngIf="this.loginForm">

This will not render the form until it is initialized.

Freemarker iterating over hashmap keys

Iterating Objects

If your map keys is an object and not an string, you can iterate it using Freemarker.

1) Convert the map into a list in the controller:

List<Map.Entry<myObjectKey, myObjectValue>> convertedMap  = new ArrayList(originalMap.entrySet());

2) Iterate the map in the Freemarker template, accessing to the object in the Key and the Object in the Value:

<#list convertedMap as item>
    <#assign myObjectKey = item.getKey()/>
    <#assign myObjectValue = item.getValue()/>
    [...]
</#list>

Insert text with single quotes in PostgreSQL

This is so many worlds of bad, because your question implies that you probably have gaping SQL injection holes in your application.

You should be using parameterized statements. For Java, use PreparedStatement with placeholders. You say you don't want to use parameterised statements, but you don't explain why, and frankly it has to be a very good reason not to use them because they're the simplest, safest way to fix the problem you are trying to solve.

See Preventing SQL Injection in Java. Don't be Bobby's next victim.

There is no public function in PgJDBC for string quoting and escaping. That's partly because it might make it seem like a good idea.

There are built-in quoting functions quote_literal and quote_ident in PostgreSQL, but they are for PL/PgSQL functions that use EXECUTE. These days quote_literal is mostly obsoleted by EXECUTE ... USING, which is the parameterised version, because it's safer and easier. You cannot use them for the purpose you explain here, because they're server-side functions.


Imagine what happens if you get the value ');DROP SCHEMA public;-- from a malicious user. You'd produce:

insert into test values (1,'');DROP SCHEMA public;--');

which breaks down to two statements and a comment that gets ignored:

insert into test values (1,'');
DROP SCHEMA public;
--');

Whoops, there goes your database.

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Our server calls stored procs from Java like so - works on both SQL Server 2000 & 2008:

String SPsql = "EXEC <sp_name> ?,?";   // for stored proc taking 2 parameters
Connection con = SmartPoolFactory.getConnection();   // java.sql.Connection
PreparedStatement ps = con.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(<timeout value>);
ps.setString(1, <param1>);
ps.setString(2, <param2>);
ResultSet rs = ps.executeQuery();

How to count number of unique values of a field in a tab-delimited text file?

You can use awk, sort & uniq to do this, for example to list all the unique values in the first column

awk < test.txt '{print $1}' | sort | uniq

As posted elsewhere, if you want to count the number of instances of something you can pipe the unique list into wc -l

FirstOrDefault: Default value other than null

Actually, I use two approaches to avoid NullReferenceException when I'm working with collections:

public class Foo
{
    public string Bar{get; set;}
}
void Main()
{
    var list = new List<Foo>();
    //before C# 6.0
    string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;
    //C# 6.0 or later
    var barCSharp6 = list.FirstOrDefault()?.Bar;
}

For C# 6.0 or later:

Use ?. or ?[ to test if is null before perform a member access Null-conditional Operators documentation

Example: var barCSharp6 = list.FirstOrDefault()?.Bar;

C# older version:

Use DefaultIfEmpty() to retrieve a default value if the sequence is empty.MSDN Documentation

Example: string barCSharp5 = list.DefaultIfEmpty(new Foo()).FirstOrDefault().Bar;

How to round up with excel VBA round()?

The answers here are kind of all over the map, and try to accomplish several different things. I'll just point you to the answer I recently gave that discusses the forced rounding UP -- i.e., no rounding toward zero at all. The answers in here cover different types of rounding, and ana's answer for example is for forced rounding up.

To be clear, the original question was how to "round normally" -- so, "for value > 0.5, round up. And for value < 0.5, round down".

The answer that I link to there discusses forced rounding up, which you sometimes also want to do. Whereas Excel's normal ROUND uses round-half-up, its ROUNDUP uses round-away-from-zero. So here are two functions that imitate ROUNDUP in VBA, the second of which only rounds to a whole number.

Function RoundUpVBA(InputDbl As Double, Digits As Integer) As Double

    If InputDbl >= O Then
        If InputDbl = Round(InputDbl, Digits) Then RoundUpVBA = InputDbl Else RoundUpVBA = Round(InputDbl + 0.5 / (10 ^ Digits), Digits)
    Else
        If InputDbl = Round(InputDbl, Digits) Then RoundUpVBA = InputDbl Else RoundUpVBA = Round(InputDbl - 0.5 / (10 ^ Digits), Digits)
    End If

End Function

Or:

Function RoundUpToWhole(InputDbl As Double) As Integer

    Dim TruncatedDbl As Double

    TruncatedDbl = Fix(InputDbl)

    If TruncatedDbl <> InputDbl Then
        If TruncatedDbl >= 0 Then RoundUpToWhole = TruncatedDbl + 1 Else RoundUpToWhole = TruncatedDbl - 1
    Else
        RoundUpToWhole = TruncatedDbl
    End If

End Function

Some of the answers above cover similar territory, but these here are self-contained. I also discuss in my other answer some one-liner quick-and-dirty ways to round up.

Float vs Decimal in ActiveRecord

In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.

The lesson learned is "always use homogeneous development and deployment databases!"

Python: Ignore 'Incorrect padding' error when base64 decoding

"Incorrect padding" can mean not only "missing padding" but also (believe it or not) "incorrect padding".

If suggested "adding padding" methods don't work, try removing some trailing bytes:

lens = len(strg)
lenx = lens - (lens % 4 if lens % 4 else 4)
try:
    result = base64.decodestring(strg[:lenx])
except etc

Update: Any fiddling around adding padding or removing possibly bad bytes from the end should be done AFTER removing any whitespace, otherwise length calculations will be upset.

It would be a good idea if you showed us a (short) sample of the data that you need to recover. Edit your question and copy/paste the result of print repr(sample).

Update 2: It is possible that the encoding has been done in an url-safe manner. If this is the case, you will be able to see minus and underscore characters in your data, and you should be able to decode it by using base64.b64decode(strg, '-_')

If you can't see minus and underscore characters in your data, but can see plus and slash characters, then you have some other problem, and may need the add-padding or remove-cruft tricks.

If you can see none of minus, underscore, plus and slash in your data, then you need to determine the two alternate characters; they'll be the ones that aren't in [A-Za-z0-9]. Then you'll need to experiment to see which order they need to be used in the 2nd arg of base64.b64decode()

Update 3: If your data is "company confidential":
(a) you should say so up front
(b) we can explore other avenues in understanding the problem, which is highly likely to be related to what characters are used instead of + and / in the encoding alphabet, or by other formatting or extraneous characters.

One such avenue would be to examine what non-"standard" characters are in your data, e.g.

from collections import defaultdict
d = defaultdict(int)
import string
s = set(string.ascii_letters + string.digits)
for c in your_data:
   if c not in s:
      d[c] += 1
print d

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

Pure css close button

I become frustrated trying to implement something that looked consistent in all browsers and went with an svg button which can be styled with css.

html

<svg>
    <circle cx="12" cy="12" r="11" stroke="black" stroke-width="2" fill="white" />
    <path stroke="black" stroke-width="4" fill="none" d="M6.25,6.25,17.75,17.75" />
    <path stroke="black" stroke-width="4" fill="none" d="M6.25,17.75,17.75,6.25" />
</svg>

css

svg {
    cursor: pointer;
    height: 24px;
    width: 24px;
}
svg > circle {
    stroke: black;
    fill: white;
}
svg > path {
    stroke: black;
}
svg:hover > circle {
    fill: red;
}
svg:hover > path {
    stroke: white;
}

http://jsfiddle.net/purves/5exav2m7/

How to get Top 5 records in SqLite?

Select TableName.* from  TableName DESC LIMIT 5

Looping from 1 to infinity in Python

Simplest and best:

i = 0
while not there_is_reason_to_break(i):
    # some code here
    i += 1

It may be tempting to choose the closest analogy to the C code possible in Python:

from itertools import count

for i in count():
    if thereIsAReasonToBreak(i):
        break

But beware, modifying i will not affect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.

Assembly code vs Machine code vs Object code?

8B 5D 32 is machine code

mov ebx, [ebp+32h] is assembly

lmylib.so containing 8B 5D 32 is object code

Breaking up long strings on multiple lines in Ruby without stripping newlines

I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:

%W[
  It's a nice day "#{name}"
  for a walk!
].join(' ')

where name = 'fred' this produces It's a nice day "fred" for a walk!

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

What is the best way to modify a list in a 'foreach' loop?

You can't change the enumerable collection while it is being enumerated, so you will have to make your changes before or after enumerating.

The for loop is a nice alternative, but if your IEnumerable collection does not implement ICollection, it is not possible.

Either:

1) Copy collection first. Enumerate the copied collection and change the original collection during the enumeration. (@tvanfosson)

or

2) Keep a list of changes and commit them after the enumeration.

How to create an ArrayList from an Array in PowerShell?

Probably the shortest version:

[System.Collections.ArrayList]$someArray

It is also faster because it does not call relatively expensive New-Object.

Recursively looping through an object to build a property list

A simple path global variable across each recursive call does the trick for me !

_x000D_
_x000D_
var object = {
  aProperty: {
    aSetting1: 1,
    aSetting2: 2,
    aSetting3: 3,
    aSetting4: 4,
    aSetting5: 5
  },
  bProperty: {
    bSetting1: {
      bPropertySubSetting: true
    },
    bSetting2: "bString"
  },
  cProperty: {
    cSetting: "cString"
  }
}

function iterate(obj, path = []) {
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (typeof obj[property] == "object") {
        let curpath = [...path, property];
        iterate(obj[property], curpath);
      } else {
        console.log(path.join('.') + '.' + property + "   " + obj[property]);
        $('#output').append($("<div/>").text(path.join('.') + '.' + property))
      }
    }
  }
}

iterate(object);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<div id='output'></div>
_x000D_
_x000D_
_x000D_

Accessing JSON elements

Here's an alternative solution using requests:

import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']

How do I get into a Docker container's shell?

SSH into a Docker container using this command:

sudo docker exec -i -t (container ID) bash

How do I test axios in Jest?

For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:

File actions.test.js:

describe('SignInUser', () => {
  var history = {
    push: function(str) {
        expect(str).toEqual('/feed');
    }
  }

  it('Dispatches authorization', () => {
    let mock = new MockAdapter(axios);
    mock.onPost(`${ROOT_URL}/auth/signin`, {
        email: '[email protected]',
        password: 'test'
    }).reply(200, {token: 'testToken' });

    const expectedActions = [ { type: types.AUTH_USER } ];
    const store = mockStore({ auth: [] });

    return store.dispatch(actions.signInUser({
        email: '[email protected]',
        password: 'test',
      }, history)).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
  });

});

In order to test a successful case for signInUser in file actions/index.js:

export const signInUser = ({ email, password }, history) => async dispatch => {
  const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
    .catch(({ response: { data } }) => {
        ...
  });

  if (res) {
    dispatch({ type: AUTH_USER });                 // Test verified this
    localStorage.setItem('token', res.data.token); // Test mocked this
    history.push('/feed');                         // Test mocked this
  }
}

Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:

const localStorageMock = {
  removeItem: jest.fn(),
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;

The module was expected to contain an assembly manifest

I found that, I am using a different InstallUtil from my target .NET Framework. I am building a .NET Framework 4.5, meanwhile the error occured if I am using the .NET Framework 2.0 release. Having use the right InstallUtil for my target .NET Framework, solved this problem!

How can I autoplay a video using the new embed code style for Youtube?

Just add ?autoplay=1 after url in embed code, example :

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0" frameborder="0"></iframe>

Change it to:

<iframe width="420" height="315" src="http://www.youtube.com/embed/
oHg5SJYRHA0?autoplay=1" frameborder="0"></iframe>

Producer/Consumer threads using a Queue

You are reinventing the wheel.

If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).

If you need fast in-memory queues use one of the impementations of java's Queue.

If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.

C# Creating an array of arrays

I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.

How to create custom spinner like border around the spinner with down triangle on the right side?

You can achieve the following by using a single line in your spinner declaration in XML: enter image description here

Just add this: style="@android:style/Widget.Holo.Light.Spinner"

This is a default generated style in android. It doesn't contain borders around it though. For that you'd better search something on google.

Hope this helps.

UPDATE: AFter a lot of digging I got something which works well for introducing border around spinner.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="8dp"
        android:top="8dp">
        <shape>
            <solid android:color="@android:color/white" />
            <corners android:radius="4dp" />
            <stroke
                android:width="2dp"
                android:color="#9E9E9E" />
            <padding
                android:bottom="16dp"
                android:left="8dp"
                android:right="16dp"
                android:top="16dp" />
        </shape>
    </item>
</layer-list>

Place this in the drawable folder and use it as a background for spinner. Like this:

<RelativeLayout
        android:id="@+id/speaker_relative_layout"
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:background="@drawable/spinner_style"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Spinner
            android:id="@+id/select_speaker_spinner"
            style="@style/Widget.AppCompat.DropDownItem.Spinner"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:entries="@array/select_speaker_spinner_array"
            android:spinnerMode="dialog" />

    </RelativeLayout>

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

If your issue is with linked servers, you need to look at a few things.

First, your users need to have delegation enabled and if the only thing that's changed, it'l likely they do. Otherwise you can uncheck the "Account is sensitive and cannot be delegated" checkbox is the user properties in AD.

Second, your service account(s) must be trusted for delegation. Since you recently changed your service account I suspect this is the culprit. (http://technet.microsoft.com/en-us/library/cc739474(v=ws.10).aspx)

You mentioned that you might have some SPN issues, so be sure to set the SPN for both endpoints, otherwise you will not be able to see the delegation tab in AD. Also make sure you're in advanced view in "Active Directory Users and Computers."

If you still do not see the delegation tab, even after correcting your SPN, make sure your domain not in 2000 mode. If it is, you can "raise domain function level."

At this point, you can now mark the account as trusted for delegation:

In the details pane, right-click the user you want to be trusted for delegation, and click Properties.

Click the Delegation tab, select the Account is trusted for delegation check box, and then click OK.

Finally you will also need to set all the machines as trusted for delegation.

Once you've done this, reconnect to your sql server and test your liked servers. They should work.

right click context menu for datagridview

Follow the steps:

  1. Create a context menu like: Sample context menu

  2. User needs to right click on the row to get this menu. We need to handle the _MouseClick event and _CellMouseDown event.

selectedBiodataid is the variable that contains the selected row information.

Here is the code:

private void dgrdResults_MouseClick(object sender, MouseEventArgs e)
{   
    if (e.Button == System.Windows.Forms.MouseButtons.Right)
    {                      
        contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
    }   
}

private void dgrdResults_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    //handle the row selection on right click
    if (e.Button == MouseButtons.Right)
    {
        try
        {
            dgrdResults.CurrentCell = dgrdResults.Rows[e.RowIndex].Cells[e.ColumnIndex];
            // Can leave these here - doesn't hurt
            dgrdResults.Rows[e.RowIndex].Selected = true;
            dgrdResults.Focus();

            selectedBiodataId = Convert.ToInt32(dgrdResults.Rows[e.RowIndex].Cells[1].Value);
        }
        catch (Exception)
        {

        }
    }
}

and the output would be:

Final output

How to dismiss a Twitter Bootstrap popover by clicking outside?

jQuery("#menu").click(function(){ return false; });
jQuery(document).one("click", function() { jQuery("#menu").fadeOut(); });

How do I strip all spaces out of a string in PHP?

str_replace will do the trick thusly

$new_str = str_replace(' ', '', $old_str);