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.
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).
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.
The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.
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.
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!
You can use result.className = 'red';
, but you can also use result.classList.add('red');
. The .classList.add(str)
way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.
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.
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;} );
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
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"/>
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.
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
<%= 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
Since nullptr
is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.
I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.
To run the code in setNum
you have to call it. If you don't call it, the default value is 0
.
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.
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
This should do it:
#!/usr/local/cpython-2.7/bin/python # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print "\nHow much space should the random song list occupy?\n" print "1. 100Mb" print "2. 250Mb\n" tSizeAns = int(raw_input()) if tSizeAns == 1: tSize = "100Mb" elif tSizeAns == 2: tSize = "250Mb" else: tSize = "100Mb" # in case user fails to enter either a 1 or 2 print "\nYou want to create a random song list that is {}.".format(tSize)
BTW, in case you're open to moving to Python 3.x, the differences are slight:
#!/usr/local/cpython-3.3/bin/python # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print("\nHow much space should the random song list occupy?\n") print("1. 100Mb") print("2. 250Mb\n") tSizeAns = int(input()) if tSizeAns == 1: tSize = "100Mb" elif tSizeAns == 2: tSize = "250Mb" else: tSize = "100Mb" # in case user fails to enter either a 1 or 2 print("\nYou want to create a random song list that is {}.".format(tSize))
HTH
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.
This regex should do it.
\b[a-z]+-[a-z]+\b
\b
indicates a word-boundary.
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.
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.
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.
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
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"
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);
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();
No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?
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.
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (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.
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.
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');
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
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.
You can use Jquery's on method and listen for the scroll
event.
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
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.)
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(.,'"','''')"/> </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(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
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:
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.
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?
preg_replace('/^[^:\/?]+:\/\//','',$url);
some results:
input: http://php.net/preg_replace output: php.net/preg_replace input: https://www.php.net/preg_replace output: www.php.net/preg_replace input: ftp://www.php.net/preg_replace output: www.php.net/preg_replace input: https://php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net/preg_replace?url=http://whatever.com output: php.net/preg_replace?url=http://whatever.com input: php.net?site=http://whatever.com output: php.net?site=http://whatever.com
Thank you guys for the help,
When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:
I believe that you are looking for the java.lang.BigDecimal class.
being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -
eventually decided to use CLINT as an answer that was given there by great and smart people
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.
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.
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.
There should be three pages here:
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).
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.
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.
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.
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
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.
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;
{ "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.
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.
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
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); }
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
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
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); } }
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
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)
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.
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);
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.
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.
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.
As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:
xlrd has explicitly removed support for anything other than xls files.
In your case, the solution is to:
openpyxl
: https://openpyxl.readthedocs.io/en/stable/df1 = pd.read_excel(
os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
engine='openpyxl',
)
This error occurs when versions of NodeJS and Node Sass are not matched.
you can resolve your issue by doing as below:
- Step 1: Remove Nodejs from your computer
- Step 2: Reinstall Nodejs version 14.15.1.
- Step 3: Uninstall Node sass by run the command npm uninstall node-sass
- Step 4: Reinstall Node sass version 4.14.1 by run the command npm install [email protected]
After all steps, you can run command ng serve -o
to run your application.
I found that
Build Active Architecture Only
set to YES
for everything, in both Project and Targetpodfile
:post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings["ONLY_ACTIVE_ARCH"] = "YES"
end
end
end
worked for me.
We had both Pods and SPM and they didn't work with any of the combinations of other answers. My colleagues all use Intel MacBooks and we haven't tested this config on their computers, though.
I am using an iPhone SE iOS 13.6.1 and Xcode 13.5 and I faced the same issue. While the iPhone is not available. Please reconnect the device
warning window is open, I turned off the iPhone, reopened and rebuilt the Xcode project, Trust
ed in the iPhone and my problem was solved.
You need to open chrome in developper mode : select more tools then extensions and select developper mode
Goto You Chrome setting->About Chorme->Check version and download chromedriver from Below according your chrome Version https://chromedriver.chromium.org/downloads
npm cache clean --force
-> cleaning the cache maybe solve the issue.
I didn't want to upgrade react-scripts
, so I used the 3rd party reinstall npm module to reinstall it, and it worked.
npm i -g npm-reinstall
reinstall react-scripts
Adding skipLibCheck: true
in compilerOptions
inside tsconfig.json
file fixed my issue.
"compilerOptions": {
"skipLibCheck": true,
},
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
This solution worked for me :
I preinstalled the environnement with anaconda (here is the code)
conda create -n YOURENVNAME python=3.6 // 3.6> incompatible with keras
conda activate YOURENVNAME
conda install tensorflow-gpu
conda install -c anaconda keras
conda install -c anaconda scikit-learn
conda install matplotlib
but after I had still these warnings
2020-02-23 13:31:44.910213: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-02-23 13:31:44.925815: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll
2020-02-23 13:31:44.941384: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll
2020-02-23 13:31:44.947427: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll
2020-02-23 13:31:44.965893: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll
2020-02-23 13:31:44.982990: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll
2020-02-23 13:31:44.990036: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudnn64_7.dll'; dlerror: cudnn64_7.dll not found
How I solved the first warning : I just download a zip file wich contained all the cudnn files (dll, etc) here : https://developer.nvidia.com/cudnn
How I solved the second warning : I looked the last missing file (cudart64_101.dll) in my virtual env created by conda and I just copy/pasted it in the same lib folder than for the .dll cudnn
Try to hit the below URL in any browser. It will return 501
http://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-ssh/2.1/wagon-ssh-2.1.pom
Please try with https. It will download a pom.xml file:
https://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-ssh/2.1/wagon-ssh-2.1.pom
Please add it (https://repo.maven.apache.org/maven2) in the setting.xml file:
<repositories>
<repository>
<id>Central Maven repository</id>
<name>Central Maven repository https</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
You need to set language level, release version and add maven compiler plugin to the pom.xml
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
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:
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)
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).
Such a weird problem because this worked for me yesterday and I came across the same error this morning. Based on the release notes, a new feature was added to support templates so it looks like a few parts have changed in the command line (for example, the --typescript
was deprecated in favor of using --template typescript
)
I did manage to get it all working by doing the following:
npm uninstall create-react-app -g
.npm cache verify
.npx create-react-app my-app --template typescript
If it works, you should see multiple installs: one for react-scripts and one for the template. The error message should also no longer appear.
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;
}
brew switch openssl 1.0.2s
worked for me on "macOS Mojave", "version 10.14.6".
In Case your running nodemon for the node version 12 ,use this command.
server.js is the "main" inside package.json
file ,replace it with relevant file inside your package.json file
nodemon --experimental-modules server.js
This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.
It has nothing to do with your code. It is something their web servers will have to support.
Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site
February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.
For the full Chrome release schedule, see here.
I solved same problem by adding in response header
response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
SameSite
prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.
SameSite cookies explained here
Please refer this before applying any option.
Hope this helps you.
This error is currently being fixed: https://chromium-review.googlesource.com/c/chromium/src/+/2001234
But it helped me, changing nginx settings:
In my case, Nginx acts as a reverse proxy for Node.js application.
I was also facing the same issue until I added the type="module" to the script.
Before it was like this
<script src="../src/main.js"></script>
And after changing it to
<script type="module" src="../src/main.js"></script>
It worked perfectly.
I also encountered similar problem which is asked here. The issue was that some applications come with their own JRE and sometimes the installed JDK appears at lower priority level in environment path. Now there are two options:
I also removed the path as suggested by @CrazyCoder
This is caused by node v12.11.0 due to the way it deals regular location there two ways to solve this problem
Method I
You can downgrade to node v12.10.0 this will apply the correct way to deal with parsing error
Method II
You can correctly terminate the regular expression in you case by changing the file located a:
\node_modules\metro-config\src\defaults\blacklist.js
From:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
To:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
I solved my problem by running below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
In my case problem arose due to gradle version upgradation from 6.2 all to 6.6 all in gradle wrapper. So i wiped out data of avd and restarted it and then deleted .gradle folder in android/.gradle and then run yarn start --reset-cache and yarn android. Then it worked for me
In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
mask = np.zeros(edges.shape)
to
mask = np.zeros(edges.shape,dtype='uint8')
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
Well I am not a python guy nor I know what is the actual use of this 'Colab', I use it as a build system lol. And I used to setup ssh forwarding in it then put this code and just leave it running and yeah it works.
import getpass
authtoken = getpass.getpass()
I have made a simulation of the problem. looks like the issue is how we should Access Object Properties Dynamically Using Bracket Notation in Typescript
interface IUserProps {
name: string;
age: number;
}
export default class User {
constructor(private data: IUserProps) {}
get(propName: string): string | number {
return this.data[propName as keyof IUserProps];
}
}
I found a blog that might be helpful to understand this better.
here is a link https://www.nadershamma.dev/blog/2019/how-to-access-object-properties-dynamically-using-bracket-notation-in-typescript/
Run PowerShell or command prompt as Administrator and run below command.
dotnet tool install --global dotnet-ef --version 3.1.3
Because most answers either show a lot of unrelated configuration or don't show the configuration, I created my own answer that tries to be more focused. It is mainly based on the profile settings reference and Archimedes Trajano's answer.
Open PowerShell and enter [guid]::NewGuid()
to generate a new GUID. We will use it at step 3.
> [guid]::NewGuid()
Guid
----
a3da8d92-2f3f-4e36-9714-98876b6cb480
Open the settings of Windows Terminal. (CTRL+,)
Add the following JSON object to profiles.list
. Replace guid
with the one you generated at step 1.
{
"guid": "{a3da8d92-2f3f-4e36-9714-98876b6cb480}",
"name": "Git Bash",
"commandline": "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" -i -l",
"icon": "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico",
"startingDirectory" : "%USERPROFILE%"
},
There is currently an issue that you cannot use your arrow keys (and some other keys). It seems to work with the latest preview version, though. (issue #6859)
Specifying "startingDirectory" : "%USERPROFILE%"
shouldn't be necessary according to the reference. However, if I don't specify it, the starting directory was different depending on how I started the terminal initially.
Settings that shall apply to all terminals can be specified in profiles.defaults
.
I recommend to set "antialiasingMode": "cleartype"
in profiles.defaults
. You have to remove "useAcrylic"
(if you have added it as suggested by some other answers) to make it work. It improves the quality of text rendering. However, you cannot have transparent background without useAcrylic
. See issue #1298.
If you have problems with the cursor, you can try another shape like "cursorShape": "filledBox"
. See cursor settings for more information.
Use this
@ViewChild(ChildDirective, {static: false}) Component
In my case, I was trying to use mdbreact on windows. Though it installed, But i was getting the above error. I had to reinstall it and everything was ok. It happened to me once two with antd Library
Try import tkinter
because pycharm already installed tkinter for you, I looked Install tkinter for Python
You can maybe try:
import tkinter
import matplotlib
matplotlib.use('TkAgg')
plt.plot([1,2,3],[5,7,4])
plt.show()
as a tkinter-installing way
I've tried your way, it seems no error to run at my computer, it successfully shows the figure. maybe because pycharm have tkinter as a system package, so u don't need to install it. But if u can't find tkinter inside, you can go to Tkdocs to see the way of installing tkinter, as it mentions, tkinter is a core package for python.
You have two options with simple and idiomatic Typescript:
DNATranscriber: { [char: string]: string } = {
G: "C",
C: "G",
T: "A",
A: "U",
};
This is the index signature the error message is talking about. Reference
DNATranscriber: { G: string; C: string; T: string; A: string } = {
G: "C",
C: "G",
T: "A",
A: "U",
};
This is worked for me
Latest Update-
If you're using Xcode 10.x, then the default UIUserInterfaceStyle
is light
for iOS 13.x. When run on an iOS 13 device, it will work in Light Mode only.
No need to explicitly add the UIUserInterfaceStyle
key in Info.plist file, adding it will give an error when you Validate your app, saying:
Invalid Info.plist Key. The key 'UIUserInterfaceStyle' in the Payload/AppName.appInfo.plist file is not valid.
Only add the UIUserInterfaceStyle
key in Info.plist file when using Xcode 11.x.
This is a useful bit of code:
extension View {
func expandable () -> some View {
ZStack {
Color.clear
self
}
}
}
Compare the results with and without the .expandable()
modifier:
Text("hello")
.background(Color.blue)
-
Text("hello")
.expandable()
.background(Color.blue)
If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors();
in the configure
method. The method looks like that:
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests() // authorize
.anyRequest().authenticated() // all requests are authenticated
.and()
.httpBasic();
http.cors();
}
I used withStyles
instead of makeStyle
EX :
import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";
const useStyles = theme => ({
root: {
flexGrow: 1,
},
});
class App extends Component {
render() {
const { classes } = this.props;
return(
<div className={classes.root}>
Test
</div>
)
}
}
export default withStyles(useStyles)(App)
I had the same problem, but I solved it thanks to the comment of Ekta Gandhi:
Finally i found the solution.
1) Firstly eliminate all changes in package.json file by giving simple command git checkout package.json.
2) Then after make change in package.json in @angular-devkit/build-angular- ~0.800.1(Add tail instead of cap)
3) Then run command rm -rf node_modules/
4) Then clean catch by giving command npm clean cache -f
5) And at last run command npm install. This works for me.
.... Along with the modification proposed by Dimuthu
Made it to @angular-devkit/build-angular": "0.13.4" and it worked.
in your tsconfig you have to add: "esModuleInterop": true - it should help.
I updated spring tool suits by going help
> check for update
.
In my case worked with:
np.load(path, allow_pickle=True)
I'm Daniel Stenberg.
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.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
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.
Yeah. For real.
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.
I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API
Use const App instead of const app
Linux uses the inotify package to observe filesystem events, individual files or directories.
Since React / Angular hot-reloads and recompiles files on save it needs to keep track of all project's files. Increasing the inotify watch limit should hide the warning messages.
You could try editing
# insert the new value into the system config
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
# check that the new value was applied
cat /proc/sys/fs/inotify/max_user_watches
# config variable name (not runnable)
fs.inotify.max_user_watches=524288
You don't need to run Xcode 10.2 for iOS 12.2 support. You just need access to the appropriate folder in DeviceSupport.
A possible solution is
/Applications
. It's possible to have multiple Xcode versions in the same directory.Create a symbolic link in Terminal.app to have access to the 12.2 device support folder in Xcode 10.2
ln -s /Applications/Xcode102.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/12.2\ \(16E226\) /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
You can move Xcode 10.2 to somewhere else but then you have to adjust the path.
Now Xcode 10.1 supports devices running iOS 12.2
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
Just change "target": "es2015" to "target": "es5" in your tsconfig.json.
Work for me with Angular 8.2.XX
Tested on IE11 and Edge
In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).
Initialize Model Structure in Constructor:
this.newForm = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
});
If you want to update all fields of form:
this.newForm.setValue({
firstName: 'abc',
lastName: 'def'
});
If you want to update specific field of form:
this.newForm.controls.firstName.setValue('abc');
Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.
If you want to update some/ specific fields of form:
this.newForm.patchValue({
firstName: 'abc'
});
Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.
You need to add an event, before call your handleFunction like this:
function SingInContainer() {
..
..
handleClose = () => {
}
return (
<SnackBar
open={open}
handleClose={() => handleClose}
variant={variant}
message={message}
/>
<SignInForm/>
)
}
The same problem happened to me today.
My solution:
Download the latest stable release of chromedriver: https://sites.google.com/a/chromium.org/chromedriver/
Update the chrome driver on your Selenium folder. This is a bit hard, because is in a hidden folder on your PC called AppData. Here is how I did it in my computer (Windows 7):
C: > users > your user > \AppData (you need to write this in the folder path box, since it is a hidden folder) > Local (this is the folder name in portuguese, maybe it will have a different name for you) > SeleniumBasic
There you will find the chromedriver application. Just rename it (in case it does not work, you want to have the older version) and than paste the newest release.
In my case just run the command and worked like charm.
php artisan route:clear
According to TF 1:1 Symbols Map
, in TF 2.0 you should use tf.compat.v1.Session()
instead of tf.Session()
https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0
To get TF 1.x like behaviour in TF 2.0 one can run
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
but then one cannot benefit of many improvements made in TF 2.0. For more details please refer to the migration guide https://www.tensorflow.org/guide/migrate
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"), [] );
Open the developer setting and click console and type the following
JSON.parse(document.getElementById('jupyter-config-data').textContent).token
Then try saving the Notebook. The notebook that was not saving previously will save now.
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
Following solution worked for me-
goto resources/android/xml/network_security_config.xml
Change it to-
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
<domain includeSubdomains="true">api.example.com(to be adjusted)</domain>
</domain-config>
</network-security-config>
Try these steps:
cd /ios
pod install
This was what worked for me.
sudo apt update
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.7
sudo apt install python3-pip
python3.7 -m pip install pip
sudo update-alternatives --install /usr/local/bin/python python /usr/bin/python3.7 10
sudo update-alternatives --install /usr/local/bin/pip pip /home/your_username/.local/bin/pip3.7 10
source ~/.bashrc
python --version
pip --version
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 :
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 :
Timer.periodic
creation with a non null condition so that clicking the button multiple times has no effectif (_timer != null) {
_timer = new Timer.periodic(...);
}
if (_timer != null) {
_timer.cancel();
_start = 10;
}
_timer = new Timer.periodic(...);
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
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name
A.B
designates a submodule namedB
in a package namedA
....
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring
, from unintentionally hiding valid modules that occur later on the module search path.
You need to set it up to something like this:
man
|- __init__.py
|- Mans
|- __init__.py
|- man1.py
|- MansTest
|- __init.__.py
|- SoftLib
|- Soft
|- __init__.py
|- SoftWork
|- __init__.py
|- manModules.py
|- Unittests
|- __init__.py
|- man1test.py
SECOND, for the "ModuleNotFoundError: No module named 'Soft'
" error caused by from ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py to sys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path
directly, you can also modify PYTHONPATH
:
sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
THIRD, for from ...MansTest.SoftLib import Soft
which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.
With that said, here's how I got it to work.
man1.py:
from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH
def foo():
print("called foo in man1.py")
print("foo call module1 from manModules: " + module1())
man1test.py
# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1
man1.foo()
manModules.py
def module1():
return "module1 in manModules"
Terminal output:
$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
...
from ...Mans import man1
File "/temp/man/Mans/man1.py", line 2, in <module>
from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'
$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).
Here's a quick way to get what is happening:
When you did the following:
name? : string
You were saying to TypeScript it was optional. Nevertheless, when you did:
let name1 : string = person.name; //<<<Error here
You did not leave it a choice. You needed to have a Union on it reflecting the undefined type:
let name1 : string | undefined = person.name; //<<<No error here
Using your answer, I was able to sketch out the following which is basically, an Interface, a Class and an Object. I find this approach simpler, never mind if you don't.
// Interface
interface iPerson {
fname? : string,
age? : number,
gender? : string,
occupation? : string,
get_person?: any
}
// Class Object
class Person implements iPerson {
fname? : string;
age? : number;
gender? : string;
occupation? : string;
get_person?: any = function () {
return this.fname;
}
}
// Object literal
const person1 : Person = {
fname : 'Steve',
age : 8,
gender : 'Male',
occupation : 'IT'
}
const p_name: string | undefined = person1.fname;
// Object instance
const person2: Person = new Person();
person2.fname = 'Steve';
person2.age = 8;
person2.gender = 'Male';
person2.occupation = 'IT';
// Accessing the object literal (person1) and instance (person2)
console.log('person1 : ', p_name);
console.log('person2 : ', person2.get_person());
You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
So in the end I found that if I commented out the Conda initialisation block like so:
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# __conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
# if [ $? -eq 0 ]; then
# eval "$__conda_setup"
# else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
# unset __conda_setup
# <<< conda initialize <<<
It works exactly how I want. That is, Conda is available to activate an environment if I want, but doesn't activate by default.
I had a similar problem: my default gradle wrapper
was version 4.x, while the support for higher versions of Java has been added in Gradle 5.
I've updated my gradlew
as described here: https://docs.gradle.org/current/userguide/gradle_wrapper.html#sec:upgrading_wrapper
TLTD:
./gradlew wrapper --gradle-version 5.6.2
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
If anyone is searching for useState() hooks update for object
- Through Input
const [state, setState] = useState({ fName: "", lName: "" });
const handleChange = e => {
const { name, value } = e.target;
setState(prevState => ({
...prevState,
[name]: value
}));
};
<input
value={state.fName}
type="text"
onChange={handleChange}
name="fName"
/>
<input
value={state.lName}
type="text"
onChange={handleChange}
name="lName"
/>
***************************
- Through onSubmit or button click
setState(prevState => ({
...prevState,
fName: 'your updated value here'
}));
2021 Jan.12th
the whole point for me is to explicitly specify the version as java 11 in my pom.xml, and I solved the problem by taking the following steps.
open terminal and input: java -version, then i got 1.8, and i went to .bash_profile to switch the java version to 11.2 as i have multiple java version installed. please remember "restart" your terminal and check your java version again to confirm switch is successful.
Then i went to File -> Project Structure to make sure my IntelliJ using the same version as my env, which is 11.2.
RESTART your Intellij, mvn clean install, solved, hope this could help someone with this issue, thanks.
I use this "Win64 OpenSSL v1.1.1h" -> EXE from https://slproweb.com/products/Win32OpenSSL.html
i've installed it and works
If you go to chrome://extensions/, you can just toggle each extension one at a time and see which one is actually triggering the issue.
Once you toggle the extension off, refresh the page where you are seeing the error and wiggle the mouse around, or click. Mouse actions are the things that are throwing errors.
So I was able to pinpoint which extension was actually causing the issue and disable it.
In vscode select folder and create WS and it will work fine
useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.
object and array spread or rest will not work inside useEffect.
React.useEffect(() => {
console.log("effect");
(async () => {
try {
let result = await fetch("/query/countries");
const res = await result.json();
let result1 = await fetch("/query/projects");
const res1 = await result1.json();
let result11 = await fetch("/query/regions");
const res11 = await result11.json();
setData({
countries: res,
projects: res1,
regions: res11
});
} catch {}
})(data)
}, [setData])
# or use this
useEffect(() => {
(async () => {
try {
await Promise.all([
fetch("/query/countries").then((response) => response.json()),
fetch("/query/projects").then((response) => response.json()),
fetch("/query/regions").then((response) => response.json())
]).then(([country, project, region]) => {
// console.log(country, project, region);
setData({
countries: country,
projects: project,
regions: region
});
})
} catch {
console.log("data fetch error")
}
})()
}, [setData]);
I have tried a lot of ways to solve this. But I am failed again and again. Then I did this:
Open Git Bash
> go to your directory
> paste the git clone https://[email protected]/*******.git
after that a command prompt will be shown to give the login credentials. Give the credentials and clone your project.
Inspired by the accepted answer by @ford04 I had even better approach dealing with it, instead of using useEffect
inside useAsync
create a new function that returns a callback for componentWillUnmount
:
function asyncRequest(asyncRequest, onSuccess, onError, onComplete) {
let isMounted=true
asyncRequest().then((data => isMounted ? onSuccess(data):null)).catch(onError).finally(onComplete)
return () => {isMounted=false}
}
...
useEffect(()=>{
return asyncRequest(()=>someAsyncTask(arg), response=> {
setSomeState(response)
},onError, onComplete)
},[])
You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.
You may want to send back a response telling the user what went wrong as well as logging the error on your server.
I am not sure exactly what errors the request might return, you may want to return something like.
router.get("/emailfetch", authCheck, async (req, res) => {
try {
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch(error) {
res.status(error.response.status)
return res.send(error.message);
})
})
This code will need to be adapted to match the errors that you get from the axios call.
I have also converted the code to use the try and catch syntax since you are already using async.
The accepted answer won't fix the error when importing own modules.
Use the following setting in your workspace settings .vscode/settings.json
:
"python.autoComplete.extraPaths": ["./path-to-your-code"],
Reference: Troubleshooting, Unresolved import warnings
If you want beautiful and responsive alert dialog then you can use flutter packages like
rflutter alert ,fancy dialog,rich alert,sweet alert dialogs,easy dialog & easy alert
These alerts are good looking and responsive. Among them rflutter alert is the best. currently I am using rflutter alert for my apps.
You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect
for this.
The following version works:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{ id: 0, value: " --- Select a State ---" }];
const allowedState = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const [stateOptions, setStateValues] = useState(initialValue);
// initialValue.push(...allowedState);
console.log(initialValue.length);
// ****** BEGINNING OF CHANGE ******
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setStateValues(allowedState);
}, []);
// ****** END OF CHANGE ******
return (<div>
<label>Select a State:</label>
<select>
{stateOptions.map((localState, index) => (
<option key={localState.id}>{localState.value}</option>
))}
</select>
</div>);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
and here it is in a code sandbox.
I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState
directly without using useState
at all). If so, that api call to load the list could also go inside the useEffect
block.
I found another issue that starts out giving the same error message as in the question. I am sharing this here so that before changing the project file you can make sure your services are properly registered.
I am also running .netcore 2.2 and was receiving the same error message so I changed project file from InProcess to OutOfProcess as in the selected answer. After that I found the real cause for my issue when I received “Cannot instantiate implementation type” : The cause of this was for me was having:
services.AddScoped<IMyService, IMyService>();
instead of
services.AddScoped<IMyService, MyService>();
Related post: Why am I getting the error "Cannot instantiate implementation type" for my generic service?
I opened up my Software & Updates program
and switched from my country to the main servers like so:
After I done this and run the sudo apt update
commando again, my problems where gone.
The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.
As a type that contains children, I'm using:
type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">
This children container type is generic enough to support all the different cases and also aligned with the ReactJS API.
So, for your example it would be something like:
const layout = ({ children }: ChildrenContainer) => (
<Aux>
<div>Toolbar, SideDrawer, Backdrop</div>
<main>
{children}
</main>
<Aux/>
)
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
For me,
flutter clean
,giving full patth in my image
image: AssetImage(
'./lib/graphics/logo2.png'
),
width: 200,
height: 200,
);
these three steps did the trick.
This post will go through the following topics:
merge
, join
, concat
There are a few options, some simpler than others depending on the use case.
DataFrame.merge
withleft_index
andright_index
(orleft_on
andright_on
using names indexes)
- supports inner/left/right/full
- can only join two at a time
- supports column-column, index-column, index-index joins
DataFrame.join
(join on index)
- supports inner/left (default)/right/full
- can join multiple DataFrames at a time
- supports index-index joins
pd.concat
(joins on index)
- supports inner/full (default)
- can join multiple DataFrames at a time
- supports index-index joins
Setup & Basics
import pandas as pd
import numpy as np
np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)},
index=['A', 'B', 'C', 'D'])
right = pd.DataFrame(data={'value': np.random.randn(4)},
index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'
left
value
idxkey
A -0.602923
B -0.402655
C 0.302329
D -0.524349
right
value
idxkey
B 0.543843
D 0.013135
E -0.326498
F 1.385076
Typically, an inner join on index would look like this:
left.merge(right, left_index=True, right_index=True)
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
Other joins follow similar syntax.
Notable Alternatives
DataFrame.join
defaults to joins on the index. DataFrame.join
does a LEFT OUTER JOIN by default, so how='inner'
is necessary here.
left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
Note that I needed to specify the lsuffix
and rsuffix
arguments since join
would otherwise error out:
left.join(right)
ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
Since the column names are the same. This would not be a problem if they were differently named.
left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
leftvalue value
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
pd.concat
joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner'
is required here..
pd.concat([left, right], axis=1, sort=False, join='inner')
value value
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
For more information on concat
, see this post.
To perform an inner join using index of left, column of right, you will use DataFrame.merge
a combination of left_index=True
and right_on=...
.
right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
colkey value
0 B 0.543843
1 D 0.013135
2 E -0.326498
3 F 1.385076
left.merge(right2, left_index=True, right_on='colkey')
value_x colkey value_y
0 -0.402655 B 0.543843
1 -0.524349 D 0.013135
Other joins follow a similar structure. Note that only merge
can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.
join
and concat
are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index
.
If your index is named, then from pandas >= 0.23, DataFrame.merge
allows you to specify the index name to on
(or left_on
and right_on
as necessary).
left.merge(right, on='idxkey')
value_x value_y
idxkey
B -0.402655 0.543843
D -0.524349 0.013135
For the previous example of merging with the index of left, column of right, you can use left_on
with the index name of left:
left.merge(right2, left_on='idxkey', right_on='colkey')
value_x colkey value_y
0 -0.402655 B 0.543843
1 -0.524349 D 0.013135
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
For me "npm install" again from command prompt worked. Command Prompt must be "Run as Administrator"
I know this is old but I just encountered the issue in my team (some mac, some linux, some windows , all vscode).
solution was to set the line ending in vscode's settings:
.vscode/settings.json
{
"files.eol": "\n",
}
https://qvault.io/2020/06/18/how-to-get-consistent-line-breaks-in-vs-code-lf-vs-crlf/
More of an addendum. I did repro the experiment using the latest Java 8 JVM from IBM:
java version "1.8.0_191"
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.8.0_191-b12 26_Oct_2018_18_45 Mac OS X x64(SR5 FP25))
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)
And this shows very similar results:
0.374653912 s
n = 119860736
0.447778698 s
n = 119860736
(second results using 2 * i * i).
Interestingly enough, when running on the same machine, but using Oracle Java:
Java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
results are on average a bit slower:
0.414331815 s
n = 119860736
0.491430656 s
n = 119860736
Long story short: even the minor version number of HotSpot matter here, as subtle differences within the JIT implementation can have notable effects.
This is another option:
export default function Counter() {
}
The provided solution here is correct. However, the same error can also occur from a user error, where your endpoint request method is NOT matching the method your using when making the request.
For example, the server endpoint is defined with "RequestMethod.PUT" while you are requesting the method as POST.
I had the same problem in Xcode 11.5 after revoking a certificate through Apple's developer homepage and adding it again (even though it looked different afterwards):
Every time I tried to archive my app, it would fail at the very end (not the pods but my actual app) with the same PhaseScriptExecution failed with a nonzero exit code
error message. There is/was a valid team with an "Apple Development" signing certificate in "Signing & Capabilities" (project file in Xcode) and locking & unlocking the keychain, cleaning & building the project, restarting,... didn't work.
The problem was caused by having two active certificates of the same type that I must have added on accident, in addition to the renewed one. I deleted both the renewed one and the duplicate and it worked again.
You can find your certificates here or find the page like this:
Also check that there aren't any duplicates in your keychain! Be careful though - don't delete or add anything unless you know what you're doing, otherwise you might create a huge mess!
You can simply define the useState like that:
const [, forceUpdate] = React.useState(0);
And usage: forceUpdate(n => !n)
Hope this help !
Yesterday, I got the same error: Failed building wheel for hddfancontrol
when I ran pip3 install hddfancontrol
. The result was Failed to build hddfancontrol
. The cause was error: invalid command 'bdist_wheel'
and Running setup.py bdist_wheel for hddfancontrol ... error
. The error was fixed by running the following:
pip3 install wheel
(From here.)
Alternatively, the "wheel" can be downloaded directly from here. When downloaded, it can be installed by running the following:
pip3 install "/the/file_path/to/wheel-0.32.3-py2.py3-none-any.whl"
If you're using Lombok on a POJO model, make sure you have these annotations:
@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
It could vary, but make sure @Getter
and especially @NoArgsConstructor
.
useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:
import React, {useState} from react
function HookCounter {
const [count, stateCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count}</button>
</div>
)
}
useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.
function useOnceCall(cb, condition = true) {
const isCalledRef = React.useRef(false);
React.useEffect(() => {
if (condition && !isCalledRef.current) {
isCalledRef.current = true;
cb();
}
}, [cb, condition]);
}
and use it.
useOnceCall(()=>{
console.log('called');
})
or
useOnceCall(()=>{
console.log('isLoading');
},isLoading);
I came across this error on linux environment. If not using headless then you will need
from sys import platform
if platform != 'win32':
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
If you're using scss for your styles you can use a mixin to help generate the code. Your styles will quickly get out of hand if you put all the properties every time.
This is a very simple example - really nothing more than a proof of concept, you can extend this with multiple properties and rules as needed.
@mixin mat-table-columns($columns)
{
.mat-column-
{
@each $colName, $props in $columns {
$width: map-get($props, 'width');
&#{$colName}
{
flex: $width;
min-width: $width;
@if map-has-key($props, 'color')
{
color: map-get($props, 'color');
}
}
}
}
}
Then in your component where your table is defined you just do this:
@include mat-table-columns((
orderid: (width: 6rem, color: gray),
date: (width: 9rem),
items: (width: 20rem)
));
This generates something like this:
.mat-column-orderid[_ngcontent-c15] {
flex: 6rem;
min-width: 6rem;
color: gray; }
.mat-column-date[_ngcontent-c15] {
flex: 9rem;
min-width: 9rem; }
In this version width
becomes flex: value; min-width: value
.
For your specific example you could add wrap: true
or something like that as a new parameter.
In my case, I got the error on the setState line:
increment(){
this.setState(state => {
count: state.count + 1
});
}
I changed it to this, now it works
increment(){
this.setState(state => {
const count = state.count + 1
return {
count
};
});
}
Adding to Stefan Seidel's answer.
Well, at least in Ubuntu 20.04.2 LTS or maybe in other versions you can't really edit the policy.xml file directly in a GUI way. Here is a terminal way to edit it.
Open the policy.xml file in terminal by entering this command -
sudo nano /etc/ImageMagick-6/policy.xml
Now, directly edit the file in terminal, find
<policy domain="coder" rights="none" pattern="PDF" />
and replace none
with read|write
as shown in the picture. Then press Ctrl+X to exit.
I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.
Expanded(child:MyListView())
Solution:
Add the below line in your application
tag:
android:usesCleartextTraffic="true"
As shown below:
<application
....
android:usesCleartextTraffic="true"
....>
UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"
No Need to set clear text traffic to true as shown above, instead use the below code:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
....
....
</domain-config>
<base-config cleartextTrafficPermitted="false"/>
</network-security-config>
Set the cleartextTrafficPermitted
to true
Hope it helps.
Another thing which might be causing this is a 'weird' symbol in your file and directory names. All umlaut (äöå) and other (éóâ etc) characters should be removed from the file and folder names. I've had this same issue sometimes because of these characters.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
Be sure to check Xcode Preferences -> Locations.
The Command Line Tools I had selected was for the previous version of Xcode (8.2.1 instead of 10.1)
on the main.dart file import service like follow
import 'package:flutter/services.dart';
and inside build method just add this line before return
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.orange
));
Like this:
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: CustomColors.appbarcolor
));
return MaterialApp(
home: MySplash(),
theme: ThemeData(
brightness: Brightness.light,
primaryColor: CustomColors.appbarcolor,
),
);
}
When the plugin detects that you're using an API that's no longer supported, it can now provide more-detailed information to help you determine where that API is being used. To see the additional info, you need to include the following in your project's gradle.properties file:
android.debug.obsoleteApi=true
Quick summary, you can do either:
Include the JavaFX modules via --module-path
and --add-modules
like in José's answer.
OR
Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java
file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java
file).
This answer is a supplement to Jose's answer.
The situation is this:
IllegalAccessError
involving an "unnamed module" when trying to launch the app.Excerpt for a stack trace generating an IllegalAccessError
when trying to run a JavaFX app from Intellij Idea:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main
OK, now you are kind of stuck and have no clue what is going on.
What has actually happened is this:
So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError
. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).
This is where some of the other answers to this question, which reference module-info.java
, come into the picture.
So let's take a crash course in Java modules:
The key part is this:
4.9. Opens
If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.
But remember, this will open the package up to the entire world, so make sure that is what you want:
module my.module { opens com.my.package; }
So, perhaps you don't want to open your package to the entire world, then you can do:
4.10. Opens … To
Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:
module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }
So, you end up creating a src/main/java/module-info.java class which looks like this:
module org.jewelsea.demo.javafx.springboot {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}
Where, org.jewelsea.demo.javafx.springboot
is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics
and javafx.fxml
to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot
package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError
generated by JavaFX's use of reflection will no longer occur.
But what if you don't want to create a module-info.java file
If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:
javafx.run
.Run Maven Build
or Debug...
.Then the app will run without the module-info.java
file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java
file, though I don't know how this is accomplished.
To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run
Maven target and choose the option to Create Run/Debug Configuration
for the target. Then you can just choose Run from the top toolbar to execute the Maven target.
Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.
Difference between OpenJDK and AdoptOpenJDK
The first provides source-code, the other provides builds of that source-code.
Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:
See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.
Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.
Here is a list of considerations and motivations to consider in choosing a vendor and implementation.
Some vendors offer you a choice of JIT technologies.
To understand more about this Java ecosystem, read Java Is Still Free
Your data homes
is an array, so you would have to iterate over the array using Array.prototype.map() for it to work.
return (
<div className="col">
<h1>Mi Casa</h1>
<p>This is my house y'all!</p>
{homes.map(home => <div>{home.name}</div>)}
</div>
);
Open Keychain Access on your Mac and delete the old expired Apple Development certificates. This solved the issue for me.
Just a visualisation
Lock Keychain "login" -> Unlock Keychain "login" -> Always allow
If the error says it can't find Info.plist and it's looking in the wrong path, do the following:
Here's another approach using Vuetify grid
system available in Vuetify 2.x
: https://vuetifyjs.com/en/components/grids
<v-container>
<v-row align="center">
Hello I am center to vertically using "grid".
</v-row>
</v-container>
I have got the same error as :
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
As, said by @Agaline, i download the outside wheel from this Christoph Gohlke.
If your is Python 3.7
then try to PyAudio-0.2.11-cp37-cp37m-win_amd64.whl
and use command as, go to the download directroy and:
pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl
and it works.
Install the plugin-proposal-class-properties
npm install @babel/plugin-proposal-class-properties --save-dev
Update your webpack.config.js by adding
'plugins': ['@babel/plugin-proposal-class-properties']}]
Instead of using
sudo systemctl start redis
use:
sudo /etc/init.d/redis start
as of right now we do not have systemd in WSL
The use of the deprecated new Buffer()
constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.
According to the deprecation warning new Buffer()
should be replaced with one of:
Buffer.alloc()
Buffer.allocUnsafe()
or Buffer.from()
Another option in order to avoid this issue would be using the safe-buffer package instead.
You can also try (when using yarn..):
yarn global add yarn
as mentioned here: Link
Another suggestion from the comments (thx to gkiely): self-update
Note: self-update is not available. See policies for enforcing versions within a project
In order to update your version of Yarn, run
curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
if you want include Id
async getMarkers() {
const events = await firebase.firestore().collection('events')
events.get().then((querySnapshot) => {
const tempDoc = querySnapshot.docs.map((doc) => {
return { id: doc.id, ...doc.data() }
})
console.log(tempDoc)
})
}
Same way with array
async getMarkers() {
const events = await firebase.firestore().collection('events')
events.get().then((querySnapshot) => {
const tempDoc = []
querySnapshot.forEach((doc) => {
tempDoc.push({ id: doc.id, ...doc.data() })
})
console.log(tempDoc)
})
}
As stated in the above answers, it's always a good practice to initialize the variables, but if you have something which you don't know what value should it takes, and you want to leave it uninitialized so you have to make sure that you are updating it before using it.
For example:
Assume we have double _bmi;
and you don't know what value should it takes, so you can leave it as it is, but before using it, you have to update its value first like calling a function that calculating BMI like follows:
String calculateBMI (){
_bmi = weight / pow( height/100, 2);
return _bmi.toStringAsFixed(1);}
or whatever, what I mean is, you can leave the variable as it is, but before using it make sure you have initialized it using whatever the method you are using.
You need not to worry
Just enable Jetifier in your projet.
Open gradle.properties
and add below two lines.
android.enableJetifier=true
android.useAndroidX=true
It will convert all support libraries of your dependency to AndroidX at run time (you may have compile time errors, but app will run).
When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink]
, then it should be assigned a name of the property the value of which will be the route it should navigate the user to.
So to fix your issue, replace this routerLink="['/about']"
with routerLink="/about"
in your HTML.
There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:
<nav class="main-nav>
<ul
class="main-nav__list"
ng-sticky
addClass="main-sticky-link"
[ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/">Home</a>
</li>
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/about">About us</a>
</li>
</ul>
</nav>
It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>
, either in your template provided above or in a parent component.
There's another issue with your AppRoutingModule
. You need to export the RouterModule
from there so that it is available to your AppModule
when it imports it. To fix that, export it from your AppRoutingModule
by adding it to the exports
array.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
{ path: 'about', component: AboutComponent },
{ path: 'what', component: WhatwedoComponent },
{ path: 'contacts', component: FooterComponent },
{ path: 'projects', component: ProjectsComponent},
];
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes),
],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule { }
In your scenario, converting a string to a boolean can be done via something like someString === 'true'
(as was already answered).
However, let me try to address your main issue: dealing with the local storage.
The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.
A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.
The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.
function setItemInStorage(key, item) {
localStorage.setItem(key, JSON.stringify(item));
}
function getItemFromStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
Your example could then be rewritten as:
setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);
And:
if (getItemFromStorage('CheckOutPageReload')) {
const pageLoadParams = getItemFromStorage('CheckOutPageReload');
this.btnLoginNumOne = pageLoadParams[0];
this.btnLoginEdit = pageLoadParams[1];
}
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :
@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}
Spring doc about Aggregating @Configuration classes with @Import: link
Here you go, options have values, label and css classes that gets reflected on parent element upon selection.
$(document).on('click','.update_app_status', function (e) {
let $div = $(this).parent().parent();
let $btn = $div.find('.vBtnMain');
let $btn2 = $div.find('.vBtnArrow');
let cssClass = $(this).data('status_class');
let status_value = $(this).data('status_value');
let status_label = $(this).data('status_label');
$btn.html(status_label);
$btn.removeClass();
$btn2.removeClass();
$btn.addClass('btn btn-sm vBtnMain '+cssClass);
$btn2.addClass('btn btn-sm vBtnArrow dropdown-toggle dropdown-toggle-split '+cssClass);
$div.removeClass('show');
$div.find('.dropdown-menu').removeClass('show');
e.preventDefault();
return false;
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group">
<button type="button" class="btn btn-sm vBtnMain btn-warning">Awaiting Review</button>
<button type="button" class="btn btn-sm vBtnArrow btn-warning dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item update_app_status" data-status_class="btn-warning" data-status_value="1" data-status_label="Awaiting Review" href="#">Awaiting Review</a>
<a class="dropdown-item update_app_status" data-status_class="btn-info" data-status_value="2" data-status_label="Reviewed" href="#">Reviewed</a>
<a class="dropdown-item update_app_status" data-status_class="btn-dark" data-status_value="3" data-status_label="Contacting" href="#">Contacting</a>
<a class="dropdown-item update_app_status" data-status_class="btn-success" data-status_value="4" data-status_label="Hired" href="#">Hired</a>
<a class="dropdown-item update_app_status" data-status_class="btn-danger" data-status_value="5" data-status_label="Rejected" href="#">Rejected</a>
</div>
</div>
_x000D_
An empty string will raise an error if you access [1:]. Therefore I would use:
def my_uppercase(title):
if not title:
return ''
return title[0].upper() + title[1:]
to uppercase the first letter only.
TL;DR: If it works, avoid, or use specifiers like __attribute__
, otherwise _Pragma
.
This is a short version of my blog article Suppressing Warnings in GCC and Clang.
Consider the following Makefile
CPPFLAGS:=-std=c11 -W -Wall -pedantic -Werror
.PHONY: all
all: puts
for building the following puts.c
source code
#include <stdio.h>
int main(int argc, const char *argv[])
{
while (*++argv) puts(*argv);
return 0;
}
It will not compile because argc
is unused, and the settings are hardcore (-W -Wall -pedantic -Werror
).
There are 5 things you could do:
__attribute__
_Pragma
#pragma
The first attempt should be checking if the source code can be improved to get rid of the warning. In this case we don't want to change the algorithm just because of that, as argc
is redundant with !*argv
(NULL
after last element).
__attribute__
#include <stdio.h>
int main(__attribute__((unused)) int argc, const char *argv[])
{
while (*++argv) puts(*argv);
return 0;
}
If you're lucky, the standard provides a specifier for your situation, like _Noreturn
.
__attribute__
is proprietary GCC extension (supported by Clang and some other compilers like armcc
as well) and will not be understood by many other compilers. Put __attribute__((unused))
inside a macro if you want portable code.
_Pragma
operator_Pragma
can be used as an alternative to #pragma
.
#include <stdio.h>
_Pragma("GCC diagnostic push")
_Pragma("GCC diagnostic ignored \"-Wunused-parameter\"")
int main(int argc, const char *argv[])
{
while (*++argv) puts(*argv);
return 0;
}
_Pragma("GCC diagnostic pop")
The main advantage of the _Pragma
operator is that you could put it inside macros, which is not possible with the #pragma
directive.
Downside: It's almost a tactical nuke, as it works line-based instead of declaration-based.
The _Pragma
operator was introduced in C99.
#pragma
directive.We could change the source code to suppress the warning for a region of code, typically an entire function:
#include <stdio.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
int main(int argc, const char *argv[])
{
while (*++argc) puts(*argv);
return 0;
}
#pragma GCC diagnostic pop
Downside: It's almost a tactical nuke, as it works line-based instead of declaration-based.
Note that a similar syntax exists in clang.
We could add the following line to the Makefile
to suppress the warning specifically for puts:
CPPFLAGS:=-std=c11 -W -Wall -pedantic -Werror
.PHONY: all
all: puts
puts.o: CPPFLAGS+=-Wno-unused-parameter
This is probably not want you want in your particular case, but it may help other reads who are in similar situations.
I figured this one out. I know this will help someone someday.
How to Vertically & Horizontally Center a Div Over a Relatively Positioned Image
The key was a 3rd wrapper. I would vote up any answer that uses less wrappers.
HTML
<div class="wrapper">
<img src="my-slide.jpg">
<div class="outer-wrapper">
<div class="table-wrapper">
<div class="table-cell-wrapper">
<h1>My Title</h1>
<p>Subtitle</p>
</div>
</div>
</div>
</div>
CSS
html, body {
margin: 0; padding: 0;
width: 100%; height: 100%;
}
ul {
width: 100%;
height: 100%;
list-style-position: outside;
margin: 0; padding: 0;
}
li {
width: 100%;
display: table;
}
img {
width: 100%;
height: 100%;
}
.outer-wrapper {
width: 100%;
height: 100%;
position: absolute;
top: 0;
margin: 0; padding: 0;
}
.table-wrapper {
width: 100%;
height: 100%;
display: table;
vertical-align: middle;
text-align: center;
}
.table-cell-wrapper {
width: 100%;
height: 100%;
display: table-cell;
vertical-align: middle;
text-align: center;
}
You can see the working jsFiddle here.
The trick is hide the input and customize the label.
HTML:
<div class="inputfile-box">
<input type="file" id="file" class="inputfile" onchange='uploadFile(this)'>
<label for="file">
<span id="file-name" class="file-box"></span>
<span class="file-button">
<i class="fa fa-upload" aria-hidden="true"></i>
Select File
</span>
</label>
</div>
CSS:
.inputfile-box {
position: relative;
}
.inputfile {
display: none;
}
.container {
display: inline-block;
width: 100%;
}
.file-box {
display: inline-block;
width: 100%;
border: 1px solid;
padding: 5px 0px 5px 5px;
box-sizing: border-box;
height: calc(2rem - 2px);
}
.file-button {
background: red;
padding: 5px;
position: absolute;
border: 1px solid;
top: 0px;
right: 0px;
}
JS:
function uploadFile(target) {
document.getElementById("file-name").innerHTML = target.files[0].name;
}
You can check this example: https://jsfiddle.net/rjurado/hnf0zhy1/4/
An alternative solution uses the stash:
Before:
~/dev/gitpro $git stash list
~/dev/gitpro $git log --oneline -3
* 7049dd5 (HEAD -> master) c111
* 3f1fa3d c222
* 0a0f6c4 c333
note you cannot run 'git stash pop' without specifying the stash@{1} entry. The stash is a LIFO stack -- not FIFO -- so that would incorrectly pop the stash@{0} entry with c222's changes (instead of stash@{1} with c111's changes).
note if there are conflicting chunks between commits 111 and 222, then you'll be forced to resolve them when attempting to pop. (This would be the case if you went with an alternative rebase solution as well.)
After:
~/dev/gitpro $git stash list
stash@{0}: On master: c222
~/dev/gitpro $git log -2 --oneline
* edbd9e8 (HEAD -> master) c111
* 0a0f6c4 c333
Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).
PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)
In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:
If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).
If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)
From OWASP.org:
Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).
From a Ruby-forum post:
When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.
Try one of these:
gdb -p 12271
gdb /path/to/exe 12271
gdb /path/to/exe
(gdb) attach 12271
Follow the steps given below:
Download Plugin Manager from here.
Extract the contents of zip file under "C:\Program Files\Notepad++"
Restart Notepad++
That's it !!
You need to wrap the table inside another element and set the height of that element. Example with inline css:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
Possibly unrelated, but if you want to start a new line after the current line, you can use o anywhere in the line.
If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.
However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.
You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.
A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.
You can find more details in the Testing help section of the on-line documentation.
In one line:
String date=new SimpleDateFormat("MM-dd-yyyy").format(new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01"));
Where:
String date=new SimpleDateFormat("FinalFormat").format(new SimpleDateFormat("InitialFormat").parse("StringDate"));
try {
Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
} catch (Exception e) {}
note: you have to include necessary imports from java.net
You can always tell the window to start in maximized... it should give you the same result... Like this: this.WindowState = FormWindowState.Maximized;
P.S. You could also try (and I'm not recommending this) to subtract the taskbar height.
It's been a while but for future reference: the method shouldComponentUpdate() can be used.
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
The essential difference between /*
and /
is that a servlet with mapping /*
will be selected before any servlet with an extension mapping (like *.html
), while a servlet with mapping /
will be selected only after extension mappings are considered (and will be used for any request which doesn't match anything else---it is the "default servlet").
In particular, a /*
mapping will always be selected before a /
mapping. Having either prevents any requests from reaching the container's own default servlet.
Either will be selected only after servlet mappings which are exact matches (like /foo/bar
) and those which are path mappings longer than /*
(like /foo/*
). Note that the empty string mapping is an exact match for the context root (http://host:port/context/
).
See Chapter 12 of the Java Servlet Specification, available in version 3.1 at http://download.oracle.com/otndocs/jcp/servlet-3_1-fr-eval-spec/index.html.
You can either return a response as String
as suggested by @vagaasen or you can use ResponseEntity
Object provided by Spring as below. By this way you can also return Http status code
which is more helpful in webservice call.
@RestController
@RequestMapping("/api")
public class MyRestController
{
@GetMapping(path = "/hello", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> sayHello()
{
//Get data from service layer into entityList.
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject entity = new JSONObject();
entity.put("aa", "bb");
entities.add(entity);
}
return new ResponseEntity<Object>(entities, HttpStatus.OK);
}
}
If you want to use scrollWidth to get the "REAL" CONTENT WIDTH/HEIGHT (as content can be BIGGER than the css-defined width/height-Box) the scrollWidth/Height is very UNRELIABLE as some browser seem to "MOVE" the paddingRIGHT & paddingBOTTOM if the content is to big. They then place the paddings at the RIGHT/BOTTOM of the "too broad/high content" (see picture below).
==> Therefore to get the REAL CONTENT WIDTH in some browsers you have to substract BOTH paddings from the scrollwidth and in some browsers you only have to substract the LEFT Padding.
I found a solution for this and wanted to add this as a comment, but was not allowed. So I took the picture and made it a bit clearer in the regard of the "moved paddings" and the "unreliable scrollWidth". In the BLUE AREA you find my solution on how to get the "REAL" CONTENT WIDTH!
Hope this helps to make things even clearer!
static object Lock = new object();
lock (Lock)
{
// do stuff
}
You could achieve this without having to import traceback:
try:
func1()
except Exception as ex:
trace = []
tb = ex.__traceback__
while tb is not None:
trace.append({
"filename": tb.tb_frame.f_code.co_filename,
"name": tb.tb_frame.f_code.co_name,
"lineno": tb.tb_lineno
})
tb = tb.tb_next
print(str({
'type': type(ex).__name__,
'message': str(ex),
'trace': trace
}))
Output:
{
'type': 'ZeroDivisionError',
'message': 'division by zero',
'trace': [
{
'filename': '/var/playground/main.py',
'name': '<module>',
'lineno': 16
},
{
'filename': '/var/playground/main.py',
'name': 'func1',
'lineno': 11
},
{
'filename': '/var/playground/main.py',
'name': 'func2',
'lineno': 7
},
{
'filename': '/var/playground/my.py',
'name': 'test',
'lineno': 2
}
]
}
empty()
returns true for everything that evaluates to FALSE
, it is actually a 'not' (!
) in disguise. I think you meant isset()
Note that this behaves the same on IIS 6 and 7.x, and .NET 2, 3, and 4.x.
Also note that when app_offline.htm is present, IIS will return this http status code:
HTTP/1.1 503 Service Unavailable
This is all by design. This allows your load balancer (or whatever) to see that the server is off line.
Try using setAttribute on the result:
result.setAttribute("class","red");
Equivalent to Dror's answer but as an extension method:
namespace System
{
public static class TypeExtensions
{
public static object Default(this Type type)
{
object output = null;
if (type.IsValueType)
{
output = Activator.CreateInstance(type);
}
return output;
}
}
}
for using As logout you need to terminate all app from Ram Cache so close The Application first and then Rerun it
//on clicking Logout Button
foreach(Form frm in Application.OpenForms.Cast<Form>().ToList())
{
frm.Close();
}
System.Diagnostics.Process.Start(Application.ExecutablePath);
Expanding on @lhunath's and @GregV's answers, here's the code for the people who want to easily put that check inside an if
statement:
exists()
{
command -v "$1" >/dev/null 2>&1
}
Here's how to use it:
if exists bash; then
echo 'Bash exists!'
else
echo 'Your system does not have Bash'
fi
Much simpler: use sudo
to run a shell and use a heredoc to feed it commands.
#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
(answer originally on SuperUser)
If you have already defined your view in layout(xml) file and only want to change the weight pro grammatically, then then creating new LayoutParams overwrites other params defined in you xml file.
So first you should use "getLayoutParams" and then setLayoutParams
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams();
params.weight = 4f;
mButton.setLayoutParams(params);
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload
or DOMReady
event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
A/code.cpp
#include <B/file.hpp>
A/a/code2.cpp
#include <B/file.hpp>
Compile using:
g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp
Edit:
You can use environment variables to change the path g++ looks for header files. From man page:
Some additional environments variables affect the behavior of the preprocessor.
CPATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH
Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon.
CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.
The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.
In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include.
There are many ways you can change an environment variable. On bash prompt you can do this:
$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp
You can of course add this in your Makefile etc.
Use jQuery's
$(this).addClass('showhideExtra_up_hover');
and
$(this).addClass('showhideExtra_down_hover');
Check this link, the most simplest way and it does not disable the validations.
http://aspsnippets.com/Articles/Disable-Button-before-Page-PostBack-in-ASP.Net.aspx
If you have e.g.
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Clicked" />
</form>
Then you can use
<script type = "text/javascript">
function DisableButton() {
document.getElementById("<%=Button1.ClientID %>").disabled = true;
}
window.onbeforeunload = DisableButton;
</script>
To disable the button if and after validation has succeeded, just as the page is doing a server postback.
Python opens files almost in the same way as in C:
r+
Open for reading and writing. The stream is positioned at the beginning of the file.
a+
Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).
Try Aspose.Words for Java, it runs on any OS where Java is installed.
It will output the document to DOC, DOCX or RTF if you need an MS Word output format. All are supported equally well.
Using this API you can create a document from scratch, literally from nodes and set their formatting properties. You can also use a DocumentBuilder which provides higher level methods such as create a table row, insert a field etc. Or you can copy/join/move portions between existing pre created document, say you want to assemble a contract, just grab and copy pieces from several documents and Aspose.Words will merge styles, list formatting etc properly in the resulting document.
You will be able to insert a TOC field using Aspose.Words, but as of today, the TOC field will require a field update when the document is opened in Microsoft Word. However, we are going to release full support for TOC fields early in 2010. E.g. it will build complete TOC as MS Word does it.
I'm on the Aspose.Words team.
Depends on your editor.
Have you tried Shift+Tab?
A slight edit on an example provided in http://matplotlib.org/users/shell.html:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')
line, = ax.plot(np.random.rand(100), '-', picker=5) # 5 points tolerance
def onpick(event):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
print('onpick points:', *zip(xdata[ind], ydata[ind]))
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
This plots a straight line plot, as Sohaib was asking
from IPython.display import display
display(df) # OR
print df.to_html()
The answer that the OP accepted is wildly different from the question I thought was asked. I thought the OP wanted a way to auto-align =
signs or +
signs, similar to the tabularize plugin for vim.
For this task, I found the Columns4Eclipse plugin to be just what I needed.
@HostListener("window:resize", [])
public onResize() {
this.detectScreenSize();
}
public ngAfterViewInit() {
this.detectScreenSize();
}
private detectScreenSize() {
const height = window.innerHeight;
const width = window.innerWidth;
}
header file lives at
/usr/include/SDL/SDL.h
__OR__
/usr/include/SDL2/SDL.h # for SDL2
in your c++ code pull in this header using
#include <SDL.h>
__OR__
#include <SDL2/SDL.h> // for SDL2
you have the correct usage of
sdl-config --cflags --libs
__OR__
sdl2-config --cflags --libs # sdl2
which will give you
-I/usr/include/SDL -D_GNU_SOURCE=1 -D_REENTRANT
-L/usr/lib/x86_64-linux-gnu -lSDL
__OR__
-I/usr/include/SDL2 -D_REENTRANT
-lSDL2
at times you may also see this usage which works for a standard install
pkg-config --cflags --libs sdl
__OR__
pkg-config --cflags --libs sdl2 # sdl2
which supplies you with
-D_GNU_SOURCE=1 -D_REENTRANT -I/usr/include/SDL -lSDL
__OR__
-D_REENTRANT -I/usr/include/SDL2 -lSDL2 # SDL2
In my case, the route signature was different from the method parameter. I had id, but I was accepting documentId as parameter, that caused the problem.
[Route("Documents/{id}")] <--- caused the webapi error
[Route("Documents/{documentId}")] <-- solved
public Document Get(string documentId)
{
..
}
I spent about one day to configure the new gmaps API (Google Maps Android API v2) on the Android emulator. None of the methods of those I found on the Internet was working correctly for me. But still I did it. Here is how:
On the other versions I could not configure because of various errors when I installed the necessary applications.
2) Start the emulator and install the following applications:
You can do this with following commands:
2.1) adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system
2.2) adb shell chmod 777 /system/app
2.3-2.5) adb push Each_of_the_3_apk_files.apk /system/app/
Links to download APK files. I have copied them from my rooted Android device.
3) Install Google Play Services and Google Maps on the emulator. I have an error 491, if I install them from Google Play store. I uploaded the apps to the emulator and run the installation locally. (You can use adb
to install this). Links to the apps:
4) I successfully run a demo sample on the emulator after these steps. Here is a screenshot:
On server where your admin run kafka find kafka-console-consumer.sh by command find . -name kafka-console-consumer.sh
then go to that directory and run for read message from your topic
./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning --max-messages 10
note that in topic may be many messages in that case I use --max-messages key
Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:
# Set seed for reproducibility.
set.seed(1)
# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))
# compare data frames by specific columns and keep only
# the rows with equal values
data_A[data_A$id %in% data_B$id,] # will keep data in data_A
data_B[data_B$id %in% data_A$id,] # will keep data in data_b
Results:
> data_A[data_A$id %in% data_B$id,]
id value
1 1 1
2 2 2
3 3 3
> data_B[data_B$id %in% data_A$id,]
id value
1 1 5
2 2 6
3 3 7
you can reset your branch with HEAD
git reset --hard branch_name
then fetch branches and delete branches which are not on remote from local,
git fetch -p
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
One other answer mentioned grep's -Cn switch which includes n lines of Context. I sometimes do this with n=99 as a quick-and-dirty way of getting [at least] a screenfull of context when the egrep pattern seems too fiddly, or when I'm on a machine on which I've not installed rcg and/or ccze.
I recently discovered ccze
which is a more powerful colorizer. My only complaint is that it is screen-oriented (like less
, which I never use for that reason) unless you specify the -A switch for "raw ANSI" output.
+1 for the rcg
mention above. It is still my favorite since it is so simple to customize in an alias. Something like this is usually in my ~/.bashrc:
alias tailc='tail -f /my/app/log/file | rcg send "BOLD GREEN" receive "CYAN" error "RED"'
Capture the onContextMenu
event, and return false in the event handler.
You can also capture the click event and check which mouse button fired the event with event.button
, in some browsers anyway.
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
There are at least 2 different methods of invoking functions on radio button selection:
1) Using ng-change
directive:
<input type="radio" ng-model="value" value="foo" ng-change='newValue(value)'>
and then, in a controller:
$scope.newValue = function(value) {
console.log(value);
}
Here is the jsFiddle: http://jsfiddle.net/ZPcSe/5/
2) Watching the model for changes. This doesn't require anything special on the input level:
<input type="radio" ng-model="value" value="foo">
but in a controller one would have:
$scope.$watch('value', function(value) {
console.log(value);
});
And the jsFiddle: http://jsfiddle.net/vDTRp/2/
Knowing more about your the use case would help to propose an adequate solution.
WPF only
don't have the exact code to hand, but in a recent project I think I used MouseDown event and simply put this:
frmBorderless.DragMove();
A solution without creating a temporary branch.
How to exit (“fix”) detached HEAD state when you already changed something in this mode and, optionally, want to save your changes:
Commit changes you want to keep. If you want to take over any of the changes you made in detached HEAD state, commit them. Like:
git commit -a -m "your commit message"
Discard changes you do not want to keep. The hard reset will discard any uncommitted changes that you made in detached HEAD state:
git reset --hard
(Without this, step 3 would fail, complaining about modified uncommitted files in the detached HEAD.)
Check out your branch. Exit detached HEAD state by checking out the branch you worked on before, for example:
git checkout master
Take over your commits. You can now take over the commits you made in detached HEAD state by cherry-picking, as shown in my answer to another question.
git reflog
git cherry-pick <hash1> <hash2> <hash3> …
You could git fetch origin
to update the remote branch in your repository to point to the latest version. For a diff against the remote:
git diff origin/master
Yes, you can use caret notation as well.
If you want to accept the remote changes:
git merge origin/master
To make it more simple to understand:
Step 1: lets go to one directory, where all will be included
$ cd /var/tmp
Step 2: now lets make a class1.py file which has a class name Class1 with some code
$ cat > class1.py <<\EOF
class Class1:
OKBLUE = '\033[94m'
ENDC = '\033[0m'
OK = OKBLUE + "[Class1 OK]: " + ENDC
EOF
Step 3: now lets make a class2.py file which has a class name Class2 with some code
$ cat > class2.py <<\EOF
class Class2:
OKBLUE = '\033[94m'
ENDC = '\033[0m'
OK = OKBLUE + "[Class2 OK]: " + ENDC
EOF
Step 4: now lets make one main.py which will be execute once to use Class1 and Class2 from 2 different files
$ cat > main.py <<\EOF
"""this is how we are actually calling class1.py and from that file loading Class1"""
from class1 import Class1
"""this is how we are actually calling class2.py and from that file loading Class2"""
from class2 import Class2
print Class1.OK
print Class2.OK
EOF
Step 5: Run the program
$ python main.py
The output would be
[Class1 OK]:
[Class2 OK]:
I know sounds crazy but I received such error because I forget to remove
private static final long serialVersionUID = 1L;
automatically generated by Eclipse JPA tool when a table to entities transformation I've done.
Removing the line above that solved the issue
No, there is no inline function in java. Yes, you can use a public static method anywhere in the code when placed in a public class. The java compiler may do inline expansion on a static or final method, but that is not guaranteed.
Typically such code optimizations are done by the compiler in combination with the JVM/JIT/HotSpot for code segments used very often. Also other optimization concepts like register declaration of parameters are not known in java.
Optimizations cannot be forced by declaration in java, but done by compiler and JIT. In many other languages these declarations are often only compiler hints (you can declare more register parameters than the processor has, the rest is ignored).
Declaring java methods static, final or private are also hints for the compiler. You should use it, but no garantees. Java performance is dynamic, not static. First call to a system is always slow because of class loading. Next calls are faster, but depending on memory and runtime the most common calls are optimized withinthe running system, so a server may become faster during runtime!
I had a problem where files from one folder wont get added to the Github source control. To solve that I deleted the .git folder that was created under that folder.
Agile is the practice and Scrum is the process to following this practice same as eXtreme Programming (XP) and Kanban are the alternative process to following Agile development practice.
I found that user controls can exist in the same project.
As others have mentioned, AutoToolboxPopulate must be set to True.
Create the desired user control.
Select Build Solution.
If the new user control doesn't show up in the toolbox, close/open Visual Studio.
If the user controls still aren't showing up in the toolbox, right click on the toolbox and select Reset Toolbox. Then select Build Solution. If they still aren't there, restart Visual Studio.
There must not be any build errors when the solution is built, otherwise new toolbox items will not be added to the toolbox.
Print truncates the varchar(MAX) to 8000, nvarchar(MAX) to 4000 chars.
But;
PRINT CAST(@query AS NTEXT)
will print the whole query.
select E1.EmpId,E1.Name,E2.Name as Manager from Employee E1 left join Employee E2 on E1.ManagerID = E2.EmpId
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
Answer:
public void Print(string FileName)
{
StringBuilder logMessage = new StringBuilder();
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ START - {0} - {1} -------------------]", MethodBase.GetCurrentMethod(), DateTime.Now.ToShortDateString()));
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "Parameter: 1: [Name - {0}, Value - {1}", "None]", Convert.ToString("")));
try
{
if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.
PrintDocument pd = new PrintDocument();
//Disable the printing document pop-up dialog shown during printing.
PrintController printController = new StandardPrintController();
pd.PrintController = printController;
//For testing only: Hardcoded set paper size to particular paper.
//pd.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
//pd.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pd.PrintPage += (sndr, args) =>
{
System.Drawing.Image i = System.Drawing.Image.FromFile(FileName);
//Adjust the size of the image to the page to print the full image without loosing any part of the image.
System.Drawing.Rectangle m = args.MarginBounds;
//Logic below maintains Aspect Ratio.
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
//Calculating optimal orientation.
pd.DefaultPageSettings.Landscape = m.Width > m.Height;
//Putting image in center of page.
m.Y = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Height - m.Height) / 2);
m.X = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Width - m.Width) / 2);
args.Graphics.DrawImage(i, m);
};
pd.Print();
}
catch (Exception ex)
{
log.ErrorFormat("Error : {0}\n By : {1}-{2}", ex.ToString(), this.GetType(), MethodBase.GetCurrentMethod().Name);
}
finally
{
logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ END - {0} - {1} -------------------]", MethodBase.GetCurrentMethod().Name, DateTime.Now.ToShortDateString()));
log.Info(logMessage.ToString());
}
}
For my list view am using custom Adapter which extends ArrayAdapter. in listiview i have 2 buttons one of the buttons as Custom AlertDialogBox. Ex: Activity parentActivity; Constructor for Adapter `
public CustomAdapter(ArrayList<Contact> data, Activity parentActivity,Context context) {
super(context,R.layout.listdummy,data);
this.mContext = context;
this.parentActivity = parentActivity;
}
` calling Adapter from MainActivty
adapter = new CustomAdapter(dataModels,MainActivity.this,this);
_x000D_
now write ur alertdialog inside ur button which is in the Adapter class
viewHolder.update.setOnClickListener(new View.OnClickListener() {_x000D_
@Override_x000D_
public void onClick(final View view) {_x000D_
_x000D_
_x000D_
AlertDialog.Builder alertDialog = new AlertDialog.Builder(parentActivity);_x000D_
alertDialog.setTitle("Updating");_x000D_
alertDialog.setCancelable(false);_x000D_
_x000D_
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);_x000D_
@SuppressLint("InflateParams") final View view1 = layoutInflater.inflate(R.layout.dialog,null);_x000D_
alertDialog.setView(view1);_x000D_
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {_x000D_
@Override_x000D_
public void onClick(DialogInterface dialogInterface, int i) {_x000D_
dialogInterface.cancel();_x000D_
}_x000D_
});_x000D_
alertDialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {_x000D_
@Override_x000D_
public void onClick(DialogInterface dialogInterface, int i) {_x000D_
_x000D_
//ur logic_x000D_
}_x000D_
}_x000D_
});_x000D_
alertDialog.create().show();_x000D_
_x000D_
}_x000D_
});
_x000D_
//do the edit in your javascript
$('.signinform').submit(function() {
$(this).ajaxSubmit({
type : "POST",
//set the data type
dataType:'json',
url: 'index.php/user/signin', // target element(s) to be updated with server response
cache : false,
//check this in Firefox browser
success : function(response){ console.log(response); alert(response)},
error: onFailRegistered
});
return false;
});
//controller function
public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
//add the header here
header('Content-Type: application/json');
echo json_encode( $arr );
}
Doing something like this should work for you.
<!--[if IE 8]>
<div id="IE8">
<![endif]-->
*Your content*
<!--[if IE 8]>
</div>
<![endif]-->
Then your CSS can look like this:
#IE8 div.something
{
color: purple;
}
Although both elements deliver functionally the same result *, I strongly recommend you use <button>
:
input
suggests that the control is editable, or can be edited by the user; button
is far more explicit in terms of the purpose it servesinput[type="submit"]
do not display correctly in some casesPOST
/GET
request to the server* With the exception of <button type="button">
which by default has no specified behaviour.
In summary, I highly discourage use of <input type="submit" />
.
Delete your .git folder, and reinitialize the git with git init, in my case that's work , because git add command staging the folder and the files in .git folder, if you close CLI after the commit , there will be double folder in staging area that make git system throw this issue.
I had an issue where I was putting in the override = "Allow" values (mentioned here already)......but on a x64 bit system.......my 32 notepad++ was phantom saving them. Switching to Notepad (which is a 64bit application on a x64 bit O/S) allowed me to save the settings.
See :
http://dpotter.net/technical/2009/11/editing-applicationhostconfig-on-64-bit-windows/
The relevant text:
One of the problems I’m running down required that I view and possibly edit applicationHost.config. This file is located at %SystemRoot%\System32\inetsrv\config. Seems simple enough. I was able to find it from the command line easily, but when I went to load it in my favorite editor (Notepad++) I got a file not found error. Turns out that the System32 folder is redirected for 32-bit applications to SysWOW64. There appears to be no way to view the System32 folder using a 32-bit app. Go figure. Fortunately, 64-bit versions of Windows ship with a 64-bit version of Notepad. As much as I dislike it, at least it works.
If you only want one or more columns in the front and don't care about the order of the rest:
require(dplyr)
test %>%
select(B, everything())
I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:
function showMessage(msg) {
alert(msg);
};
<input type="button" value="ahaha" onclick="showMessage('msg');" />
UPDATE: With a small change to how your method is defined I can get it to work:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript">
// define the function within the global scope
$.fn.MessageBox = function(msg) {
alert(msg);
};
// or, if you want to encapsulate variables within the plugin
(function($) {
$.fn.MessageBoxScoped = function(msg) {
alert(msg);
};
})(jQuery); //<-- make sure you pass jQuery into the $ parameter
</script>
</head>
<body>
<div class="Title">Welcome!</div>
<input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>
UPDATE 2014-11-14: The solution below is too old, I recommend using flex box layout method. Here is a overview: http://learnlayout.com/flexbox.html
My solution
<li class="grid-list-header row-cw row-cw-msg-list ...">
<div class="col-md-1 col-cw col-cw-name">
<div class="col-md-1 col-cw col-cw-keyword">
<div class="col-md-1 col-cw col-cw-reply">
<div class="col-md-1 col-cw col-cw-action">
</li>
<li class="grid-list-item row-cw row-cw-msg-list ...">
<div class="col-md-1 col-cw col-cw-name">
<div class="col-md-1 col-cw col-cw-keyword">
<div class="col-md-1 col-cw col-cw-reply">
<div class="col-md-1 col-cw col-cw-action">
</li>
.row-cw {
position: relative;
}
.col-cw {
position: absolute;
top: 0;
}
.ir-msg-list {
$col-reply-width: 140px;
$col-action-width: 130px;
.row-cw-msg-list {
padding-right: $col-reply-width + $col-action-width;
}
.col-cw-name {
width: 50%;
}
.col-cw-keyword {
width: 50%;
}
.col-cw-reply {
width: $col-reply-width;
right: $col-action-width;
}
.col-cw-action {
width: $col-action-width;
right: 0;
}
}
Without modify too much bootstrap layout code.
Update (not from OP): adding code snippet below to facilitate understanding of this answer. But it doesn't seem to work as expected.
ul {_x000D_
list-style: none;_x000D_
}_x000D_
.row-cw {_x000D_
position: relative;_x000D_
height: 20px;_x000D_
}_x000D_
.col-cw {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
background-color: rgba(150, 150, 150, .5);_x000D_
}_x000D_
.row-cw-msg-list {_x000D_
padding-right: 270px;_x000D_
}_x000D_
.col-cw-name {_x000D_
width: 50%;_x000D_
background-color: rgba(150, 0, 0, .5);_x000D_
}_x000D_
.col-cw-keyword {_x000D_
width: 50%;_x000D_
background-color: rgba(0, 150, 0, .5);_x000D_
}_x000D_
.col-cw-reply {_x000D_
width: 140px;_x000D_
right: 130px;_x000D_
background-color: rgba(0, 0, 150, .5);_x000D_
}_x000D_
.col-cw-action {_x000D_
width: 130px;_x000D_
right: 0;_x000D_
background-color: rgba(150, 150, 0, .5);_x000D_
}
_x000D_
<ul class="ir-msg-list">_x000D_
<li class="grid-list-header row-cw row-cw-msg-list">_x000D_
<div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
<div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
<div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
<div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
</li>_x000D_
_x000D_
<li class="grid-list-item row-cw row-cw-msg-list">_x000D_
<div class="col-md-1 col-cw col-cw-name">name</div>_x000D_
<div class="col-md-1 col-cw col-cw-keyword">keyword</div>_x000D_
<div class="col-md-1 col-cw col-cw-reply">reply</div>_x000D_
<div class="col-md-1 col-cw col-cw-action">action</div>_x000D_
</li>_x000D_
</ul>
_x000D_
echo str_pad("1234567", 8, '0', STR_PAD_LEFT);
In my case it was entirely my fault (as usual) I was changing the system path under the environment variables, in Windows, and messed up the path for Node/NPM. So the solution is to either re-add the path for NPM, see this answer or the lazy option: re-install it which will re-add it for you.
LocalDateTime.parse(
"2018-01-23 01:23:45".replace( " " , "T" )
).plusHours( 2 )
The modern approach uses the java.time classes added to Java 8, Java 9, and later.
user enters in the format YYYY-MM-DD HH:MM:SS
Parse that input string into a date-time object. Your format is close to complying with standard ISO 8601 format, used by default in the java.time classes for parsing/generating strings. To fully comply, replace the SPACE in the middle with a T
.
String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45
Parse as a LocalDateTime
given that your input lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
add two hours
The java.time classes can do the math for you.
LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;
Be aware that a LocalDateTime
does not represent a moment, a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. The “Local” part of the name means any locality or no locality, rather than any one particular locality. Just saying "noon on Jan 21st" could mean noon in Auckland, New Zealand which happens several hours earlier than noon in Paris France.
To define an actual moment, you must specify a zone or offset.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Define an actual moment, a point on the timeline by giving a context with time zone.
If you know the intended time zone for certain, apply it before adding the two hours. The LocalDateTime
class assumes simple generic 24-hour days when doing the math. But in various time zones on various dates, days may be 23 or 25 hours long, or may be other lengths. So, for correct results in a zoned context, add the hours to your ZonedDateTime
rather than LocalDateTime
.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
=
(@AndrewF)+
(added by me)For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R
'USERNAME' %in% names(Sys.getenv())
math.log
is the natural logarithm:
math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).
Your equation is therefore:
n = math.log((1 + (FV * r) / p) / math.log(1 + r)))
Note that in your code you convert n to a str
twice which is unnecessary
Assuming you are using debian linux (I'm using Linux mint 12, problem was on Ubuntu 12.04.1 LTS server I ssh'ed into.)
I suggest taking @dkamins advice and making sure you have mcrypt installed and active on your php5 install. Use "sudo apt-get install php5-mcrypt" to install. My notes below.
Using PHP version PHP Version 5.3.10-1ubuntu3.4
, if you open phpinfo() as suggested by @John Conde, which you do by creating test file on web server (e.g. create status page testphp.php with just the contents "" anywhere accessible on the server via browser)
I found no presence of enabled or disabled status on the status page when opened in browser. When I then opened the php.ini file, mentioned by @Anthony Forloney, thinking to uncomment ;extension=php_mcrypt.dll to extension=php_mcrypt.dll
I toggled that back and forth and restarted Apache (I'm running Apache2 and you can restart in my setup with sudo /etc/init.d/apache2 restart
or when you are in that directory just sudo restart
I believe)
with change and without change but all no go. I took @dkamins advice and went to install the package with "sudo apt-get install php5-mcrypt" and then restarted apache as above. Then my error was gone and my application worked fine.
I had gone this way:
scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return isBlockedScrollView;
}
});
for xamarin ios:
public static void RotateAnimation (this UIView view, float duration=1, float rotations=1, float repeat=int.MaxValue)
{
var rotationAnimation = CABasicAnimation.FromKeyPath ("transform.rotation.z");
rotationAnimation.To = new NSNumber (Math.PI * 2.0 /* full rotation*/ * 1 * 1);
rotationAnimation.Duration = 1;
rotationAnimation.Cumulative = true;
rotationAnimation.RepeatCount = int.MaxValue;
rotationAnimation.RemovedOnCompletion = false;
view.Layer.AddAnimation (rotationAnimation, "rotationAnimation");
}
The officially supported method for this is:
GET graph.facebook.com/debug_token?
input_token={token-to-inspect}
&access_token={app-token-or-admin-token}
See the check token docs for more information.
An example response is:
{
"data": {
"app_id": 138483919580948,
"application": "Social Cafe",
"expires_at": 1352419328,
"is_valid": true,
"issued_at": 1347235328,
"metadata": {
"sso": "iphone-safari"
},
"scopes": [
"email",
"publish_actions"
],
"user_id": 1207059
}
}
Cleaning the project in Android studio and running again fixed the issue. May be do "Make Project" as well.
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
You can use a variable and change the variable instead.
````setInterval([the function], [the variable])```
\t
in a string marks an escape sequence for a tab character. For a literal \
, use \\
.
For reference, there's a pretty significant speed difference between the various stated solutions. Here is some comparison code. The solution pointed to by Lennart is called "historic", the one proposed by Ants is called "naive", and the one by RC is called "regexp."
from sys import argv
from time import time
def prime(i, primes):
for prime in primes:
if not (i == prime or i % prime):
return False
primes.add(i)
return i
def historic(n):
primes = set([2])
i, p = 2, 0
while True:
if prime(i, primes):
p += 1
if p == n:
return primes
i += 1
def naive(n):
from itertools import count, islice
primes = (n for n in count(2) if all(n % d for d in range(2, n)))
return islice(primes, 0, n)
def isPrime(n):
import re
# see http://tinyurl.com/3dbhjv
return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None
def regexp(n):
import sys
N = int(sys.argv[1]) # number of primes wanted (from command-line)
M = 100 # upper-bound of search space
l = list() # result list
while len(l) < N:
l += filter(isPrime, range(M - 100, M)) # append prime element of [M - 100, M] to l
M += 100 # increment upper-bound
return l[:N] # print result list limited to N elements
def dotime(func, n):
print func.__name__
start = time()
print sorted(list(func(n)))
print 'Time in seconds: ' + str(time() - start)
if __name__ == "__main__":
for func in naive, historic, regexp:
dotime(func, int(argv[1]))
The output of this on my machine for n = 100 is:
naive
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
Time in seconds: 0.0219371318817
historic
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
Time in seconds: 0.00515413284302
regexp
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
Time in seconds: 0.0733318328857
As you can see, there's a pretty big discrepancy. Here it is again for 1000 (prime outputs removed):
naive
Time in seconds: 1.49018788338
historic
Time in seconds: 0.148319005966
regexp
Time in seconds: 29.2350409031
use xargs
to make wget
working in multiple file in parallel
#!/bin/bash
mywget()
{
wget "$1"
}
export -f mywget
# run wget in parallel using 8 thread/connection
xargs -P 8 -n 1 -I {} bash -c "mywget '{}'" < list_urls.txt
Aria2 options, The right way working with file smaller than 20mb
aria2c -k 2M -x 10 -s 10 [url]
-k 2M
split file into 2mb chunk
-k
or --min-split-size
has default value of 20mb, if you not set this option and file under 20mb it will only run in single connection no matter what value of -x
or -s
You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
you can use CHARINDEX
in t-sql.
select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0
Select the Text
From the menu, go to Plugins > NPPExport > Copy RTF to clipboard
In MS Word go to Edit > Paste Special
This will open the Paste Special dialog box. Select the Paste radio button and from the list select Formatted Text (RTF)
You should be able to see the Formatted Text.
You need to put <!DOCTYPE HTML>
in the first line of your html.
Put your url here Facebook Login -> Settings -> Valid OAuth redirect URIs AND you'll also get that error if your APP ID is wrong
this is better function
function RGB2HTML(red, green, blue)
{
var decColor =0x1000000+ blue + 0x100 * green + 0x10000 *red ;
return '#'+decColor.toString(16).substr(1);
}
Depending on the scope of my application, I like to put the object hydration mechanisms in the object itself. I'll wrap the data reader with a custom object and pass it a delegate that gets executed once the query returns. The delegate gets passed the DataReader. Then, since I'm in my smart business object, I can hydrate away with my private setters.
The "DataAccessWrapper" wraps all of the connection and object lifecycle management for me. So, when I call "ExecuteDataReader," it creates the connection, with the passed proc (there's an overload for params,) executes it, executes the delegate and then cleans up after itself.
public class User
{
public static List<User> GetAllUsers()
{
DataAccessWrapper daw = new DataAccessWrapper();
return (List<User>)(daw.ExecuteDataReader("MyProc", new ReaderDelegate(ReadList)));
}
protected static object ReadList(SQLDataReader dr)
{
List<User> retVal = new List<User>();
while(dr.Read())
{
User temp = new User();
temp.Prop1 = dr.GetString("Prop1");
temp.Prop2 = dr.GetInt("Prop2");
retVal.Add(temp);
}
return retVal;
}
}
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
When TypeScript thinks that property "x" does not exist on "y", then you can always cast "y" into "any", which will allow you to call anything (like "x") on "y".
Theory
(<any>y).x;
Real World Example
I was getting the error "TS2339: Property 'name' does not exist on type 'Function'" for this code:
let name: string = this.constructor.name;
So I fixed it with:
let name: string = (<any>this).constructor.name;
Try this:
SELECT GETDATE(), 'Today'
UNION ALL
SELECT DATEADD(DAY, 10, GETDATE()), '10 Days Later'
UNION ALL
SELECT DATEADD(DAY, –10, GETDATE()), '10 Days Earlier'
UNION ALL
SELECT DATEADD(MONTH, 1, GETDATE()), 'Next Month'
UNION ALL
SELECT DATEADD(MONTH, –1, GETDATE()), 'Previous Month'
UNION ALL
SELECT DATEADD(YEAR, 1, GETDATE()), 'Next Year'
UNION ALL
SELECT DATEADD(YEAR, –1, GETDATE()), 'Previous Year'
Result Set:
———————– —————
2011-05-20 21:11:42.390 Today
2011-05-30 21:11:42.390 10 Days Later
2011-05-10 21:11:42.390 10 Days Earlier
2011-06-20 21:11:42.390 Next Month
2011-04-20 21:11:42.390 Previous Month
2012-05-20 21:11:42.390 Next Year
2010-05-20 21:11:42.390 Previous Year
The best option is to use the 'System.Diagnostics' namespace.
Enclose your code in if else block for debug mode and release mode as shown below to switch between debug and release mode in visual studio,
#if DEBUG // for debug mode
**Debugger.Launch();** //debugger will hit here
foreach (var job in JobFactory.GetJobs())
{
//do something
}
#else // for release mode
**Debugger.Launch();** //debugger will hit here
// write code here to do something in Release mode.
#endif
I have started using Markdown to post some of my documents to an internal web site for in-house users. It is an easy way to have a document shared but not able to be edited by the viewer.
So, this marking of text in color is “Great”. I have use several like this and works wonderful.
<span style="color:blue">some *This is Blue italic.* text</span>
Turns into This is Blue italic.
And
<span style="color:red">some **This is Red Bold.** text</span>
Turns into This is Red Bold.
I love the flexibility and ease of use.
Sometimes it's as simple as adding: '-ms-' in front of the style Like -ms-flex-flow: row wrap; to get it to work also.
After adding the icon to the toolbar and when modifying the selected icon, the ampersand in the name input is specifying that the next character is the character used along with Alt for the shortcut. Since you must select a display option from the Modify Selection drop down menu that includes displaying the text, you could also write &C in the name field and get the same result as &Comment Block (without the lengthy text).
View::share('site_settings', $site_settings);
Add to
app->Providers->AppServiceProvider
file boot method
it's global variable.
Very easy ... outside "span" element with small font and underline, and inside "font" element with bigger font size.
<span style="font-size:1em;text-decoration:underline;">_x000D_
<span style="font-size:1.5em;">_x000D_
Text with big font size and thin underline_x000D_
</span>_x000D_
</span>
_x000D_
Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn't be surprised.)
>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]
By lines I assume you mean rows in the table person
. What you're looking for is:
select p.name
from person p
where p.name LIKE '%A%'; --contains the character 'A'
The above is case sensitive. For a case insensitive search, you can do:
select p.name
from person p
where UPPER(p.name) LIKE '%A%'; --contains the character 'A' or 'a'
For the special character, you can do:
select p.name
from person p
where p.name LIKE '%'||chr(8211)||'%'; --contains the character chr(8211)
The LIKE
operator matches a pattern. The syntax of this command is described in detail in the Oracle documentation. You will mostly use the %
sign as it means match zero or more characters.
I like this option
for x in $(ls ./*.php); do echo $x; cat $x | grep -i 'menuItem'; done
Output looks like this:
./debug-things.php
./Facebook.Pixel.Code.php
./footer.trusted.seller.items.php
./GoogleAnalytics.php
./JivositeCode.php
./Live-Messenger.php
./mPopex.php
./NOTIFICATIONS-box.php
./reviewPopUp_Frame.php
$('#top-nav-scroller-pos-<?=$active**MenuItem**;?>').addClass('active');
gotTo**MenuItem**();
./Reviews-Frames-PopUps.php
./social.media.login.btns.php
./social-side-bar.php
./staticWalletsAlerst.php
./tmp-fix.php
./top-nav-scroller.php
$active**MenuItem** = '0';
$active**MenuItem** = '1';
$active**MenuItem** = '2';
$active**MenuItem** = '3';
./Waiting-Overlay.php
./Yandex.Metrika.php
You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.
Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.
Streams don't have a simple .toString()
function (which I understand) nor something like a .toStringAsync(cb)
function (which I don't understand).
So I created my own helper function:
var streamToString = function(stream, callback) {
var str = '';
stream.on('data', function(chunk) {
str += chunk;
});
stream.on('end', function() {
callback(str);
});
}
// how to use:
streamToString(myStream, function(myStr) {
console.log(myStr);
});
Try this:
in.nextLine();
This advances the Scanner to the next line.
You can use urllib2
import urllib2
content = urllib2.urlopen(some_url).read()
print content
Also you can use httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK
or the requests library
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200
You have to do:
git branch <branch_name> <commit>
(you were interchanging the branch name and commit)
Or you can do:
git checkout -b <branch_name> <commit>
If in place of you use branch name, you get a branch out of tip of the branch.
Maybe it's a coincidence that the column order you want happens to have column names in descending alphabetical order. Since that's the case you could just do:
df<-df[,order(colnames(df),decreasing=TRUE)]
That's what I use when I have large files with many columns.
Technical differences are a consequence of the goal of each one (OpenJDK is meant to be the reference implementation, open to the community, while Oracle is meant to be a commercial one)
They both have "almost" the same code of the classes in the Java API; but the code for the virtual machine itself is actually different, and when it comes to libraries, OpenJDK tends to use open libraries while Oracle tends to use closed ones; for instance, the font library.
Here's my Swift solution. In your subclass of UIViewController, override the navigationShouldPopOnBackButton method.
extension UIViewController {
func navigationShouldPopOnBackButton() -> Bool {
return true
}
}
extension UINavigationController {
func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool {
if let vc = self.topViewController {
if vc.navigationShouldPopOnBackButton() {
self.popViewControllerAnimated(true)
} else {
for it in navigationBar.subviews {
let view = it as! UIView
if view.alpha < 1.0 {
[UIView .animateWithDuration(0.25, animations: { () -> Void in
view.alpha = 1.0
})]
}
}
return false
}
}
return true
}
}
Here I did it using a rather simple form:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("url")
searchTxt=''
while not searchTxt:
try:
searchTxt=browser.find_element_by_name('NAME OF ELEMENT')
searchTxt.send_keys("USERNAME")
except:continue
If everything fails here is another solution:
$names = array();
foreach ($my_array as $my_object) {
$names[] = $my_object->name; //any object field
}
array_multisort($names, SORT_ASC, $my_array);
return $my_array;
@ubuntu 18.04
sudo apt install openjdk-8-jdk
then
sudo update-alternatives --config java
Selection Path Priority Status
------------------------------------------------------------
0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 auto mode
1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 manual mode
* 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode
Press <enter> to keep the current choice[*], or type selection number:
choose java 8 then restart netbeans
Done
It is a tradition to use Turbo C for graphic in C/C++. But it’s also a pain in the neck. We are using Code::Blocks IDE, which will ease out our work.
Steps to run graphics code in CodeBlocks:
To test the setting copy paste run following code:
#include <graphics.h>
int main( )
{
initwindow(400, 300, "First Sample");
circle(100, 50, 40);
while (!kbhit( ))
{
delay(200);
}
return 0;
}
Here is a complete setup instruction for Code::Blocks
Eclipse hooks Dynamic Web projects into tomcat and maintains it's own configuration but does not deploy the standard tomcat ROOT.war. As http://localhost:8085/ link returns 404 does indeed show that tomcat is up and running, just can't find a web app deployed to root.
By default, any deployed dynamic web projects use their project name as context root, so you should see http://localhost:8085/yourprojectname working properly, but check the Servers tab first to ensure that your web project has actually been deployed.
Hope that helps.
In the Powershell, cd to the .exe file location. For example:
cd C:\Users\Administrators\Downloads
PS C:\Users\Administrators\Downloads> & '.\aaa.exe'
The installer pops up and follow the instruction on the screen.
x = ['1', '2', '3']
s = f"{x[0]} BLAH {x[1]} FOO {x[2]} BAR"
print(s)
The output is
1 BLAH 2 FOO 3 BAR
Here's something a guy on Wordpress forum showed us. Add the following to your functions.php file. (remember to create a backup of your functions.php first)
add_filter( 'wp_image_editors', 'change_graphic_lib' );
function change_graphic_lib($array) {
return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}
...it was that simple.
These are known errors from libGL and libstdc++
You can quick fix this by change to use Software
for Emulated Performance Graphics
option, in the AVD settings.
Or try to use the libstdc++.so.6
(which is available in your system) instead of the one bundled inside Android SDK. There are 2 ways to replace it:
The emulator has a switch -use-system-libs
. You can found it here: ~/Android/Sdk/tools/emulator -avd Nexus_5_API_23 -use-system-libs
.
This option force Linux emulator to load the system libstdc++
(but not Qt libraries),
in cases where the bundled ones (from Android SDK) prevent it from loading or
working correctly. See this commit
Alternatively you can set the ANDROID_EMULATOR_USE_SYSTEM_LIBS
environment variable to 1
for your user/system
.
This has the benefit of making sure that the emulator will work even if you launched it from within Android Studio.
See: libGL error and libstdc++: Cannot launch AVD in emulator - Issue Tracker
which platform ?
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
ELSE FRUIT ='B' THEN 'BANANA'
END AS FRUIT
FROM FRUIT_TABLE;
The configuration I use in my parent level pom where I have separate unit and integration test phases.
I configure the following properties in the parent POM Properties
<maven.surefire.report.plugin>2.19.1</maven.surefire.report.plugin>
<jacoco.plugin.version>0.7.6.201602180812</jacoco.plugin.version>
<jacoco.check.lineRatio>0.52</jacoco.check.lineRatio>
<jacoco.check.branchRatio>0.40</jacoco.check.branchRatio>
<jacoco.check.complexityMax>15</jacoco.check.complexityMax>
<jacoco.skip>false</jacoco.skip>
<jacoco.excludePattern/>
<jacoco.destfile>${project.basedir}/../target/coverage-reports/jacoco.exec</jacoco.destfile>
<sonar.language>java</sonar.language>
<sonar.exclusions>**/generated-sources/**/*</sonar.exclusions>
<sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
<sonar.coverage.exclusions>${jacoco.excludePattern}</sonar.coverage.exclusions>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/coverage-reports</sonar.jacoco.reportPath>
<skip.surefire.tests>${skipTests}</skip.surefire.tests>
<skip.failsafe.tests>${skipTests}</skip.failsafe.tests>
I place the plugin definitions under plugin management.
Note that I define a property for surefire (surefireArgLine) and failsafe (failsafeArgLine) arguments to allow jacoco to configure the javaagent to run with each test.
Under pluginManagement
<build>
<pluginManagment>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<fork>true</fork>
<meminitial>1024m</meminitial>
<maxmem>1024m</maxmem>
<compilerArgument>-g</compilerArgument>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<forkCount>4</forkCount>
<reuseForks>false</reuseForks>
<argLine>-Xmx2048m ${surefireArgLine}</argLine>
<includes>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/*IT.java</exclude>
</excludes>
<skip>${skip.surefire.tests}</skip>
</configuration>
</plugin>
<plugin>
<!-- For integration test separation -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.19.1</version>
</dependency>
</dependencies>
<configuration>
<forkCount>4</forkCount>
<reuseForks>false</reuseForks>
<argLine>${failsafeArgLine}</argLine>
<includes>
<include>**/*IT.java</include>
</includes>
<skip>${skip.failsafe.tests}</skip>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
</goals>
</execution>
<execution>
<id>verify</id>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<!-- Code Coverage -->
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.plugin.version}</version>
<configuration>
<haltOnFailure>true</haltOnFailure>
<excludes>
<exclude>**/*.mar</exclude>
<exclude>${jacoco.excludePattern}</exclude>
</excludes>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>${jacoco.check.lineRatio}</minimum>
</limit>
<limit>
<counter>BRANCH</counter>
<value>COVEREDRATIO</value>
<minimum>${jacoco.check.branchRatio}</minimum>
</limit>
</limits>
</rule>
<rule>
<element>METHOD</element>
<limits>
<limit>
<counter>COMPLEXITY</counter>
<value>TOTALCOUNT</value>
<maximum>${jacoco.check.complexityMax}</maximum>
</limit>
</limits>
</rule>
</rules>
</configuration>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>${jacoco.destfile}</destFile>
<append>true</append>
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${jacoco.destfile}</dataFile>
<outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
<skip>${skip.surefire.tests}</skip>
</configuration>
</execution>
<execution>
<id>pre-integration-test</id>
<phase>pre-integration-test</phase>
<goals>
<goal>prepare-agent-integration</goal>
</goals>
<configuration>
<destFile>${jacoco.destfile}</destFile>
<append>true</append>
<propertyName>failsafeArgLine</propertyName>
</configuration>
</execution>
<execution>
<id>post-integration-test</id>
<phase>post-integration-test</phase>
<goals>
<goal>report-integration</goal>
</goals>
<configuration>
<dataFile>${jacoco.destfile}</dataFile>
<outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
<skip>${skip.failsafe.tests}</skip>
</configuration>
</execution>
<!-- Disabled until such time as code quality stops this tripping
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<dataFile>${jacoco.destfile}</dataFile>
</configuration>
</execution>
-->
</executions>
</plugin>
...
And in the build section
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<!-- for unit test execution -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<!-- For integration test separation -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
<plugin>
<!-- For code coverage -->
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
</plugin>
....
And in the reporting section
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>${maven.surefire.report.plugin}</version>
<configuration>
<showSuccess>false</showSuccess>
<alwaysGenerateFailsafeReport>true</alwaysGenerateFailsafeReport>
<alwaysGenerateSurefireReport>true</alwaysGenerateSurefireReport>
<aggregate>true</aggregate>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*.mar</exclude>
<exclude>${jacoco.excludePattern}</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</reporting>
One consideration is that FTP can use non-standard ports, which can make getting though firewalls difficult (especially if you're using SSL). HTTP is typically on a known port, so this is rarely a problem.
If you do decide to use FTP, make sure you read about Active and Passive FTP.
In terms of performance, at the end of the day they're both spewing files directly down TCP connections so should be about the same.
Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/
Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)
Libraries cannot be directly used in any program if not properly added to the project gradle files.
This can easily be done in smart IDEs like inteli J.
1) First as a convention add a folder names 'libs' under your project src file. (this can easily be done using the IDE itself)
2) then copy or add your library file (eg: .jar file) to the folder named 'libs'
3) now you can see the library file inside the libs folder. Now right click on the file and select 'add as library'. And this will fix all the relevant files in your program and library will be directly available for your use.
Please note:
Whenever you are adding libraries to a project, make sure that the project supports the library
How to Use TempTable in Stored Procedure?
Here are the steps:
CREATE TEMP TABLE
-- CREATE TEMP TABLE
Create Table #MyTempTable (
EmployeeID int
);
INSERT TEMP SELECT DATA INTO TEMP TABLE
-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100
SELECT TEMP TABLE (You can now use this select query)
Select EmployeeID from #MyTempTable
FINAL STEP DROP THE TABLE
Drop Table #MyTempTable
I hope this will help. Simple and Clear :)
use this and it works on both the static arrays and dynamically generated arrays.
var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );
I had the issue when I use trying to find max value from code below
$('#myTabs').find('li.active').prevAll().andSelf().each(function () {
newGetWidthOfEachTab.push(parseInt($(this).outerWidth()));
});
for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
newWidthOfEachTabTotal += newGetWidthOfEachTab[i];
newGetWidthOfEachTabArr.push(parseInt(newWidthOfEachTabTotal));
}
getMaxValue = Math.max.apply(Math, array);
I was getting 'NAN'
when I use
var max_value = Math.max(12, 21, 23, 2323, 23);
with my code
go to Start->Run and type cmd this starts the Command Prompt (also available from Start->Programs->Accessories->Command Prompt)
type cd .. and press return type cd .. and press return again (keep doing this until the prompt shows :> )
now you need to go to a special folder which might be c:\windows\system32 or it might be c:\winnt\system32 or it might be c:\windows\sysWOW64 try typing each of these eg cd c:\windows\sysWOW64 (if it says The system cannot find the path specified, try the next one) cd c:\windows\system32 cd c:\winnt\system32 when one of those doesn't cause an error, stop, you've found the correct folder.
now you need to register the OLE DB 4.0 DLLs by typing these commands and pressing return after each
regsvr32 Msjetoledb40.dll regsvr32 Msjet40.dll regsvr32 Mswstr10.dll regsvr32 Msjter40.dll regsvr32 Msjint40.dll
You don't need anything fancy: the following contains a new line (two, actually):
<summary>Tootsie roll tiramisu macaroon wafer carrot cake.
Danish topping sugar plum tart bonbon caramels cake.
</summary>
The question is, why isn't this newline having the desired effect: and that's a question about what the recipient of the XML is actually doing with it. For example, if the recipient is translating it to HTML and the HTML is being displayed in the browser, then the newline will be converted to a space by the browser. You need to tell us something about the processing pipeline.
Here's how I do it:
new WebDriverWait(driver, 20).until(
ExpectedConditions.jsReturnsValue(
"return document.readyState === 'complete' ? true : false"));
Answers = Answers.GroupBy(a => a.id).Select(x => x.First());
This will select each unique object by email
Duration timeLeft = Duration.ofMillis(3600000);
String hhmmss = String.format("%02d:%02d:%02d",
timeLeft.toHours(), timeLeft.toMinutesPart(), timeLeft.toSecondsPart());
System.out.println(hhmmss);
This prints:
01:00:00
You are doing right in letting library methods do the conversions involved for you. java.time
, the modern Java date and time API, or more precisely, its Duration
class does it more elegantly and in a less error-prone way than TimeUnit
.
The toMinutesPart
and toSecondsPart
methods I used were introduced in Java 9.
long hours = timeLeft.toHours();
timeLeft = timeLeft.minusHours(hours);
long minutes = timeLeft.toMinutes();
timeLeft = timeLeft.minusMinutes(minutes);
long seconds = timeLeft.toSeconds();
String hhmmss = String.format("%02d:%02d:%02d", hours, minutes, seconds);
System.out.println(hhmmss);
The output is the same as above.
java.time
comes built-in.org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Create a String class extension:
extension String
{ // returns false if passed string is nil or empty
static func isNilOrEmpty(_ string:String?) -> Bool
{ if string == nil { return true }
return string!.isEmpty
}
}// extension: String
Notice this will return TRUE if the string contains one or more blanks. To treat blank string as "empty", use...
return string!.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty
... instead. This requires Foundation.
Use it thus...
if String.isNilOrEmpty("hello world") == true
{ print("it's a string!")
}
I have created the Fade in and Fade Out animation for Dialogbox using ChrisJD code.
Inside res/style.xml
<style name="AppTheme" parent="android:Theme.Light" />
<style name="PauseDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/PauseDialogAnimation</item>
</style>
<style name="PauseDialogAnimation">
<item name="android:windowEnterAnimation">@anim/fadein</item>
<item name="android:windowExitAnimation">@anim/fadeout</item>
</style>
Inside anim/fadein.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />
Inside anim/fadeout.xml
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/anticipate_interpolator"
android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />
MainActivity
Dialog imageDiaglog= new Dialog(MainActivity.this,R.style.PauseDialog);
Currently, it's very easy to achieve this. You only need to add the following code to your pages:
<a href="whatsapp://send?text=<<HERE GOES THE URL ENCODED TEXT YOU WANT TO SHARE>>" data-action="share/whatsapp/share">Share via Whatsapp</a>
And that's it. No Javascript needed, nothing else needed. Of course you can style it as you want and include a nice Whatsapp icon.
I tested this in my Android device with Google Chrome. The versions:
It also works on iOS. I've made a quick test on an iPhone 5 with Safari and it works as well.
Hope this helps someone. :-)
If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.
If you can not use *ngif, [class.hide] works in angular 7. example:
<mat-select (selectionChange)="changeFilter($event.value)" multiple [(ngModel)]="selected">
<mat-option *ngFor="let filter of gridOptions.columnDefs"
[class.hide]="filter.headerName=='Action'" [value]="filter.field">{{filter.headerName}}</mat-option>
</mat-select>
You need to set the OFS
variable (output field separator) to be a tab:
echo "$line" |
awk -v var="$mycol_new" -F $'\t' 'BEGIN {OFS = FS} {$3 = var; print}'
(make sure you quote the $line
variable in the echo statement)
I did this before using the MSXML library and then using the XMLHttpRequest object, see here.
I experienced this issue when trying to restore a database on MS SQL Server 2012.
Here's what worked for me:
I had to first run the RESTORE FILELISTONLY
command below on the backup file to list the logical file names:
RESTORE FILELISTONLY
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
This displayed the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively:
LogicalName PhysicalName
com.my_db C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf
com.my_db_log C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf
All I had to do was to simply replace the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively in my database restore script:
USE master;
GO
ALTER DATABASE my_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE my_db
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
WITH REPLACE,
MOVE 'com.my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf',
MOVE 'com.my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf'
GO
ALTER DATABASE my_db SET MULTI_USER;
GO
And the Database Restore task ran successfully:
That's all.
I hope this helps
I wrote the code from the accepted answer as a jQuery plugin, which I find more useful. (also, it now ignores hidden, disabled, and readonly form elements).
$.fn.enterAsTab = function () {
$(this).find('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input:visible:not(disabled):not([readonly])"),
idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
return this;
};
This way I can do $('#form-id').enterAsTab(); ... Figured I'd post since no one has posted it as a $ plugin yet and they aren't entirely intuitive to write.
I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.
Here's the SSCCE:
import java.util.*;
import java.lang.management.ManagementFactory;
class main {
public static void main(final String[] args) {
System.out.println(fullVMArguments());
}
static String fullVMArguments() {
String name = javaVmName();
return (contains(name, "Server") ? "-server "
: contains(name, "Client") ? "-client " : "")
+ joinWithSpace(vmArguments());
}
static List<String> vmArguments() {
return ManagementFactory.getRuntimeMXBean().getInputArguments();
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static String javaVmName() {
return System.getProperty("java.vm.name");
}
static String joinWithSpace(Collection<String> c) {
return join(" ", c);
}
public static String join(String glue, Iterable<String> strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator<String> i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
}
Could be made shorter if you want the arguments in a List<String>
.
Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.
Before deploying an install package I always control the content of it.
It's just a simple call at the command line (according to Terrences post) open command line and enter
msiexec /a Package.msi /qb TARGETDIR="%CD%\Extract" /l*vx "%CD\install.log%"
This will extract package contents to an subdir 'Extract' with the current path.
Someone is not converting their line-ending characters correctly.
I assume it's the Windows folk as they love their CRLF. Unix loves LF and Mac loved CR until it was shown the Unix way.
I solved it with window.length
.
But with this solution you can take current error (X-Frame or 404).
iframe.onload = event => {
const isLoaded = event.target.contentWindow.window.length // 0 or 1
}
Rebase doesn't happen in the background. "rebase in progress" means that you started a rebase, and the rebase got interrupted because of conflict. You have to resume the rebase
(git rebase --continue
) or abort it (git rebase --abort
).
As the error message from git rebase --continue
suggests, you asked git to apply a patch that results in an empty patch. Most likely, this means the patch was already applied and you want to drop it using git rebase --skip
.
https://hub.docker.com/search?q=* shows all the images in the entire Docker hub, it's not possible to get this via the search command as it doesnt accept wildcards.
As of v1.10 you can find all the layers in an image by pulling it and using these commands:
docker pull ubuntu
ID=$(sudo docker inspect -f {{.Id}} ubuntu)
jq .rootfs.diff_ids /var/lib/docker/image/aufs/imagedb/content/$(echo $ID|tr ':' '/')
3) The size can be found in /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/size
although LAYERID != the diff_ids found with the previous command. For this you need to look at /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/diff
and compare with the previous command output to properly match the correct diff_id and size.
This is not an appropriate use of regular expressions. You'd be better off using
[0-9]{2}/[0-9]{2}/[0-9]{4}
and then checking ranges in a higher-level language.
You can send intent MASTER_CLEAR in adb:
adb shell am broadcast -a android.intent.action.MASTER_CLEAR
or as root
adb shell "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"
The line
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
would do the same as
when(someObject.doSomething(Matchers.any())).thenReturn(true);
So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.
And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.
In my case the problem is fixed by setting the right permissions for the tomcat home path:
cd /opt/apache-tomee-webprofile-7.1.0/
chown -R tomcat:tomcat *
from the SimpleDateFormat java doc:
* <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
* <td><code>02001.July.04 AD 12:08 PM</code>
* <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
* <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
a) Open the "php.ini". For XAMPP,it is located in C:\XAMPP\php\php.ini. Find out if you are using WAMP or LAMP server. Note : Make a backup of php.ini file
b) Search [mail function] in the php.ini file.
You can find like below.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost
Change the localhost to the smtp server name of your ISP. No need to change the smtp_port. Leave it as 25. Change sendmail_from from postmaster@localhost to your domain email address which will be used as from address..
So for me, it will become like this.
[mail function]
; For Win32 only.
SMTP = smtp.planetghost.com
smtp_port = 25
; For Win32 only.
sendmail_from = [email protected]
auth_username = [email protected]
auth_password = example_password
c) Restart the XAMPP or WAMP(apache server) so that changes will start working.
d) Now try to send the mail using the mail() function ,
mail("[email protected]","Success","Great, Localhost Mail works");
================================================================================
Another way
Gmail servers use SMTP Authentication under SSL. I think that there is no way to use the mail() function under that circumstances, so you might want to check these alternatives:
They both support SMTP auth under SSL.
Credit : Check reference answer here
Real example:
var trackList = Model.TrackingHistory.GroupBy(x => x.ShipmentStatusId).Select(x => x.Last()).Reverse();
List<int> done_step1 = new List<int>() {2,3,4,5,6,7,8,9,10,11,14,18,21,22,23,24,25,26 };
bool isExists = trackList.Where(x => done_step1.Contains(x.ShipmentStatusId.Value)).FirstOrDefault() != null;
NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.
NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];
[self.downloadTask resume];
You can then use the NSURLSessionDownloadDelegate delegate methods to monitor errors, download completion, download progress etc... There are inline block completion handler callback methods too if you prefer. Apples docs explain when you need to use one over the other.
Have a read of these articles:
To show both string.Split
and Regex
usage:
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");
You Must use
-(void)viewWillAppear:(BOOL)animated
and set your entries like you want...
For example, To store data in the session, you will typically use the put
method or the session
helper:
// Via a request instance...
$request->session()->put('key', 'value');
or
// Via the global helper...
session(['key' => 'value']);
for retrieving an item from the session, you can use get
:
$value = $request->session()->get('key', 'default value');
or global session
helper :
$value = session('key', 'default value');
To determine if an item is present in the session, you may use the has
method:
if ($request->session()->has('users')) {
//
}
Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.
From there you can change the binding options for both the client and the services, one of these options will be for time-outs.
Do not try to prevent SQL injection by sanitizing input data.
Instead, do not allow data to be used in creating your SQL code. Use Prepared Statements (i.e. using parameters in a template query) that uses bound variables. It is the only way to be guaranteed against SQL injection.
Please see my website http://bobby-tables.com/ for more about preventing SQL injection.
In my case, same code worked fine on Firefox, but not on Google Chrome. Google Chrome's JavaScript console said:
XMLHttpRequest cannot load http://www.xyz.com/getZipInfo.php?zip=11234.
Origin http://xyz.com is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"
I had to drop the www part of the Ajax URL for it to match correctly with the origin URL and it worked fine then.
Get input1 data to send them to input2 immediately
<div>
<label>Input1</label>
<input type="text" id="input1" value="">
</div>
</br>
<label>Input2</label>
<input type="text" id="input2" value="">
<script type="text/javascript">
$(document).ready(function () {
$("#input1").keyup(function () {
var value = $(this).val();
$("#input2").val(value);
});
});
</script>
I know this is an older question, but I found this nifty library on nuget that seems to do just the trick for me:
According https://apiblueprint.org/documentation/examples/13-named-endpoints.html is a resource a "general" place of storage of the given entity - e.g. /customers/30654/orders, whereas an endpoint is the concrete action (HTTP Method) over the given resource. So one resource can have multiple endpoints.
If you are developing a child theme you can use:
<img src="<?php echo get_template_directory_uri(); ?>-child/images/example.png" />
get_template_directory_uri() will return url to your currently active theme (parent theme), then you add -child/, then add path to your image (the example above assumes your image is at <child-theme-directory>/images/example.png
)
var a = 'something' + Array(10).fill('\xa0').join('') + 'something'
number inside Array(10)
can be changed to needed number of spaces
Like this
class CustomDictOne(dict):
def __init__(self,*arg,**kw):
super(CustomDictOne, self).__init__(*arg, **kw)
Now you can use the built-in functions, like dict.get()
as self.get()
.
You do not need to wrap a hidden self._dict
. Your class already is a dict.
I`ve aways use this:
<?php function fRand($len) {
$str = '';
$a = "abcdefghijklmnopqrstuvwxyz0123456789";
$b = str_split($a);
for ($i=1; $i <= $len ; $i++) {
$str .= $b[rand(0,strlen($a)-1)];
}
return $str;
} ?>
When you call it, sets the lenght of string.
<?php echo fRand([LENGHT]); ?>
You can also change the possible characters in the string $a
.
Besides authentication, I suggest you think about the big picture. Consider make your backend RESTful service without any authentication; then put some very simple authentication required middle layer service between the end user and the backend service.
This was the best way for me. You can retrieve all existing files (be it symbolic links or normal):
os.path.lexists(path)
Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat().
New in version 2.4.
It is working for me. I think you probably need to use urlencode()
on each of the components of $map_url
.
spent some time trying to import modules from a list, and this is the thread that got me most of the way there - but I didnt grasp the use of ___import____ -
so here's how to import a module from a string, and get the same behavior as just import. And try/except the error case, too. :)
pipmodules = ['pycurl', 'ansible', 'bad_module_no_beer']
for module in pipmodules:
try:
# because we want to import using a variable, do it this way
module_obj = __import__(module)
# create a global object containging our module
globals()[module] = module_obj
except ImportError:
sys.stderr.write("ERROR: missing python module: " + module + "\n")
sys.exit(1)
and yes, for python 2.7> you have other options - but for 2.6<, this works.
A simple answer is to click the magnifying glass on the left side bar
This is a simpler version
import pandas as pd
df = pd.DataFrame(columns=('col1', 'col2', 'col3'))
for i in range(5):
df.loc[i] = ['<some value for first>','<some value for second>','<some value for third>']`
"ABCDEFG".First
returns "A"
Dim s as string
s = "Rajan"
s.First
'R
s = "Sajan"
s.First
'S
TLDR for Python 3:
import subprocess
import sys
with open('test.log', 'wb') as f:
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
for c in iter(lambda: process.stdout.read(1), b''):
sys.stdout.buffer.write(c)
f.buffer.write(c)
You have two ways of doing this, either by creating an iterator from the read
or readline
functions and do:
import subprocess
import sys
with open('test.log', 'w') as f: # replace 'w' with 'wb' for Python 3
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
for c in iter(lambda: process.stdout.read(1), ''): # replace '' with b'' for Python 3
sys.stdout.write(c)
f.write(c)
or
import subprocess
import sys
with open('test.log', 'w') as f: # replace 'w' with 'wb' for Python 3
process = subprocess.Popen(your_command, stdout=subprocess.PIPE)
for line in iter(process.stdout.readline, ''): # replace '' with b'' for Python 3
sys.stdout.write(line)
f.write(line)
Or you can create a reader
and a writer
file. Pass the writer
to the Popen
and read from the reader
import io
import time
import subprocess
import sys
filename = 'test.log'
with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader:
process = subprocess.Popen(command, stdout=writer)
while process.poll() is None:
sys.stdout.write(reader.read())
time.sleep(0.5)
# Read the remaining
sys.stdout.write(reader.read())
This way you will have the data written in the test.log
as well as on the standard output.
The only advantage of the file approach is that your code doesn't block. So you can do whatever you want in the meantime and read whenever you want from the reader
in a non-blocking way. When you use PIPE
, read
and readline
functions will block until either one character is written to the pipe or a line is written to the pipe respectively.
I had a similar issue.
Cause:
import HomeComponent from "components/HomeComponent";
Solution:
import HomeComponent from "./components/HomeComponent";
NOTE: ./
was before components. You can read @Zac Kwan's post above on how to use import
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
To change the password for a key myalias
inside of the keystore mykeyfile
:
keytool -keystore mykeyfile -keypasswd -alias myalias
This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:
window.getSelection().anchorNode.textContent.substring(
window.getSelection().extentOffset,
window.getSelection().anchorOffset)
Deletes all child fields in the database then we use on_delete as so:
class user(models.Model):
commodities = models.ForeignKey(commodity, on_delete=models.CASCADE)
Use the <button>
tag instead. <button>
labels are vertically centered by default.
When a servlet 3.0 application starts the container has to scan all the classes for annotations (unless metadata-complete=true). Tomcat uses a fork (no additions, just unused code removed) of Apache Commons BCEL to do this scanning. The web app is failing to start because BCEL has come across something it doesn't understand.
If the applications runs fine on Tomcat 6, adding metadata-complete="true" in your web.xml or declaring your application as a 2.5 application in web.xml will stop the annotation scanning.
At the moment, this looks like a problem in the class being scanned. However, until we know which class is causing the problem and take a closer look we won't know. I'll need to modify Tomcat to log a more useful error message that names the class in question. You can follow progress on this point at: https://issues.apache.org/bugzilla/show_bug.cgi?id=53161
Well i understand the aboves answers are correct but they are on application level, why don't we simply use .htaccess
file to set the expire time ?
<IfModule mod_php5.c>
#Session timeout
php_value session.cookie_lifetime 1800
php_value session.gc_maxlifetime 1800
</IfModule>
I prefer skipping it, I read somewhere that interfaces are by default, public
and abstract
.
To my surprise the book - Head First Design Patterns, is using public
with interface declaration and interface methods... that made me rethink once again and I landed up on this post.
Anyways, I think redundant information should be ignored.
There is issue of 31st and 28th Feb with getDate()
I use this function getTime
and 24*60*60*1000 = 86400000
var dateWith31 = new Date("2017-08-31");_x000D_
var dateWith29 = new Date("2016-02-29");_x000D_
_x000D_
var amountToIncreaseWith = 1; //Edit this number to required input_x000D_
_x000D_
console.log(incrementDate(dateWith31,amountToIncreaseWith));_x000D_
console.log(incrementDate(dateWith29,amountToIncreaseWith));_x000D_
_x000D_
function incrementDate(dateInput,increment) {_x000D_
var dateFormatTotime = new Date(dateInput);_x000D_
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));_x000D_
return increasedDate;_x000D_
}
_x000D_
Upgrade MySql driver to Connector/Python 8.0.17 or greater than 8.0.17, Those who are using greater than MySQL 5.5 version
I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with
$my_url = urlencode("my url");
and then calling
file_get_contents($my_url);
and see if you have better luck.
An awesome repository here .
api : masfufa.js
sample : masfufa.html
Two Examples will be enough to understand this library :
/* | 1 , 2 , 3 |
* MX= | 4 , 5 , 6 | Dimensions= 3 x 3
* | 7 , 8 , 9 |
*/
jsdk.getAPI('my');
var A=[1, 2, 3, 4, 5, 6, 7, 8, 9];
var MX=myAPI.getInstance('masfufa',{data:A,dim:'3x3'});
then :
MX.get[0][0] // -> 1 (first)
MX.get[2][2] // ->9 (last)
/* | 1 , 9 , 3 , 4 |
* MXB= | 4 , 5 , 6 , 2 | Dimensions= 2 x 4
*
*/
var B=[1 , 9 , 3 , 4 , 4 , 5 , 6 , 2];
var MXB=myAPI.getInstance('masfufa',{data:B,dim:'2x4'});
then :
MXB.get[0][0] // -> 1 (first)
MXB.get[1][3] // -> 2 (last)
MXB.get[1][2] // -> 6 (before last)
document.getElementById('mybox').style.display = "block";
There is no other way, so this is the best.
Edit: This answer is not valid since PHP 5.4 and higher.