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.
Scan your workspace .metadata
directory for files called *.launch
. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core
one.
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 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.
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
I would approach it like this:
sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s) for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1): size = sizes[choice - 1] # note index offset from choice print "You want to create a random song list that is {0}Mb.".format(size)
You could also loop until you get an acceptable answer and cover yourself in case of error:
choice = 0 while choice not in range(1, len(sizes) + 1): # loop try: # guard against error choice = int(raw_input(...)) except ValueError: # couldn't make an int print "Please enter a number" choice = 0 size = sizes[choice - 1] # now definitely valid
This regex should do it.
\b[a-z]+-[a-z]+\b
\b
indicates a word-boundary.
A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:
$ curl -I https://atmosphere.meteor.com HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive
However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.
<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script>
If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should 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);
A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:
t = Guide.arel_table Guide.where(t[:title].matches('%attack'))
Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null
comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null
the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.
Nonprimitive (int
s, char
s, double
s, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.
On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.
In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.
And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.
Java's actually very nicely made so that you shouldn't have to worry about null
ing variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.
*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.
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.
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');
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
You can use Jquery's on method and listen for the scroll
event.
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.)
Most likely, as mentioned by others, it is a class carrying the css values:
.clear{clear: both;}
in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.
In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.
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:
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?
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
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.
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.
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.
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
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
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
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);
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
Set the "Build Active Architecture Only"(ONLY_ACTIVE_ARCH)
build setting to yes, xcode
is asking for arm64 because of Silicon MAC architecture which is arm64.
arm64 has been added as simulator arch in Xcode12 to support Silicon MAC.
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/SDKSettings.json
try
ng update @angular/core @angular/cli
Then, just to sync material, run:
ng update @angular/material
This problem occurred because there is global installs of create-react-app
are no longer supported. For solving this problem, you should uninstall and remove completely create-react-app
from your system, so run these command respectively:
npm uninstall -g create-react-app
or
yarn global remove create-react-app
Then please check if the create-react-app exists or not with this command
which create-react-app
If it returns any correct path like a
/c/Users/Dell/AppData/Local/Yarn/bin/create-react-app
Then run this command to remove create-react-app
globally
rm -rf /c/Users/Dell/AppData/Local/Yarn/bin/create-react-app
Now you can create a new react app with one of these commands:
npx create-react-app my-app
npm init react-app my-app
yarn create react-app my-app
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;
}
use Illuminate\Support\Facades\Route;
Warning Disappeared after importing the corresponding namespace.
Version's
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
I didn't figure out what exactly was happening, but I found a solution.
The CDN feature of OVH was the culprit. I had it installed on my host service but disabled for my domain because I didn't need it.
Somehow, when I enable it, everything works.
I think it forces Apache to use the HTTP2 protocol, but what I don't understand is that there indeed was an HTTP2 mention in each of my headers, which I presume means the server was answering using the right protocol.
So the solution for my very particular case was to enable the CDN option on all concerned domains.
If anyone understands better what could have happened here, feel free to share explanations.
I got an stacktrace similar to yours only when building to Lollipop or Marshmallow, and the solution was to disable Advanved profiling.
Find it here:
Run -> Edit Configurations -> Profiling -> Enable advanced profiling
the following LATEST solution works for me:
function ClickConnect(){
colab.config
console.log("Connnect Clicked - Start");
document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect").click();
console.log("Connnect Clicked - End");
};
setInterval(ClickConnect, 60000)
For me, The problem was solved after I close Visual Studio and Open it again
Simple answer: replace python with PY everything will work as expected
This error can also occur when you make the mistake of declaring useDispatch from react-redux the wrong way:
when you go:
const dispatch = useDispatch
instead of:
const dispatch = useDispatch();
(i.e remember to add the parenthesis)
issue = “UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.”
And this worked for me
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Qt5Agg')
Xcode 11.5
Simply use ZStack to add background color or images to your main view in SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Color.black
}
.edgesIgnoringSafeArea(.vertical)
}
}
Hi instead of using hook API, you should use Higher-order component API as mentioned here
I'll modify the example in the documentation to suit your need for class component
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';
const styles = theme => ({
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
});
class HigherOrderComponentUsageExample extends React.Component {
render(){
const { classes } = this.props;
return (
<Button className={classes.root}>This component is passed to an HOC</Button>
);
}
}
HigherOrderComponentUsageExample.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(HigherOrderComponentUsageExample);
For me I changed in the parent tag of the pom.xml and it solved it change 2.1.5 to 2.1.4 then Maven-> Update Project
Use following commands to install node v11.15.0
and gulp v3.9.1
:
npm install -g n
sudo n 11.15.0
npm install gulp@^3.9.1
npm install
npm rebuild node-sass
Will solve this issue:
ReferenceError: primordials is not defined in node
What I have found is that TensorFlow 2.0 (I am using 2.0.0-alpha0) is not compatible with the latest version of Numpy i.e. v1.17.0 (and possibly v1.16.5+). As soon as TF2 is imported, it throws a huge list of FutureWarning, that looks something like this:
FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
This also resulted in the allow_pickle error when tried to load imdb dataset from keras
I tried to use the following solution which worked just fine, but I had to do it every single project where I was importing TF2 or tf.keras.
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)
The easiest solution I found was to either install numpy 1.16.1 globally, or use compatible versions of tensorflow and numpy in a virtual environment.
My goal with this answer is to point out that its not just a problem with imdb.load_data, but a larger problem vaused by incompatibility of TF2 and Numpy versions and may result in many other hidden bugs or issues.
If you want to use tf.contrib, you need to now copy and paste the source code from github into your script/notebook. It's annoying and doesn't always work. But that's the only workaround I've found. For example, if you wanted to use tf.contrib.opt.AdamWOptimizer, you have to copy and paste from here. https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/opt/python/training/weight_decay_optimizers.py#L32
In the app function you have incorrectly spelled the word setpersonSate
, missing the letter t
, thus it should be setpersonState
.
Error:
const app = props => {
const [personState, setPersonSate] = useState({....
Solution:
const app = props => {
const [personState, setPersonState] = useState({....
For ng9 upgraders:
npm i -g core-js@^3
..then:
npm cache clean -f
..followed by:
npm i
Based on responses and comments below, the following was the simple solution for my issue and THIS WORKED. Now my app, Match4app, is fully compatible with latest iOS versions!
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
I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.
const SingInContainer = ({ message, variant}) => {
const [open, setSnackBarState] = useState(false);
const handleClose = (reason) => {
if (reason === 'clickaway') {
return;
}
setSnackBarState(false)
};
if (variant) {
setSnackBarState(true); // HERE BE DRAGONS
}
return (
<div>
<SnackBar
open={open}
handleClose={handleClose}
variant={variant}
message={message}
/>
<SignInForm/>
</div>
)
}
Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:
const SingInContainer = ({ message, variant}) => {
const [open, setSnackBarState] = useState(variant ? true : false);
// or useState(!!variant);
// or useState(Boolean(variant));
const handleClose = (reason) => {
if (reason === 'clickaway') {
return;
}
setSnackBarState(false)
};
return (
<div>
<SnackBar
open={open}
handleClose={handleClose}
variant={variant}
message={message}
/>
<SignInForm/>
</div>
)
}
See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.
Another answer since Francesco Borzi's didn't work for me.
Add this to your travis.yml:
addons:
chrome: stable
before_script:
- LATEST_CHROMEDRIVER_VERSION=`curl -s "https://chromedriver.storage.googleapis.com/LATEST_RELEASE"`
- curl "https://chromedriver.storage.googleapis.com/${LATEST_CHROMEDRIVER_VERSION}/chromedriver_linux64.zip" -O
- unzip chromedriver_linux64.zip -d ~/bin
Many thanks and credit to tagliala on github:
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>
Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class
TweenAnimationBuilder<Duration>(
duration: Duration(minutes: 3),
tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
onEnd: () {
print('Timer ended');
},
builder: (BuildContext context, Duration value, Widget child) {
final minutes = value.inMinutes;
final seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('$minutes:$seconds',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30)));
}),
and You also get onEnd call back which notifies you when the animation completes;
here's the output
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.
Make sure you create the project with conda environment option selected.
My problem solved by recreate the project and select "conda" from "New environment using" options
see image:
const handleClick = async (item: NavheadersType, index: number) => {
const newNavHeaders = [...navheaders];
if (item.url) {
await router.push(item.url); =>>>> line causing error (causing route to happen)
// router.push(item.url); =>>> coreect line
newNavHeaders.forEach((item) => (item.active = false));
newNavHeaders[index].active = true;
setnavheaders([...newNavHeaders]);
}
};
On OSX 10.15.4 running xcode-select --install
fixed the issue for me.
For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version
I haved a similar problem, I fixed here:
uses-material-design: true
assets:
- assets/images/
After, do:
Flutter Clean
A supplemental visual view of pd.concat([df0, df1], kwargs)
.
Notice that, kwarg axis=0
or axis=1
's meaning is not as intuitive as df.mean()
or df.apply(func)
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
You can multiply numpy arrays by scalars and it just works.
>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2, 4, 6],
[ 8, 10, 12]])
This is also a very fast and efficient operation. With your example:
>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
[6., 8.]])
Angular and Django Rest Framework.
I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.
In my case the error was caused by the lack of space on my machine. Deleting old builds fixed the problem.
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
Just delete module-info.java at your Project Explorer tab.
Just add style="width:5% !important;"
to th and td
<ng-container matColumnDef="username">
<th style="width:5% !important;" mat-header-cell *matHeaderCellDef> Full Name </th>
<td style="width:5% !important;" mat-cell *matCellDef="let element"> {{element.username}} ( {{element.usertype}} )</td>
</ng-container>
When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.
This is how I did it.
Step 1: Install Java 11
You can download Java 11 dmg for mac from here: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html
Step 2: After installation of Java 11. Confirm installation of all versions. Type the following command in your terminal.
/usr/libexec/java_home -V
Step 3: Edit .bash_profile
sudo nano ~/.bash_profile
Step 4: Add 11.0.1 as default. (Add below line to bash_profile file).
export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.1)
to switch to any version
export JAVA_HOME=$(/usr/libexec/java_home -v X.X.X)
Now Press CTRL+X to exit the bash. Press 'Y' to save changes.
Step 5: Reload bash_profile
source ~/.bash_profile
Step 6: Confirm current version of Java
java -version
I face this issue after updating to 3.3.0
If you are not doing what error states in gradle file, it is some plugin that still didn't update to the newer API that cause this. To figure out which plugin is it do the following (as explained in "Better debug info when using obsolete API" of 3.3.0 announcement):
Hope it helps others
I did try all the answers above and had no luck. After that I restart my iPhone and problem seems gone. I know it is so stupid but it worked. Answers above most probably solves the problem but if not try to restart your iOS device.
For me In Xcode 10, this solution worked like a charm. Just go to the Recovered References folder and remove all files in red color and add it again with proper reference. If Recovered References folder was not found: Check for all missing files in the project (files in red colour) and try to add files references again.
Let me share my experience for this issue fix.
Open target -> Build phases -> Copy Bundle Resources and remove info.plist.
Note: If you're using any extensions, remove the info.plist of that extension from the Targets.
Hope it helps.
In my.cnf file check below 2 steps.
check this value -
old_passwords=0;
it should be 0.
check this also-
[mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure
[mysqld] section should be like this.
If you have anaconda install than you just need to use command: conda install PyAudio
.
In order to execute this command you must set thePYTHONPATH
environment variable in anaconda.
Updated Answer
As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.
This answer is no longer valid
As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.
After almost 3 hours of searching and spending time on the same error, I found that I'm using name import for React:
import { React } from 'react';
which is totally wrong. Just by switching it to:
import React from 'react';
all the error are gone. I hope this helps someone. This is my .babelrc:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
the webpack.config.js
const path = require('path');
const devMode = process.env.Node_ENV !== 'production';
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/App.js',
devtool: 'source-map',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'App.js'
},
mode: 'development',
devServer: {
contentBase: path.resolve(__dirname, 'public'),
port:9090,
open: 'google chrome',
historyApiFallback: true
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},{
test: /\.(sa|sc|c)ss$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[local]--[hash:base64:5]',
sourceMap: true
}
},{
loader: 'sass-loader'
}
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: devMode ? '[name].css' : '[name].[hash].css',
chunkFilename: devMode ? '[id].css' : '[id].[hash].css'
})
]
}
the package.json
{
"name": "expense-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.1.2",
"@babel/core": "^7.1.2",
"@babel/plugin-proposal-class-properties": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.4",
"css-loader": "^1.0.0",
"mini-css-extract-plugin": "^0.4.3",
"node-sass": "^4.9.3",
"react-router-dom": "^4.3.1",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.9"
},
"dependencies": {
"normalize.css": "^8.0.0",
"react": "^16.5.2",
"react-dom": "^16.5.2"
}
}
var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');
Change this line from your code to this -
var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');
or in my case, I gave the encoding in reverse order
var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');
Because of your initialization wrong.
Don't do like this,
MethodName _methodName;
Do like this,
MethodName _methodName = MethodName();
You can enable Jetifier
on your project, which will basically exchange the Android Support Library
dependencies in your project dependencies with AndroidX
-ones. (e.g. Your Lottie dependencies will be changed from Support to AnroidX)
From the Android Studio Documentation (https://developer.android.com/studio/preview/features/):
The Android Gradle plugin provides the following global flags that you can set in your gradle.properties file:
- android.useAndroidX: When set to true, this flag indicates that you want to start using AndroidX from now on. If the flag is absent, Android Studio behaves as if the flag were set to false.
- android.enableJetifier: When set to true, this flag indicates that you want to have tool support (from the Android Gradle plugin) to automatically convert existing third-party libraries as if they were written for AndroidX. If the flag is absent, Android Studio behaves as if the flag were set to false.
Precondition for Jetifier:
Android Studio 3.2
To enable jetifier, add those two lines to your gradle.properties
file:
android.useAndroidX=true
android.enableJetifier=true
Finally, please check the release notes of AndroidX, because jetifier
has still some problems with some libraries (e.g. Dagger Android): https://developer.android.com/topic/libraries/support-library/androidx-rn
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
I found that if I run CMD as Administrator and run the command, I can install it without a problem. Try it and give me some feedback.
In case you have more than just Password and Verify Password fields. Like this the Confirm password field will only highlights error when user write something on this field:
validators.ts
import { FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
export const EmailValidation = [Validators.required, Validators.email];
export const PasswordValidation = [
Validators.required,
Validators.minLength(6),
Validators.maxLength(24),
];
export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value && control.dirty)
}
}
export function RepeatPasswordValidator(group: FormGroup) {
const password = group.controls.password.value;
const passwordConfirmation = group.controls.passwordAgain.value;
return password === passwordConfirmation ? null : { passwordsNotEqual: true }
}
register.component.ts
import { FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import { EmailValidation, PasswordValidation, RepeatPasswordEStateMatcher, RepeatPasswordValidator } from 'validators';
...
form: any;
passwordsMatcher = new RepeatPasswordEStateMatcher;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group ( {
email: new FormControl('', EmailValidation),
password: new FormControl('', PasswordValidation),
passwordAgain: new FormControl(''),
acceptTerms: new FormControl('', [Validators.requiredTrue])
}, { validator: RepeatPasswordValidator });
}
...
register.component.html
<form [formGroup]="form" (ngSubmit)="submitAccount(form)">
<div class="form-content">
<div class="form-field">
<mat-form-field>
<input matInput formControlName="email" placeholder="Email">
<mat-error *ngIf="form.get('email').hasError('required')">
E-mail is mandatory.
</mat-error>
<mat-error *ngIf="form.get('email').hasError('email')">
Incorrect E-mail.
</mat-error>
</mat-form-field>
</div>
<div class="form-field">
<mat-form-field>
<input matInput formControlName="password" placeholder="Password" type="password">
<mat-hint class="ac-form-field-description">Between 6 and 24 characters.</mat-hint>
<mat-error *ngIf="form.get('password').hasError('required')">
Password is mandatory.
</mat-error>
<mat-error *ngIf="form.get('password').hasError('minlength')">
Password with less than 6 characters.
</mat-error>
<mat-error *ngIf="form.get('password').hasError('maxlength')">
Password with more than 24 characters.
</mat-error>
</mat-form-field>
</div>
<div class="form-field">
<mat-form-field>
<input matInput formControlName="passwordAgain" placeholder="Confirm the password" type="password" [errorStateMatcher]="passwordsMatcher">
<mat-error *ngIf="form.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
</mat-form-field>
</div>
<div class="form-field">
<mat-checkbox name="acceptTerms" formControlName="acceptTerms">I accept terms and conditions</mat-checkbox>
</div>
</div>
<div class="form-bottom">
<button mat-raised-button [disabled]="!form.valid">Create Account</button>
</div>
</form>
i hope it helps!
This is the code that I have used.
Container(
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('Network_Image_Link')),
color: Colors.blue,
borderRadius: BorderRadius.all(Radius.circular(25.0)),
),
),
Thank you!!!
Replacing CRLF with LF using Notepad++
Rebuild and run the docker image should solve your problem.
Requirements:
Worked great without restart on Xcode 10
Use this:
print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
sum += number
print("Total Sum is: %d" %sum )
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
Remove this line from your code:
console.info(JSON.parse(scatterSeries));
As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx
Template
<form [formGroup]="mainForm" ng-submit="submitForm()">
Global Price: <input type="number" formControlName="globalPrice">
<button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
<table border formArrayName="orderLines">
<ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
<tr>
<td>{{orderLine.time | date}}</td>
<td>{{orderLine.quantity}}</td>
<td><input formControlName="price" type="number"></td>
</tr>
</ng-container>
</table>
</form>
Component
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 6';
mainForm: FormGroup;
orderLines = [
{price: 10, time: new Date(), quantity: 2},
{price: 20, time: new Date(), quantity: 3},
{price: 30, time: new Date(), quantity: 3},
{price: 40, time: new Date(), quantity: 5}
]
constructor() {
this.mainForm = this.getForm();
}
getForm(): FormGroup {
return new FormGroup({
globalPrice: new FormControl(),
orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
})
}
getFormGroupForLine(orderLine: any): FormGroup {
return new FormGroup({
price: new FormControl(orderLine.price)
})
}
applyPriceToAll() {
const formLines = this.mainForm.get('orderLines') as FormArray;
const globalPrice = this.mainForm.get('globalPrice').value;
formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
// optionally recheck value and validity without emit event.
}
submitForm() {
}
}
A simple case that generates this error message:
In [8]: [1,2,3,4,5][np.array([1])]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-55def8e1923d> in <module>()
----> 1 [1,2,3,4,5][np.array([1])]
TypeError: only integer scalar arrays can be converted to a scalar index
Some variations that work:
In [9]: [1,2,3,4,5][np.array(1)] # this is a 0d array index
Out[9]: 2
In [10]: [1,2,3,4,5][np.array([1]).item()]
Out[10]: 2
In [11]: np.array([1,2,3,4,5])[np.array([1])]
Out[11]: array([2])
Basic python list indexing is more restrictive than numpy's:
In [12]: [1,2,3,4,5][[1]]
....
TypeError: list indices must be integers or slices, not list
Looking again at
indices = np.random.choice(range(len(X_train)), replace=False, size=50000, p=train_probs)
indices
is a 1d array of integers - but it certainly isn't scalar. It's an array of 50000 integers. List's cannot be indexed with multiple indices at once, regardless of whether they are in a list or array.
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
I had the same problem with my Chrome extension. When I tried to add to my manifest "content_scripts" option this part:
//{
// "matches": [ "<all_urls>" ],
// "css": [ "myStyles.css" ],
// "js": [ "test.js" ]
//}
And I remove the other part from my manifest "permissons":
"https://*/"
Only when I delete it CORB on one of my XHR reqest disappare.
Worst of all that there are few XHR reqest in my code and only one of them start to get CORB error (why CORB do not appare on other XHR I do not know; why manifest changes coused this error I do not know). That's why I inspected the entire code again and again by few hours and lost a lot of time.
More simply in one line:
proxy=192.168.2.1:8080;curl -v example.com
eg. $proxy=192.168.2.1:8080;curl -v example.com
xxxxxxxxx-ASUS:~$ proxy=192.168.2.1:8080;curl -v https://google.com|head -c 15 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
By Default angular return responseType as Json, but we can configure below types according to your requirement.
responseType: 'arraybuffer'|'blob'|'json'|'text'
Ex:
this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'});
Android documentation is clear on this.Go to the below page.Underneath,there are two columns with names "OLD BUILD ARTIFACT" and "AndroidX build artifact"
https://developer.android.com/jetpack/androidx/migrate
Now you have many dependencies in gradle.Just match those with Androidx build artifacts and replace them in the gradle.
That won't be enough.
Go to your MainActivity (repeat this for all activities) and remove the word AppCompact Activity in the statement "public class MainActivity extends AppCompatActivity " and write the same word again.But this time androidx library gets imported.Until now appcompact support file got imported and used (also, remove that appcompact import statement).
Also,go to your layout file. Suppose you have a constraint layout,then you can notice that the first line constraint layout in xml file have something related to appcompact.So just delete it and write Constraint layout again.But now androidx related constraint layout gets added.
repeat this for as many activities and as many xml layout files..
But don't worry: Android Studio displays all such possible errors while compiling.
An Alternative Solution to the above
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
color: Colors.white,
child: ...
)
You can use BorderRadius.only() to customize the corners you wish to manage.
If you can't upload import file due to big size and you can't modify parameters because you are in a shared hosting try to install on your computer HeidiSQL and load file from there.
It happens when common column in both table are of different data type.
Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.
First, import it:
import { useHistory } from 'react-router-dom';
Then, in function or class:
const history = useHistory();
Finally, you put it in the onClick
function:
<Button onClick={()=> history.push("/mypage")}>Click me!</Button>
If you receive an error stating the library cannot be found, check the Google maven repo for your library and version. I had a version suddenly disappear and make my builds fail.
I had an almost identical error:
Error while connecting to MySQL: Authentication plugin 'caching_sha2_password' is not supported
The solution for me was simple:
My db username/password creds were incorrect. The error was not descriptive of the problem, so I thought I would share this in case someone else runs into this.
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
Another cause might be the fact that you're pointing to the wrong port.
Make sure you are actually pointing to the right SQL server. You may have a default installation of MySQL running on 3306 but you may actually be needing a different MySQL instance.
Check the ports and run some query against the db.
Use jdbc url
as :
jdbc:mysql://localhost:3306/Database_dbName?allowPublicKeyRetrieval=true&useSSL=false;
PortNo: 3306
can be different in your configuation
That's works for me, commit and then:
ng update @angular/cli @angular/core
npm install --save-dev @angular/cli@latest
For those who've been confused by CREATE USER 'root'@'localhost'
when you already have a root account on the server machine, keep in mind that your 'root'@'localhost'
and 'root'@'your_remote_ip'
are two different users (same user name, yet different scope) in mysql server. Hence, creating a new user with your_remote_ip
postfix will actually create a new valid root
user that you can use to access the mysql server from a remote machine.
For example, if you're using root
to connect to your mysql server from a remote machine whose IP is 10.154.10.241
and you want to set a password for the remote root account which is 'Abcdef123!@#'
, here are steps you would want to follow:
On your mysql server machine, do mysql -u root -p
, then enter your password for root
to login.
Once in mysql>
session, do this to create root user for the remote scope:
mysql> CREATE USER 'root'@'10.154.10.241' IDENTIFIED BY 'Abcdef123!@#';
After the Query OK
message, do this to grant the newly created root user all privileges:
mysql> GRANT ALL ON *.* TO 'root'@'10.154.10.241';
And then:
FLUSH PRIVILEGES;
Restart the mysqld service:
sudo service mysqld restart
Confirm that the server has successfully restarted:
sudo service mysqld status
If the steps above were executed without any error, you can now access to the mysql server from a remote machine using root
.
try use keyup.enter or keydown.enter
<button type="submit" (keyup.enter)="search(...)">Search</button>
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide(color: Colors.red)
),
I just run into this problem too, with all the MySQL re-config mentioned above the error still appears. It turns out that I misspelled the database name.
So be sure you're connecting with the right database name especially the case.
So I did mine with the full styling and border colors like this:
new OutlineButton(
shape: StadiumBorder(),
textColor: Colors.blue,
child: Text('Button Text'),
borderSide: BorderSide(
color: Colors.blue, style: BorderStyle.solid,
width: 1),
onPressed: () {},
)
For those who are having trouble with fatal error: ESP8266WiFi.h: No such file or directory
, you can install the package manually.
You may still need to have the http://arduino.esp8266.com/stable/package_esp8266com_index.json package installed beforehand, however.
Edit: That wasn't the full issue, you need to make sure you have the correct ESP8266 Board selected before compiling.
Hope this helps others.
Now you can upgrade to PHP7.4 and MySQL will go with caching_sha2_password
by default, so default MySQL installation will work with mysqli_connect
No configuration required.
class MyApp2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: AppBarTheme(
elevation: 0,
color: Colors.blueAccent,
)
),
title: 'Welcome to flutter ',
home: HomePage()
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int number = 0;
void _increment(){
setState(() {
number ++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueAccent,
appBar: AppBar(
title: Text('MyApp2'),
leading: Icon(Icons.menu),
// backgroundColor: Colors.blueAccent,
),
body: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(200.0),
topRight: Radius.circular(200)
),
color: Colors.white,
),
)
);
}
}
You can simply use RaisedButton
or you can use InkWell
to get custom button and also properties like onDoubleTap
, onLongPress
and etc
.:
new InkWell(
onTap: () => print('hello'),
child: new Container(
//width: 100.0,
height: 50.0,
decoration: new BoxDecoration(
color: Colors.blueAccent,
border: new Border.all(color: Colors.white, width: 2.0),
borderRadius: new BorderRadius.circular(10.0),
),
child: new Center(child: new Text('Click Me', style: new TextStyle(fontSize: 18.0, color: Colors.white),),),
),
),
If you want to use splashColor
, highlightColor
properties in InkWell
widget, use Material
widget as the parent of InkWell
widget instead of decorating the container(deleting decoration property). Read why? here.
You can access most IP cameras using the method below.
import cv2
# insert the HTTP(S)/RSTP feed from the camera
url = "http://username:password@your_ip:your_port/tmpfs/auto.jpg"
# open the feed
cap = cv2.VideoCapture(url)
while True:
# read next frame
ret, frame = cap.read()
# show frame to user
cv2.imshow('frame', frame)
# if user presses q quit program
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# close the connection and close all windows
cap.release()
cv2.destroyAllWindows()
There are two primary contenders for python apps on Android
This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."
This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.
Both are active projects and their github accounts shows a fair amount of recent activity.
Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.
On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.
New MySQL 8.0.11 is using caching_sha2_password
as default authentication method. I think that phpMyAdmin cannot understand this authentication method.
You need to create user with one of the older authentication method, e.g. CREATE USER xyz@localhost IDENTIFIED WITH mysql_native_password BY 'passw0rd'
.
More here https://dev.mysql.com/doc/refman/8.0/en/create-user.html and here https://dev.mysql.com/doc/refman/8.0/en/authentication-plugins.html
Although this is an old thread, I had the same issue today, last week I updated some NuGet packages and although the MVC website worked OK on my dev machine when I published to the testing server it failed.
I read numerous posts but none worked. I finally compared the DLL's in my local bin to those in the testing server and found that the netstandard.dll was not uploaded, once uploaded the website worked OK, not sure why VS2017 web deploy did not publish the DLL.
Just something to look out for in case none of the above work for you.
Step 1 curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py Step2 python get-pip.py
you can update all of the dependencies to their latest version by
npm update
DateTimeFormat
, introduced in java 8:The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z
. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
. The trailing 'Z'
is the interesting part. Usually there's time zone data here, like -0700
. So the pattern would be ...Z
, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy"
. Mind the small y
-s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
I've been knocking other people's (@datayeah & Vithani Ravi) solutions a bit hard here, so I thought I'd share my own attempt[s] at solving this variable screen density scaling problem or shut up. So I approach this problem from a solid/fixed foundation: I base all my scaling off a fixed (immutable) ratio of 2:1 (height:width). I have a helper class "McGyver" that does all the heavy lifting (and useful code finessing) across my app. This "McGyver" class contains only static methods and static constant class members.
RATIO SCALING METHOD: I scale both width & height independently based on the 2:1 Aspect Ratio. I take width & height input values and divide each by the width & height constants and finally compute an adjustment factor by which to scale the respective width & height input values. The actual code looks as follows:
import 'dart:math';
import 'package:flutter/material.dart';
class McGyver {
static const double _fixedWidth = 410; // Set to an Aspect Ratio of 2:1 (height:width)
static const double _fixedHeight = 820; // Set to an Aspect Ratio of 2:1 (height:width)
// Useful rounding method (@andyw solution -> https://stackoverflow.com/questions/28419255/how-do-you-round-a-double-in-dart-to-a-given-degree-of-precision-after-the-decim/53500405#53500405)
static double roundToDecimals(double val, int decimalPlaces){
double mod = pow(10.0, decimalPlaces);
return ((val * mod).round().toDouble() / mod);
}
// The 'Ratio-Scaled' Widget method (takes any generic widget and returns a "Ratio-Scaled Widget" - "rsWidget")
static Widget rsWidget(BuildContext ctx, Widget inWidget, double percWidth, double percHeight) {
// ---------------------------------------------------------------------------------------------- //
// INFO: Ratio-Scaled "SizedBox" Widget - Scaling based on device's height & width at 2:1 ratio. //
// ---------------------------------------------------------------------------------------------- //
final int _decPlaces = 5;
final double _fixedWidth = McGyver._fixedWidth;
final double _fixedHeight = McGyver._fixedHeight;
Size _scrnSize = MediaQuery.of(ctx).size; // Extracts Device Screen Parameters.
double _scrnWidth = _scrnSize.width.floorToDouble(); // Extracts Device Screen maximum width.
double _scrnHeight = _scrnSize.height.floorToDouble(); // Extracts Device Screen maximum height.
double _rsWidth = 0;
if (_scrnWidth == _fixedWidth) { // If input width matches fixedWidth then do normal scaling.
_rsWidth = McGyver.roundToDecimals((_scrnWidth * (percWidth / 100)), _decPlaces);
} else { // If input width !match fixedWidth then do adjustment factor scaling.
double _scaleRatioWidth = McGyver.roundToDecimals((_scrnWidth / _fixedWidth), _decPlaces);
double _scalerWidth = ((percWidth + log(percWidth + 1)) * pow(1, _scaleRatioWidth)) / 100;
_rsWidth = McGyver.roundToDecimals((_scrnWidth * _scalerWidth), _decPlaces);
}
double _rsHeight = 0;
if (_scrnHeight == _fixedHeight) { // If input height matches fixedHeight then do normal scaling.
_rsHeight = McGyver.roundToDecimals((_scrnHeight * (percHeight / 100)), _decPlaces);
} else { // If input height !match fixedHeight then do adjustment factor scaling.
double _scaleRatioHeight = McGyver.roundToDecimals((_scrnHeight / _fixedHeight), _decPlaces);
double _scalerHeight = ((percHeight + log(percHeight + 1)) * pow(1, _scaleRatioHeight)) / 100;
_rsHeight = McGyver.roundToDecimals((_scrnHeight * _scalerHeight), _decPlaces);
}
// Finally, hand over Ratio-Scaled "SizedBox" widget to method call.
return SizedBox(
width: _rsWidth,
height: _rsHeight,
child: inWidget,
);
}
}
... ... ...
Then you would individually scale your widgets (which for my perfectionist disease is ALL of my UI) with a simple static call to the "rsWidget()" method as follows:
// Step 1: Define your widget however you like (this widget will be supplied as the "inWidget" arg to the "rsWidget" method in Step 2)...
Widget _btnLogin = RaisedButton(color: Colors.blue, elevation: 9.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(McGyver.rsDouble(context, ScaleType.width, 2.5))),
child: McGyver.rsText(context, "LOGIN", percFontSize: EzdFonts.button2_5, textColor: Colors.white, fWeight: FontWeight.bold),
onPressed: () { _onTapBtnLogin(_tecUsrId.text, _tecUsrPass.text); }, );
// Step 2: Scale your widget by calling the static "rsWidget" method...
McGyver.rsWidget(context, _btnLogin, 34.5, 10.0) // ...and Bob's your uncle!!
The cool thing is that the "rsWidget()" method returns a widget!! So you can either assign the scaled widget to another variable like _rsBtnLogin
for use all over the place - or you could simply use the full McGyver.rsWidget()
method call in-place inside your build()
method (exactly how you need it to be positioned in the widget tree) and it will work perfectly as it should.
For those more astute coders: you will have noticed that I used two additional ratio-scaled methods McGyver.rsText()
and McGyver.rsDouble()
(not defined in the code above) in my RaisedButton()
- so I basically go crazy with this scaling stuff...because I demand my apps to be absolutely pixel perfect at any scale or screen density!! I ratio-scale my ints, doubles, padding, text (everything that requires UI consistency across devices). I scale my texts based on width only, but specify which axis to use for all other scaling (as was done with the ScaleType.width
enum used for the McGyver.rsDouble()
call in the code example above).
I know this is crazy - and is a lot of work to do on the main thread - but I am hoping somebody will see my attempt here and help me find a better (more light-weight) solution to my screen density 1:1 scaling nightmares.
If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none
Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:
If you found display of [hidden] class is overridden, you need to add this css code to your style:
[hidden] {
display: none !important;
}
You can Easily change the Input Type using the keyboardType Parameter and you have a lot of possibilities check the documentation TextInputType so you can use the number or phone value
new TextField(keyboardType: TextInputType.number)
This is the easiest way in my opinion:
RaisedButton(
child: Text("PRESS BUTTON"),
onPressed: booleanCondition
? () => myTapCallback()
: null
)
Your logic condition is wrong. IIUC, what you want is:
import pyspark.sql.functions as f
df.filter((f.col('d')<5))\
.filter(
((f.col('col1') != f.col('col3')) |
(f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
)\
.show()
I broke the filter()
step into 2 calls for readability, but you could equivalently do it in one line.
Output:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
You do not need to create a virtual device using android studio. You can use your android device running on android 8.0 or higher. All you have to do is to activate developer settings, then enable USB DEBUGGING in the developer settings. Your device will show at the bottom right side of the VS Code. Without enabling the USB debugging, the device may not show.enter image description here
I had this problem suddenly happening after trying to pull a dependency depending on sdk 28 (firebase crashlytics), but then decided to revert back the changes.
I tried automatic refactor Migrate to Androidx
(which do half the job), added android.useAndroidX=true
in gradle.properties
at some points, and make the project work again.
But it was a lot of changes before a delivery. There was no way to have the project compile again with SDK 27. I git clean -fd
, removed $HOME/.gradle
, and kept seeing androidx in ./gradlew :app:dependencies
I ended up removing ~/.AndroidStudio3.5/
too (I'm on 3.5.3). This makes the project compile again, and I discovered the dark mode...
Note: For MAC OS
Not a conventional answer, but I guess you could transpose the dataframe to look at the rows instead of the columns. I use this because I find looking at rows more 'intuitional' than looking at columns:
data_all2.T
This should let you view all the rows. This action is not permanent, it just lets you view the transposed version of the dataframe.
If the rows are still truncated, just use print(data_all2.T)
to view everything.
If any of the answers mentioned here doesn't work then go to File > Invalidate Catches/Restart
I know this has already been highly voted in here by now, but I'd rather go for a custom directive approach and rely on the ClipboardEvent as @jockeisorby suggested, while also making sure the listener is correctly removed (same function needs to be provided for both the add and remove event listeners)
stackblitz demo
import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";
@Directive({ selector: '[copy-clipboard]' })
export class CopyClipboardDirective {
@Input("copy-clipboard")
public payload: string;
@Output("copied")
public copied: EventEmitter<string> = new EventEmitter<string>();
@HostListener("click", ["$event"])
public onClick(event: MouseEvent): void {
event.preventDefault();
if (!this.payload)
return;
let listener = (e: ClipboardEvent) => {
let clipboard = e.clipboardData || window["clipboardData"];
clipboard.setData("text", this.payload.toString());
e.preventDefault();
this.copied.emit(this.payload);
};
document.addEventListener("copy", listener, false)
document.execCommand("copy");
document.removeEventListener("copy", listener, false);
}
}
and then use it as such
<a role="button" [copy-clipboard]="'some stuff'" (copied)="notify($event)">
<i class="fa fa-clipboard"></i>
Copy
</a>
public notify(payload: string) {
// Might want to notify the user that something has been pushed to the clipboard
console.info(`'${payload}' has been copied to clipboard`);
}
Note: notice the window["clipboardData"]
is needed for IE as it does not understand e.clipboardData
Others have answered so I'll add my 2-cents.
You can either use autoconfiguration (i.e. don't use a @Configuration to create a datasource) or java configuration.
Auto-configuration:
define your datasource type then set the type properties. E.g.
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
spring.datasource.hikari.username=sa
spring.datasource.hikari.password=password
spring.datasource.hikari.max-wait=10000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.leak-detection-threshold=600000
spring.datasource.hikari.maximum-pool-size=100
spring.datasource.hikari.pool-name=MyDataSourcePoolName
Java configuration:
Choose a prefix and define your data source
spring.mysystem.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.mysystem.datasource.jdbc-
url=jdbc:sqlserver://databaseserver.com:18889;Database=MyDatabase;
spring.mysystem.datasource.username=dsUsername
spring.mysystem.datasource.password=dsPassword
spring.mysystem.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.mysystem.datasource.max-wait=10000
spring.mysystem.datasource.connection-timeout=30000
spring.mysystem.datasource.idle-timeout=600000
spring.mysystem.datasource.max-lifetime=1800000
spring.mysystem.datasource.leak-detection-threshold=600000
spring.mysystem.datasource.maximum-pool-size=100
spring.mysystem.datasource.pool-name=MySystemDatasourcePool
Create your datasource bean:
@Bean(name = { "dataSource", "mysystemDataSource" })
@ConfigurationProperties(prefix = "spring.mysystem.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
You can leave the datasource type out, but then you risk spring guessing what datasource type to use.
Nothing worked for me until I updated my kotlin plugin dependency.
Try this:
1. Invalidate cahce and restart.
2. Sync project (at least try to)
3. Go File -> Project Structure -> Suggestions
4. If there is an update regarding Kotlin, update it.
Hope it will help someone.
As Vinay Kumar pointed out that it will not update global installed Angular CLI. To update it globally just use following commands:
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
Note if you want to update existing project you have to modify existing project, you should change package.json inside your project.
There are no breaking changes in Angular itself but they are in RxJS, so don't forget to use rxjs-compat library to work with legacy code.
npm install --save rxjs-compat
I wrote a good article about installation/updating Angular CLI http://bmnteam.com/angular-cli-installation/
In Linux environment, after installing docker
and docker-compose
reboot is required for work docker better.
$ reboot
OR restart the docker
$ sudo systemctl restart docker
Use "javascript.validate.enable": false
in your VS Code settings, It doesn't disable ESLINT. I use both ESLINT & Flow. Simply follow the instructions Flow For Vs Code Setup
Adding this line in settings.json. Helps
"javascript.validate.enable": false
In my case I use a template component in Blazor.
<BTable ID="Table1" TotalRows="MyList.Count()">
The problem is calling a method (Count) in the component header. To resolve the problem I changed it like this :
int total = MyList.Count();
and later :
<BTable ID="Table1" TotalRows="total">
I am using Visual Studio Code 1.52.1 on windows 10 machine.'cls' or 'Clear' doesn't clear the terminal.
just write
exit
It will close the terminal and press
ctrl+shift+`
to open new terminal.
You can have a datetime picker when using matInput
with type datetime-local
like so:
<mat-form-field>
<input matInput type="datetime-local" placeholder="start date">
</mat-form-field>
You can click on each part of the placeholder to set the day, month, year, hours,minutes and whether its AM or PM.
A slight variation of the nice @liangli's solution that does not require to change the index of existing dataframes:
newdf = df1.drop(df1.join(df2.set_index('Name').index))
"docker build -f Dockerfile -t SpringBoot-Docker ." As in the above commend, we are creating an image file for docker container. commend says create image use file(-f refer to docker file) and -t for the target of the image file we are going to push to docker. the "." represents the current directory
solution for the above problem: provide target image name in lowercase
Thanks, Max S. conda-forge worked for me as well.
Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:
First, check available the packages with versions
conda list
It will show packages and their installed versions in the output:
scikit-learn 0.19.1 py36hedc7406_0
Upgrade to 0.19.2 July 2018 release.
conda config --append channels conda-forge
conda install scikit-learn=0.19.2
Now check the version installed correctly or not?
conda list
Output is:
scikit-learn 0.19.2 py36_blas_openblasha84fab4_201 [blas_openblas] conda-forge
I tried following commands:
!conda update conda
!pip install -U scikit-learn
It will install the required packages also will show in the conda list
but when try to import that package it will not work.
On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.
It could be done in Bootstrap 4 using the responsive grid columns. One column for the sidebar and one for the main content.
Bootstrap 4 Sidebar switch to Top Navbar on mobile
<div class="container-fluid h-100">
<div class="row h-100">
<aside class="col-12 col-md-2 p-0 bg-dark">
<nav class="navbar navbar-expand navbar-dark bg-dark flex-md-column flex-row align-items-start">
<div class="collapse navbar-collapse">
<ul class="flex-md-column flex-row navbar-nav w-100 justify-content-between">
<li class="nav-item">
<a class="nav-link pl-0" href="#">Link</a>
</li>
..
</ul>
</div>
</nav>
</aside>
<main class="col">
..
</main>
</div>
</div>
Alternate sidebar to top
Fixed sidebar to top
For the reverse (Top Navbar that becomes a Sidebar), can be done like this example
In my case i forgot to add the () after the function name inside the render function of a react component
public render() {
let ctrl = (
<>
<div className="aaa">
{this.renderView}
</div>
</>
);
return ctrl;
};
private renderView() : JSX.Element {
// some html
};
Changing the render method, as it states in the error message to
<div className="aaa">
{this.renderView()}
</div>
fixed the problem
In my case, upgraded from spring-securiy-web 3.1.3 to 4.2.12, the defaultHttpFirewall
was changed from DefaultHttpFirewall
to StrictHttpFirewall
by default.
So just define it in XML configuration like below:
<bean id="defaultHttpFirewall" class="org.springframework.security.web.firewall.DefaultHttpFirewall"/>
<sec:http-firewall ref="defaultHttpFirewall"/>
set HTTPFirewall
as DefaultHttpFirewall
I'd a similar issue, my Swagger documentation broke after I was adding async version of APIs to existing ones. I played around the Swagger DLL's by installing / Reinstalling, finally commenting newly added APIs, and it worked. Then I added different signature in attributes, and bingo!, It worked.
In your case, you are having two API with matching signatures
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{`enter code here`
return "value";
}
Try providing different names in attributes like
[HttpGet("List")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("ListById/{id}")]
public string Get(int id)
{
return "value";
}
This should solve the issue.
If you want to use default mailtrip.io
you don't need to modify mail.php
file.
.env
file and replace all null
s of correct credentials:MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
php artisan config:cache
If you are using Gmail there is an instruction for Gmail: https://stackoverflow.com/a/64582540/7082164
Mcrypt PECL extenstion
sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install libmcrypt-dev
sudo pecl install mcrypt-1.0.1
When you are shown the prompt
libmcrypt prefix? [autodetect] :
Press [Enter] to autodetect.
After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.
The output will look like this:
...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so' ----> this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini
Grab installing path and add to cli and apache2 php.ini configuration.
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"
Verify that the extension was installed
Run command:
php -i | grep "mcrypt"
The output will look like this:
/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value
In Gradle build file, add dependency:
implementation 'com.android.support:multidex:1.0.2'
or
implementation 'com.android.support:multidex:1.0.3'
or
implementation 'com.android.support:multidex:2.0.0'
And then in the "defaultConfig" section, add:
multiDexEnabled true
Under targetSdkVersion
minSdkVersion 17
targetSdkVersion 27
multiDexEnabled true
Now if you encounter this error
Error:Failed to resolve: multidex-instrumentation Open File
You need to change your gradle to 3.0.1
classpath 'com.android.tools.build:gradle:3.0.1'
And put the following code in the file gradle-wrapper.properties
distributionUrl=https://services.gradle.org/distributions/gradle-4.1-all.zip
Finally
add class Applition in project And introduce it to the AndroidManifest Which is extends from MultiDexApplication
public class App extends MultiDexApplication {
@Override
public void onCreate( ) {
super.onCreate( );
}
}
Run the project first to create an error, then clean the project
Finally, Re-launch the project and enjoy it
element: HTMLElement;
constructor() {}
fakeClick(){
this.element = document.getElementById('ButtonX') as HTMLElement;
this.element.click();
}
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
Try this solution:
Go to->
Example Code index.php :
<?php
if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
$uri = 'https://';
} else {
$uri = 'http://';
}
$uri .= $_SERVER['HTTP_HOST'];
header('Location: '.$uri.'/dashboard/');
exit;
?>
One-line numpy solution for downsampling (by 2):
smaller_img = bigger_img[::2, ::2]
And upsampling (by 2):
bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1)
(this asssumes HxWxC shaped image. h/t to L. Kärkkäinen in the comments above. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))
My preference is to utilize the inline
attribute. This will cause the icon to correctly scale with the size of the button.
<button mat-button>
<mat-icon inline=true>local_movies</mat-icon>
Movies
</button>
<!-- Link button -->
<a mat-flat-button color="accent" routerLink="/create"><mat-icon inline=true>add</mat-icon> Create</a>
I add this to my styles.css
to:
button.mat-button .mat-icon,
a.mat-button .mat-icon,
a.mat-raised-button .mat-icon,
a.mat-flat-button .mat-icon,
a.mat-stroked-button .mat-icon {
vertical-align: top;
font-size: 1.25em;
}
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
pandas.Series.astype
You can do something like this :
weather["Temp"] = weather.Temp.astype(float)
You can also use pd.to_numeric
that will convert the column from object to float
Example :
s = pd.Series(['apple', '1.0', '2', -3])
print(pd.to_numeric(s, errors='ignore'))
print("=========================")
print(pd.to_numeric(s, errors='coerce'))
Output:
0 apple
1 1.0
2 2
3 -3
=========================
dtype: object
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64
In your case you can do something like this:
weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
convert_objects
Example is as follows
>> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
You can use this as follows:
weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
NaN
... so be careful while using it.I had the same problem and I fixed it just by setting this: <item name="android:windowIsFloating">false</item>
in styles.xml
I had the same issue, I could solve it by switching fom JDK 11 to JDK 8.
You need to install the "xlrd" lib
For Linux (Ubuntu and Derivates):
Installing via pip: python -m pip install --user xlrd
Install system-wide via a Linux package manager: *sudo apt-get install python-xlrd
Windows:
Installing via pip: *pip install xlrd
Download the files: https://pypi.org/project/xlrd/
EDIT: For Angular 6+, please use Nimesh Nishara Indimagedara's answer mentioning:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled'
});
Original Answer:
If all fails, then create some empty HTML element (eg: div) at the top (or desired scroll to location) with id="top" on template (or parent template):
<div id="top"></div>
And in component:
ngAfterViewInit() {
// Hack: Scrolls to top of Page after page view initialized
let top = document.getElementById('top');
if (top !== null) {
top.scrollIntoView();
top = null;
}
}
This worked for me;
sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php
Line No : 614
Replace two codes :
Replace:
(count($analyzed_sql_results[‘select_expr’] == 1)
With:
(count($analyzed_sql_results[‘select_expr’]) == 1)
AND
Replace:
($analyzed_sql_results[‘select_expr’][0] == ‘*’)))
With:
($analyzed_sql_results[‘select_expr’][0] == ‘*’))
save, exit and run
sudo service apache2 restart
From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows
from django.contrib import admin
from django.urls import path
from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^posts/$', post_home, name='post_home'),
]
where posts is an application & post_home is a function in views.py
Well, I faced the same issue whenever I change my login password.
Below is the command I need to run to fix this issue:-
git config --global credential.helper wincred
After running above command it asks me again my updated username and password.
A Spring Boot project configured through Maven can be run using the following command from the project source folder
mvn spring-boot:run
This happens because your local module named urllib.py
shadows the installed requests module you are trying to use. The current directory is preapended to sys.path, so the local name takes precedence over the installed name.
An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name of your script in question is matching the module you are trying to import.
Rename your file to something else like url.py
.
Then It is working fine.
Hope it helps!
The OS is not recognizing 'python' command. So try 'py'
Use 'py -m pip'
Yes, ConfigurationManager.AppSettings
is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager
.
Credits goes to @JeroenMostert for giving me the solution.
some symbols should be transferred like '%'
<string name="test" formatted="false">95%</string>
If the requested resource of the server is using Flask. Install Flask-CORS.
Try to clear cache in android studio by File-> Invalidate cache -> invalidate after invalidating build-> clean project Then you can able to build the project
Best way is using BoxDecoration()
Advantage
Disadvantage
BoxDecoration
only use with Container
widget so you want to wrap your widget in Container()
Example
Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.orange,
border: Border.all(
color: Colors.pink[800],// set border color
width: 3.0), // set border width
borderRadius: BorderRadius.all(
Radius.circular(10.0)), // set rounded corner radius
boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))]// make rounded corner of border
),
child: Text("My demo styling"),
)
Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :
public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions>
{
public IServiceProvider ServiceProvider { get; set; }
public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider)
: base (options, logger, encoder, clock)
{
ServiceProvider = serviceProvider;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync ()
{
var headers = Request.Headers;
var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);
if (string.IsNullOrEmpty (token)) {
return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
}
bool isValidToken = false; // check token here
if (!isValidToken) {
return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
}
var claims = new [] { new Claim ("token", token) };
var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
return Task.FromResult (AuthenticateResult.Success (ticket));
}
}
Startup.cs :
#region Authentication
services.AddAuthentication (o => {
o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion
And mycontroller.cs
[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }
I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :
public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}
You should define static class SchemesNamesConst
. Something like:
public static class SchemesNamesConst
{
public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}
If you are in corporate setting where there is a proxy server, double check your proxy settings.
If you think you fat-fingered the password, there is a Clear passwords button you can click to where you can re-enter your creds. HTH
Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.
More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize
The snippets to save & load can be found below:
model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')
# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')
A sample output of this :
That's all. You may want to revoke the old certificate on developer.apple.com too.
Step 1: Xcode -> Product -> Archives -> Click manage certificate
Step 2: Add iOS distribution
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
If this is a node service, try the steps outlined here
Basically, it's a Cross-Origin Resource Sharing (CORS) error. More information about such errors here.
Once I updated my node service with the following lines it worked:
let express = require("express");
let app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
Many times as API's are updated. We forgot to update SDK Managers. For accessing recent API's one should always have highest API Level updated if possible should also have other regularly used lower level APIs to accommodate backward compatibility.
Go to build.gradle (module.app) file
change compileSdkVersion
buildToolsVersion
targetSdkVersion, all should have the highest level of API.
Redirection in angularjs 4 Button for event in eg:app.home.html
<input type="button" value="clear" (click)="onSubmit()"/>
and in home.componant.ts
import {Component} from '@angular/core';
import {Router} from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.home.html',
})
export class HomeComponant {
title = 'Home';
constructor(
private router: Router,
) {}
onSubmit() {
this.router.navigate(['/doctor'])
}
}
Select e.lastname as employee ,m.lastname as manager
from employees e,employees m
where e.managerid=m.employyid(+)
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
int x, y;
std::stringstream stream;
std::cin >> x;
stream << x;
stream >> std::hex >> y;
std::cout << y;
return 0;
}
Firstly, vendor bundles are huge simply because Angular 2 relies on a lot of libraries. Minimum size for Angular 2 app is around 500KB (250KB in some cases, see bottom post).
Tree shaking is properly used by angular-cli
.
Do not include .map
files, because used only for debugging. Moreover, if you use hot replacement module, remove it to lighten vendor.
To pack for production, I personnaly use Webpack (and angular-cli relies on it too), because you can really configure everything
for optimization or debugging.
If you want to use Webpack
, I agree it is a bit tricky a first view, but see tutorials on the net, you won't be disappointed.
Else, use angular-cli
, which get the job done really well.
Using Ahead-of-time compilation is mandatory to optimize apps, and shrink Angular 2 app to 250KB.
Here is a repo I created (github.com/JCornat/min-angular) to test minimal Angular bundle size, and I obtain 384kB. I am sure there is easy way to optimize it.
Talking about big apps, using the AngularClass/angular-starter configuration, the same as in the repo above, my bundle size for big apps (150+ components) went from 8MB (4MB without map files) to 580kB.
Active mode: -server initiates the connection.
Passive mode: -client initiates the connection.
I think the main and biggest difference they have is that ListView
looks for the position of the item while creating or putting it, on the other hand RecyclerView
looks for the type of the item. if there is another item created with the same type RecyclerView
does not create it again. It asks first adapter and then asks to recycledpool, if recycled pool says "yeah I've created a type similar to it", then RecyclerView
doesn't try to create same type. ListView
doesn't have a this kind of pooling mechanism.
File.Create(string)
returns an instance of the FileStream
class. You can call the Stream.Close()
method on this object in order to close it and release resources that it's using:
var myFile = File.Create(myPath);
myFile.Close();
However, since FileStream
implements IDisposable
, you can take advantage of the using
statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:
using (var myFile = File.Create(myPath))
{
// interact with myFile here, it will be disposed automatically
}
The problem with using transaction is that you lock the table also for reading. So if you have really much data to insert and you need to access to your data, for exemple a preview or so, this way doesn't work well.
The problem with the other solution is that you lose the order of the inserting
insert into mytable (col)
select 'c'
union
select 'd'
union
select 'a'
union
select 'b';
In the sqlite the data will be store a,b,c,d...
You can regroup your steps functions calls in a facade function :
sub facade()
call step1()
call step2()
call step3()
call step4()
call step5()
end sub
Then, let your error handling be in an upper function that calls the facade :
sub main()
On error resume next
call facade()
If Err.Number <> 0 Then
' MsgBox or whatever. You may want to display or log your error there
msgbox Err.Description
Err.Clear
End If
On Error Goto 0
end sub
Now, let's suppose step3()
raises an error. Since facade()
doesn't handle errors (there is no On error resume next
in facade()
), the error will be returned to main()
and step4()
and step5()
won't be executed.
Your error handling is now refactored in 1 code block
I think a regex is a little bit of an overkill in this situation. If you just want to remove all the quotes in your string I would use this code:
details = details.replace("\"", "");
If you are using Symfony 2.7 or above, and don't want to include any additional bundle for serializing, maybe you can follow this way to seialize doctrine entities to json -
In my (common, parent) controller, I have a function that prepares the serializer
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
// -----------------------------
/**
* @return Serializer
*/
protected function _getSerializer()
{
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
return new Serializer([$normalizer], [new JsonEncoder()]);
}
Then use it to serialize Entities to JSON
$this->_getSerializer()->normalize($anEntity, 'json');
$this->_getSerializer()->normalize($arrayOfEntities, 'json');
Done!
But you may need some fine tuning. For example -
I know this is a late answer but this works for me:
TimeSpan dateDifference = new TimeSpan(0,0,0, (int)endTime.Subtract(beginTime).TotalSeconds);
dateDifference should now exclude the parts smaller than a second. Works in .net 2.0 too.
Depending on the need for performance and amount of elements to be added, this might be an ok solution. If the amount of elements are high, the Arraylist
s reallocation of memory might be a bit slower than StringBuilder
.
I was same problem, but for me the problem was ng build command. I was doing "ng build --prod" i have corrected it to "ng build --prod --base-href /applicationname/". and this solved my problem.
I had a similar error. I fixed it by just switching the directory. Cloning my project again from my git repository, importing it into android studio and building it. Seems like one of the directories/files generated by Android Studio when building your project may have gotten corrupted. Deleting all Android Studio generated files in your project or doing what I did could solve the problem. Hope this helps.
there is some change since the 0.16 so here how i did,
import in the pubspec.yaml
dependencies:
flutter:
sdk: flutter
intl: ^0.16.1
then use
txdate= DateTime.now()
DateFormat.yMMMd().format(txdate)
I know this was added in release 1.5 but the new enum type is a great feature. Not having to use the old "int enum pattern" has greatly helped a bunch of my code. Check out JLS 8.9 for the sweet gravy on your potatoes!
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday]; $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps
And you can use it for error handling and debugging, like this:
try{
somefunction();
}
catch(error){
if (error instanceof TypeError) {
// Handle type Error
} else if (error instanceof ReferenceError) {
// Handle ReferenceError
} else {
// Handle all other error types
}
}
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
I used
String encodedUrl = new URI(null, url, null).toASCIIString();
to encode urls.
To add parameters after the existing ones in the url
I use UriComponentsBuilder
You can adjust the pane title by setting the pane border in the tmux.conf for example like this:
###############
# pane border #
###############
set -g pane-border-status bottom
#colors for pane borders
setw -g pane-border-style fg=green,bg=black
setw -g pane-active-border-style fg=colour118,bg=black
setw -g automatic-rename off
setw -g pane-border-format ' #{pane_index} #{pane_title} : #{pane_current_path} '
# active pane normal, other shaded out?
setw -g window-style fg=colour28,bg=colour16
setw -g window-active-style fg=colour46,bg=colour16
Where pane_index, pane_title and pane_current_path are variables provided by tmux itself.
After reloading the config or starting a new tmux session, you can then set the title of the current pane like this:
tmux select-pane -T "fancy pane title";
#or
tmux select-pane -t paneIndexInteger -T "fancy pane title";
If all panes have some processes running, so you can't use the command line, you can also type the commands after pressing the prefix bind (C-b by default) and a colon (:) without having "tmux" in the front of the command:
select-pane -T "fancy pane title"
#or:
select-pane -t paneIndexInteger -T "fancy pane title"
The C++ string class is std::string
. To use it you need to include the <string>
header.
For the fundamentals of how to use std::string
, you'll want to consult a good introductory C++ book.
You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);
prints
f= 111111.12
d= 111111.1111
Following @Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.
Stored procedure is the best way to do it. Because Meherzad's solution would work only if the data follows the same order.
If we have a table structure like this
col1 | col2 | col3
-----+------+------
3 | k | 7
5 | d | 3
1 | a | 5
6 | o | 2
2 | 0 | 8
It wont work. SQL Fiddle Demo
Here is a sample procedure code to achieve the same.
delimiter //
CREATE PROCEDURE chainReaction
(
in inputNo int
)
BEGIN
declare final_id int default NULL;
SELECT col3
INTO final_id
FROM table1
WHERE col1 = inputNo;
IF( final_id is not null) THEN
INSERT INTO results(SELECT col1, col2, col3 FROM table1 WHERE col1 = inputNo);
CALL chainReaction(final_id);
end if;
END//
delimiter ;
call chainReaction(1);
SELECT * FROM results;
DROP TABLE if exists results;
On windows, you must set a variable to specify proxy settings, download the vagrant-proxyconf plugin: (replace {PROXY_SCHEME}(http:// or https://), {PROXY_IP} and {PROXY_PORT} by the right values)
set http_proxy={PROXY_SCHEME}{PROXY_IP}:{PROXY_PORT}
set https_proxy={PROXY_SCHEME}{PROXY_IP}:{PROXY_PORT}
After that, you can add the plugin to hardcode your proxy settings in the vagrant file
vagrant plugin install vagrant-proxyconf --plugin-source http://rubygems.org
and then you can provide config.proxy.xxx settings in your Vagrantfile to be independent against environment settings variables
Here's the code with parameter labels
def draw_text(self, frame, text, x, y, color=BGR_COMMON['green'], thickness=1.3, size=0.3,):
if x is not None and y is not None:
cv2.putText(
frame, text, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, size, color, thickness)
For font name please see another answer in this thread.
Excerpt from answer by @Roeffus
This is indeed a bit of an annoying problem. For python 2.x.x you use:
cv2.CV_FONT_HERSHEY_SIMPLEX and for Python 3.x.x:
cv2.FONT_HERSHEY_SIMPLEX
For more see this http://www.programcreek.com/python/example/83399/cv2.putText
As of 2019 there is a subcommand: vagrant box repackage
vagrant box repackage --help
Usage: vagrant box repackage <name> <provider> <version>
-h, --help Print this help
You can find name
provider
and version
by running vagrant box list
vagrant box list
macinbox (virtualbox, 10.14.5)
The ouput of vagrant box repackage
is a file called package.box
which is basically a tgz file which the content can be listed as below:
tar tzf package.box
./metadata.json
./box.ovf
./Vagrantfile
./box-disk001.vmdk
As a few people have mentioned, the parameters in paramMap
should be accessed using the common Map
API:
To get a snapshot of the params, when you don't care that they may change:
this.bankName = this.route.snapshot.paramMap.get('bank');
To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)
this.route.paramMap.subscribe( paramMap => {
this.bankName = paramMap.get('bank');
})
Since Angular 4, params
have been deprecated in favor of the new interface paramMap
. The code for the problem above should work if you simply substitute one for the other.
If you inject ActivatedRoute
in your component, you'll be able to extract the route parameters
import {ActivatedRoute} from '@angular/router';
...
constructor(private route:ActivatedRoute){}
bankName:string;
ngOnInit(){
// 'bank' is the name of the route parameter
this.bankName = this.route.snapshot.params['bank'];
}
If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:
ngOnInit(){
this.route.params.subscribe( params =>
this.bankName = params['bank'];
)
}
For the docs, including the differences between the two check out this link and search for "activatedroute"
My cacerts file was totally empty. I solved this by copying the cacerts file off my windows machine (that's using Oracle Java 7) and scp'd it to my Linux box (OpenJDK).
cd %JAVA_HOME%/jre/lib/security/
scp cacerts mylinuxmachin:/tmp
and then on the linux machine
cp /tmp/cacerts /etc/ssl/certs/java/cacerts
It's worked great so far.
Starting with C# 6.0, We can assign default value to auto-implemented properties.
public string Name { get; set; } = "Some Name";
We can also create read-only auto implemented property like:
public string Name { get; } = "Some Name";
See: C# 6: First reactions , Initializers for automatically implemented properties - By Jon Skeet
When I needed to do this, I followed Microsoft's example using Binding.ValidationRules and it worked first time.
See their article, How to: Implement Binding Validation: https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-binding-validation?view=netframeworkdesktop-4.8
You don't need to use a type assertion, instead just use the %v
format specifier with Sprintf
:
hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])
In traditional recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don't get the result of your calculation until you have returned from every recursive call.
In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params))
. Basically, the return value of any given recursive step is the same as the return value of the next recursive call.
The consequence of this is that once you are ready to perform your next recursive step, you don't need the current stack frame any more. This allows for some optimization. In fact, with an appropriately written compiler, you should never have a stack overflow snicker with a tail recursive call. Simply reuse the current stack frame for the next recursive step. I'm pretty sure Lisp does this.
Yes you can change it. if you call VBscript function within Javascript.
Here is simple example
<script>
function alert_confirm(){
customMsgBox("This is my title","how are you?",64,0,0,0);
}
</script>
<script language="VBScript">
Function customMsgBox(tit,mess,icon,buts,defs,mode)
butVal = icon + buts + defs + mode
customMsgBox= MsgBox(mess,butVal,tit)
End Function
</script>
<html>
<body>
<a href="javascript:alert_confirm()">Alert</a>
</body>
</html>
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
To add a comment under any code on NOTEPAD++ first we have to save and define the programming or scripting file type. Like, save the file as xml, html etc. Once the file is saved in proper format you will be able to add a comment directly using the shortcut ctrl+Q
var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]
use the following
select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10),GETDATE(),111)
or the following
select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10), GETDATE(), 120)
If you only need to modify the page num you can replace it:
var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
You can use:
str.replace(/text/g, "replaced text");
It is not possible yet to search for content using multiple tags, for now only single tags are supported.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:
https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey
Also note that the username is not the user-id. You can look up user-Id`s here.
A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.
Start by Comparing the distance between latitudes. Each degree of latitude is approximately 69 miles (111 kilometers) apart. The range varies (due to the earth's slightly ellipsoid shape) from 68.703 miles (110.567 km) at the equator to 69.407 (111.699 km) at the poles. The distance between two locations will be equal or larger than the distance between their latitudes.
Note that this is not true for longitudes - the length of each degree of longitude is dependent on the latitude. However, if your data is bounded to some area (a single country for example) - you can calculate a minimal and maximal bounds for the longitudes as well.
Continue will a low-accuracy, fast distance calculation that assumes spherical earth:
The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:
d = acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))
A mathematically equivalent formula, which is less subject to rounding error for short distances is:
d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
d is the distance in radians
distance_km ˜ radius_km * distance_radians ˜ 6371 * d
(6371 km is the average radius of the earth)
This method computational requirements are mimimal. However the result is very accurate for small distances.
Then, if it is in a given distance, more or less, use a more accurate method.
GeographicLib is the most accurate implementation I know, though Vincenty inverse formula may be used as well.
If you are using an RDBMS, set the latitude as the primary key and the longitude as a secondary key. Query for a latitude range, or for a latitude/longitude range, as described above, then calculate the exact distances for the result set.
Note that modern versions of all major RDBMSs support geographical data-types and queries natively.
set global sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
I had to rescale the bitmap a bit to not exceed the 1mb limit of the transaction binder. You can adapt the 400 the your screen or make it dinamic it's just meant to be an example. It works fine and the quality is nice. Its also a lot faster then saving the image and loading it after but you have the size limitation.
public void loadNextActivity(){
Intent confirmBMP = new Intent(this,ConfirmBMPActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp = returnScaledBMP();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
confirmBMP.putExtra("Bitmap",bmp);
startActivity(confirmBMP);
finish();
}
public Bitmap returnScaledBMP(){
Bitmap bmp=null;
bmp = tempBitmap;
bmp = createScaledBitmapKeepingAspectRatio(bmp,400);
return bmp;
}
After you recover the bmp in your nextActivity with the following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmBMP);
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("Bitmap");
}
I hope my answer was somehow helpfull. Greetings
Are you sure your web service is deployed correctly to the enviornment that is NOT working. Looks like the type is out of date.
Also see PEP 263 if you are using a non-ascii characterset
Abstract
This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.
Problem
In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.
Proposed Solution
I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.
To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given.
To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:
# coding=<encoding name>
or (using formats recognized by popular editors)
#!/usr/bin/python # -*- coding: <encoding name> -*-
or
#!/usr/bin/python # vim: set fileencoding=<encoding name> :
...
Another possibility would be grouping, similar to how you might approach it in raw SQL:
from y in context.MyTable
group y.MyCounter by y.MyField into GrpByMyField
where GrpByMyField.Key == value
select GrpByMyField.Max()
The only thing is (testing again in LINQPad) switching to the VB LINQ flavor gives syntax errors on the grouping clause. I'm sure the conceptual equivalent is easy enough to find, I just don't know how to reflect it in VB.
The generated SQL would be something along the lines of:
SELECT [t1].[MaxValue]
FROM (
SELECT MAX([t0].[MyCounter) AS [MaxValue], [t0].[MyField]
FROM [MyTable] AS [t0]
GROUP BY [t0].[MyField]
) AS [t1]
WHERE [t1].[MyField] = @p0
The nested SELECT looks icky, like the query execution would retrieve all rows then select the matching one from the retrieved set... the question is whether or not SQL Server optimizes the query into something comparable to applying the where clause to the inner SELECT. I'm looking into that now...
I'm not well-versed in interpreting execution plans in SQL Server, but it looks like when the WHERE clause is on the outer SELECT, the number of actual rows resulting in that step is all rows in the table, versus only the matching rows when the WHERE clause is on the inner SELECT. That said, it looks like only 1% cost is shifted to the following step when all rows are considered, and either way only one row ever comes back from the SQL Server so maybe it's not that big of a difference in the grand scheme of things.
You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html
Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.
For interpolated strings:
$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"
There's now a full-fledged plugin for that:
I encountered this problem on Mac OS X 10.7.5 and Mercurial 2.6.2 when trying to push. After upgrading to Mercurial 3.2.1, I got "no changes found" instead of "waiting for lock on repository". I found out that somehow the default path had gotten set to point to the same repository, so it's not too surprising that Mercurial would get confused.
This is easier and gives purpose to the never used unordered/ordered list tags.
In your CSS add:
li{float: left;} //Sets float left property globally for all li tags.
Then add in your HTML:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Now watch it all line up perfectly! No more arguing over tables vs divs!
The official tutorial may be of some use to you.
Class | Package | Subclass (same pkg) |
Subclass (diff pkg) |
World | |
---|---|---|---|---|---|
public |
+ | + | + | + | + |
protected |
+ | + | + | + | |
no modifier | + | + | + | ||
private |
+ |
+ : accessible
blank : not accessible
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
Using query-string module is the recommended one when you need a module to parse your query string in ease.
componentWillMount() {
var query = queryString.parse(this.props.location.search);
if (query.token) {
window.localStorage.setItem("jwt", query.token);
store.dispatch(push("/"));
}
}
Here, I am redirecting back to my client from Node.js server after successful Google-Passport authentication, which is redirecting back with token as query param.
I am parsing it with query-string module, saving it and updating the query params in the url with push from react-router-redux.
I have noticed that no answer display an image with a single legend referencing many curves in different subplots, so I have to show you one... to make you curious...
Now, you want to look at the code, don't you?
from numpy import linspace
import matplotlib.pyplot as plt
# Calling the axes.prop_cycle returns an itertoools.cycle
color_cycle = plt.rcParams['axes.prop_cycle']()
# I need some curves to plot
x = linspace(0, 1, 51)
f1 = x*(1-x) ; lab1 = 'x - x x'
f2 = 0.25-f1 ; lab2 = '1/4 - x + x x'
f3 = x*x*(1-x) ; lab3 = 'x x - x x x'
f4 = 0.25-f3 ; lab4 = '1/4 - x x + x x x'
# let's plot our curves (note the use of color cycle, otherwise the curves colors in
# the two subplots will be repeated and a single legend becomes difficult to read)
fig, (a13, a24) = plt.subplots(2)
a13.plot(x, f1, label=lab1, **next(color_cycle))
a13.plot(x, f3, label=lab3, **next(color_cycle))
a24.plot(x, f2, label=lab2, **next(color_cycle))
a24.plot(x, f4, label=lab4, **next(color_cycle))
# so far so good, now the trick
lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]
# finally we invoke the legend (that you probably would like to customize...)
fig.legend(lines, labels)
plt.show()
The two lines
lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]
lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]
deserve an explanation — to this aim I have encapsulated the tricky part in a function, just 4 lines of code but heavily commented
def fig_legend(fig, **kwdargs):
# generate a sequence of tuples, each contains
# - a list of handles (lohand) and
# - a list of labels (lolbl)
tuples_lohand_lolbl = (ax.get_legend_handles_labels() for ax in fig.axes)
# e.g. a figure with two axes, ax0 with two curves, ax1 with one curve
# yields: ([ax0h0, ax0h1], [ax0l0, ax0l1]) and ([ax1h0], [ax1l0])
# legend needs a list of handles and a list of labels,
# so our first step is to transpose our data,
# generating two tuples of lists of homogeneous stuff(tolohs), i.e
# we yield ([ax0h0, ax0h1], [ax1h0]) and ([ax0l0, ax0l1], [ax1l0])
tolohs = zip(*tuples_lohand_lolbl)
# finally we need to concatenate the individual lists in the two
# lists of lists: [ax0h0, ax0h1, ax1h0] and [ax0l0, ax0l1, ax1l0]
# a possible solution is to sum the sublists - we use unpacking
handles, labels = (sum(list_of_lists, []) for list_of_lists in tolohs)
# call fig.legend with the keyword arguments, return the legend object
return fig.legend(handles, labels, **kwdargs)
PS I recognize that sum(list_of_lists, [])
is a really inefficient method to flatten a list of lists but ? I love its compactness, ? usually is a few curves in a few subplots and ? Matplotlib and efficiency? ;-)
If you want to stick with the official Matplotlib API my answer above is perfect, really.
On the other hand, if you don't mind using a private method of the matplotlib.legend
module ... it's really much much much easier
from matplotlib.legend import _get_legend_handles_labels
...
fig.legend(*_get_legend_handles_and_labels(fig.axes), ...)
A complete explanation can be found in the source code of Axes.get_legend_handles_labels
in .../matplotlib/axes/_axes.py
You can do an interactive rebase:
git rebase -i <commit>
This will bring up your default editor. Just delete the line containing the commit you want to remove to delete that commit.
You will, of course, need access to the remote repository to apply this change there too.
See this question: Git: removing selected commits from repository
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
you could use exists
with a filter:
Content.objects.filter(name="baby").exists()
#returns False or True depending on if there is anything in the QS
just an alternative for if you only want to know if it exists
pip
is designed to upgrade python packages and not to upgrade python itself. pip
shouldn't try to upgrade python when you ask it to do so.
Don't type pip install python
but use an installer instead.
An example,
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
cor(d) # get correlations (returns matrix)
I'd suggest the following to see the difference "in commits". For symmetric difference, repeat the command with inverted args:
git cherry -v master [your branch, or HEAD as default]
By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.
Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.
You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.
To get Current timezone of the mysql you can do following things:
SELECT @@system_time_zone; # from this you can get the system timezone
SELECT IF(@@session.time_zone = 'SYSTEM', @@system_time_zone, @@session.time_zone) # This will give you time zone if system timezone is different from global timezone
Now if you want to change the mysql timezone then:
SET GLOBAL time_zone = '+00:00'; # this will set mysql timezone in UTC
SET @@session.time_zone = "+00:00"; # by this you can chnage the timezone only for your particular session
you can try this without any java script you can do that just by using CSS
img:active,
img:focus,
img:hover{
border: 10px solid red !important
}
of if your case is to add any other css class by clicking you can use query selector like
<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
in controller first search for any image with red border and remove it then by passing the image id add the border class to that image
$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
Remove:
httpRequest.setRequestHeader( 'Access-Control-Allow-Origin', '*');
... and add:
httpRequest.withCredentials = false;
In my case it works only with two line of code. Test the below C# code:
String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";
byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);
That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
This is super old, but hopefully this helps somebody. I'm sending responses with different error codes back and this is the only solution I've found that works in
$.ajax({
data: {
"data": "mydata"
},
type: "POST",
url: "myurl"
}).done(function(data){
alert(data);
}).fail(function(data){
alert(data.responseText)
});
Since JQuery deprecated the success
and error
functions, it's you need to use done
and fail
, and access the data with data.responseText
when in fail
, and just with data
when in done
. This is similar to @Marco Pavan 's answer, but you don't need any JQuery plugins or anything to use it.
Your example creates multiple key: value pairs if using fromkeys
. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.
>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
C++17 (N4659
) includes a proposal Refining Expression Evaluation Order for Idiomatic C++
which defines a stricter order of expression evaluation.
In particular, the following sentence
8.18 Assignment and compound assignment operators:
....In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.
together with the following clarification
An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
make several cases of previously undefined behavior valid, including the one in question:
a[++i] = i;
However several other similar cases still lead to undefined behavior.
In N4140
:
i = i++ + 1; // the behavior is undefined
But in N4659
i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined
Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.
You need to make sure images come first and put in a comma after the background image call. then it actually does work:
background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */
By publishing your whole node_modules
folder you are deploying far more files than you will actually need in production.
Instead, use a task runner as part of your build process to package up those files you require, and deploy them to your wwwroot
folder. This will also allow you to concat and minify your assets at the same time, rather than having to serve each individual library separately.
You can then also completely remove the FileServer
configuration and rely on UseStaticFiles
instead.
Currently, gulp is the VS task runner of choice. Add a gulpfile.js
to the root of your project, and configure it to process your static files on publish.
For example, you can add the following scripts
section to your project.json
:
"scripts": {
"prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
},
Which would work with the following gulpfile (the default when scaffolding with yo
):
/// <binding Clean='clean'/>
"use strict";
var gulp = require("gulp"),
rimraf = require("rimraf"),
concat = require("gulp-concat"),
cssmin = require("gulp-cssmin"),
uglify = require("gulp-uglify");
var webroot = "./wwwroot/";
var paths = {
js: webroot + "js/**/*.js",
minJs: webroot + "js/**/*.min.js",
css: webroot + "css/**/*.css",
minCss: webroot + "css/**/*.min.css",
concatJsDest: webroot + "js/site.min.js",
concatCssDest: webroot + "css/site.min.css"
};
gulp.task("clean:js", function (cb) {
rimraf(paths.concatJsDest, cb);
});
gulp.task("clean:css", function (cb) {
rimraf(paths.concatCssDest, cb);
});
gulp.task("clean", ["clean:js", "clean:css"]);
gulp.task("min:js", function () {
return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
.pipe(concat(paths.concatJsDest))
.pipe(uglify())
.pipe(gulp.dest("."));
});
gulp.task("min:css", function () {
return gulp.src([paths.css, "!" + paths.minCss])
.pipe(concat(paths.concatCssDest))
.pipe(cssmin())
.pipe(gulp.dest("."));
});
gulp.task("min", ["min:js", "min:css"]);
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
proc_label:BEGIN
IF tablename IS NULL THEN
LEAVE proc_label;
END IF;
#proceed the code
END;
Given that you're only converting to int
s to then perform a comparison, I'd just switch the table definition around to using varchar
also:
Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)
and remove all of the attempted CONVERT
s from the rest of the query.
SELECT a.name, a.value AS value, COUNT(*) AS pocet
FROM
(SELECT item.name, value.value
FROM mdl_feedback AS feedback
INNER JOIN mdl_feedback_item AS item
ON feedback.id = item.feedback
INNER JOIN mdl_feedback_value AS value
ON item.id = value.item
WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
) AS a
INNER JOIN #myTempTable
on a.value = #myTempTable.num
GROUP BY a.name, a.value ORDER BY a.name
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
Encapsulation- enforcing access to the internal data in a controlled manner or preventing members from being accessed directly.
Abstraction- Hiding the implementation details of certain methods is known as abstraction
Let's understand with the help of an example:-
class Rectangle
{
private int length;
private int breadth;// see the word private that means they cant be accesed from
outside world.
//now to make them accessed indirectly define getters and setters methods
void setLength(int length)
{
// we are adding this condition to prevent users to make any irrelevent changes
that is why we have made length private so that they should be set according to
certain restrictions
if(length!=0)
{
this.length=length
}
void getLength()
{
return length;
}
// same do for breadth
}
now for abstraction define a method that can only be accessed and user doesnt know what is the body of the method and how it is working Let's consider the above example, we can define a method area which calculates the area of the rectangle.
public int area()
{
return length*breadth;
}
Now, whenever a user uses the above method he will just get the area not the way how it is calculated. We can consider an example of println() method we just know that it is used for printing and we don't know how it prints the data. I have written a blog in detail you can see the below link for more info abstraction vs encapsulation
You don't need to wrap it in a list with [..]
, just provide the subselection of the columns index:
df.drop(df.columns[[1, 69]], axis=1, inplace=True)
as the index object is already regarded as list-like.
function ArrayToObject( arr ) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
var name = arr[i].name;
var value = arr[i].value;
obj[name] = arr[i].value;
}
return obj;
}
var form_data = $('#my_form').serializeArray();
form_data = ArrayToObject( form_data );
form_data.action = event.target.id;
form_data.target = event.target.dataset.event;
console.log( form_data );
$.post("/api/v1/control/", form_data, function( response ){
console.log(response);
}).done(function( response ) {
$('#message_box').html('SUCCESS');
})
.fail(function( ) { $('#message_box').html('FAIL'); })
.always(function( ) { /*$('#message_box').html('SUCCESS');*/ });
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
I faced similar problem. So far I know result may different for different names, so finally came to this solution.
public String getMimeType(String filePath) {
String type = null;
String extension = null;
int i = filePath.lastIndexOf('.');
if (i > 0)
extension = filePath.substring(i+1);
if (extension != null)
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
return type;
}
A great way of handling this is with regular expressions.
string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");
This will replace any of the 3 legal types of newline with the html tag.
This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:
set(CMAKE_CXX_STANDARD 14)
.
Example:
cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)
# Rest of your declarations...
In Visual Studio 2015 and 2017 for C# code.
SSSSSS is microseconds. Let us say the time is 10:30:22 (Seconds 22) and 10:30:22.1 would be 22 seconds and 1/10 of a second . Extending the same logic , 10:32.22.000132 would be 22 seconds and 132/1,000,000 of a second, which is nothing but microseconds.
I came across the same issue while trying to create a cardview programmatically, what is strange is that looking at the doc https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int%29, Google guys made public the api to change the background color of a card view but weirdly i didn't succeed to have access to it in the support library, so here is what worked for me:
CardViewBuilder.java
mBaseLayout = new FrameLayout(context);
// FrameLayout Params
FrameLayout.LayoutParams baseLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mBaseLayout.setLayoutParams(baseLayoutParams);
// Create the card view.
mCardview = new CardView(context);
mCardview.setCardElevation(4f);
mCardview.setRadius(8f);
mCardview.setPreventCornerOverlap(true); // The default value for that attribute is by default TRUE, but i reset it to true to make it clear for you guys
CardView.LayoutParams cardLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
cardLayoutParams.setMargins(12, 0, 12, 0);
mCardview.setLayoutParams(cardLayoutParams);
// Add the card view to the BaseLayout
mBaseLayout.addView(mCardview);
// Create a child view for the cardView that match it's parent size both vertically and horizontally
// Here i create a horizontal linearlayout, you can instantiate the view of your choice
mFilterContainer = new LinearLayout(context);
mFilterContainer.setOrientation(LinearLayout.HORIZONTAL);
mFilterContainer.setPadding(8, 8, 8, 8);
mFilterContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER));
// And here is the magic to get everything working
// I create a background drawable for this view that have the required background color
// and match the rounded radius of the cardview to have it fit in.
mFilterContainer.setBackgroundResource(R.drawable.filter_container_background);
// Add the horizontal linearlayout to the cardview.
mCardview.addView(mFilterContainer);
filter_container_background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="@android:color/white"/>
Doing that i succeed in keeping the cardview shadow and rounded corners.
I know this thread is old, but I think it can be useful for other people. If you are using gcc, you can use its instrument features (-finstrument-functions option) to log any function call (entry and exit). Have a look at this for more information: http://hacktalks.blogspot.fr/2013/08/gcc-instrument-functions.html
You can thus for instance push and pop every calls into a stack, and when you want to print it, you just look at what you have in your stack.
I've tested it, it works perfectly and is very handy
UPDATE: you can also find information about the -finstrument-functions compile option in the GCC doc concerning the Instrumentation options: https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html
simple way to do this... here are the example
cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause
this will mount the ISO image to the specific drive...use
There is jq
for parsing json on the command line:
jq '.Body'
Visit this for jq: https://stedolan.github.io/jq/
public int GetNthIndex(string s, char t, int n)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == t)
{
count++;
if (count == n)
{
return i;
}
}
}
return -1;
}
That could be made a lot cleaner, and there are no checks on the input.
You can also try to set a HostnameVerifier as described here. This worked for me to avoid this error.
// Do not do this in production!!!
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
// Example send http request
final String url = "https://encrypted.google.com/";
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost);
In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?
If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
`-- projectA
|-- branches
|-- tags
`-- trunk
|-- module1
| `-- pom.xml
|-- moduleN
| `-- pom.xml
`-- pom.xml
This makes the checkout a bit painful and a common way to deal with that is to use svn:externals
. For example, add a trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
With the following externals definition:
parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk
A checkout of trunks
would then result in the following local structure (pattern #2):
root/
parent-pom/
pom.xml
projectA/
Optionally, you can even add a pom.xml
in the trunks
directory:
root
|-- parent-pom
| |-- branches
| |-- tags
| `-- trunk
| `-- pom.xml
|-- projectA
| |-- branches
| |-- tags
| `-- trunk
| |-- module1
| | `-- pom.xml
| |-- moduleN
| | `-- pom.xml
| `-- pom.xml
`-- trunks
`-- pom.xml
This pom.xml
is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):
root/
parent-pom/
pom.xml
projectA/
pom.xml
This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.
If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).
Now, about the bonus questions:
- Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).
Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.
- How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?
The setup I use works well, nothing particular to mention.
Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent>
section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.
Lately I have been tending to prefer m_ prefix instead of having no prefix at all, the reasons isn't so much that its important to flag member variables, but that it avoids ambiguity, say you have code like:
void set_foo(int foo) { foo = foo; }
That of cause doesn't work, only one foo
allowed. So your options are:
this->foo = foo;
I don't like it, as it causes parameter shadowing, you no longer can use g++ -Wshadow
warnings, its also longer to type then m_
. You also still run into naming conflicts between variables and functions when you have a int foo;
and a int foo();
.
foo = foo_;
or foo = arg_foo;
Been using that for a while, but it makes the argument lists ugly, documentation shouldn't have do deal with name disambiguity in the implementation. Naming conflicts between variables and functions also exist here.
m_foo = foo;
API Documentation stays clean, you don't get ambiguity between member functions and variables and its shorter to type then this->
. Only disadvantage is that it makes POD structures ugly, but as POD structures don't suffer from the name ambiguity in the first place, one doesn't need to use it with them. Having a unique prefix also makes a few search&replace operations easier.
foo_ = foo;
Most of the advantages of m_
apply, but I reject it for aesthetic reasons, a trailing or leading underscore just makes the variable look incomplete and unbalanced. m_
just looks better. Using m_
is also more extendable, as you can use g_
for globals and s_
for statics.
PS: The reason why you don't see m_
in Python or Ruby is because both languages enforce the their own prefix, Ruby uses @
for member variables and Python requires self.
.
Simple and elegant solution
Just follow these steps. It worked perfectly with npm install running multiple times or installing any other modules or even publishing project to artifactory.
In the same directory where you have package.json create a npm-shrinkwrap.json file with the following contents:
{
"dependencies": {
"graceful-fs": {
"version": "4.2.2"
}
}
}
Run npm install, and don't worry, it'll update npm-shrinkwrap.json with a bunch of content. Let's get rid of this updates by updating package.json scripts options.
"scripts": {
"preshrinkwrap": "git checkout -- npm-shrinkwrap.json",
"postshrinkwrap": "git checkout -- npm-shrinkwrap.json"
}
Now you can run npm install and your npm-shrinkwrap.json will be intact and will work forever.
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
This also works with maven by defining the resources tag. You can name your src folder names whatever you like.
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/generated</directory>
<includes>
<include>**/*.java</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant
directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME
to this directory, then pre-pend to the System PATH
variable, %ANT_HOME%\bin
. This way, you don't have to put in the whole directory name.
Assuming you did the above, try this:
C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build
This will do several things:
build.xml
in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.The -d
will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999
, and run cls
first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.
Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build
target. Here it is:
<target depends="build-subprojects,build-project" name="build"/>
The build
target does nothing itself. However, it depends upon two other targets, so these will be called first:
The first target is build-subprojects
:
<target name="build-subprojects"/>
This does nothing at all. It doesn't even have a dependency.
The next target specified is build-project
does have code:
<target depends="init" name="build-project">
This target does contain tasks, and some dependent targets. Before build-project
executes, it will first run the init
target:
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
This target creates a directory called bin
, then copies all files under the src
tree with the suffix *.java
over to the bin
directory. The includeemptydirs
mean that directories without non-java code will not be created.
Ant uses a scheme to do minimal work. For example, if the bin
directory is created, the <mkdir/>
task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src
directory tree, the <copy/>
task won't run. However, the init
target will still be executed.
Next, we go back to our previous build-project
target:
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
<src path="src"/>
<classpath refid="iControlSilk4J.classpath"/>
</javac>
</target>
Look at this line:
<echo message="${ant.project.name}: ${ant.file}"/>
That should have always executed. Did your output print:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
Maybe you didn't realize that was from your build.
After that, it runs the <javac/>
task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java
files have previously been compiled, the <javac/>
task won't execute.
And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean
task, and then build
:
C:\Silk4J\Automation\iControlSilk4J> ant -d clean build
However, Ant usually prints the target being executed. You should have seen this:
init:
build-subprojects:
build-projects:
[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml
build:
Build Successful
Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.
bin
directory already exists, <mkdir/>
isn't going to execute.src
, or they have already been copied into bin
, the <copy/>
task won't execute.src
directory, or they have already been compiled, the <java/>
task won't run.If you look at the output from the -d
debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.
See if that helps.
This may work:
grant all on dbtest.* to 'dbuser'@'%' identified by 'mysql_password';
If you have 2-Step Verification step up on your Gmail account, you will need to generate an App password. https://support.google.com/accounts/answer/185833?p=app_passwords_sa&hl=en&visit_id=636903322072234863-1319515789&rd=1 Select How to generate an App password option and follow the steps provided. Copy and paste the generated App password somewhere as you will not be able to recover it after you click DONE.
var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);
What do you mean by delete
? In Python, removing a reference (or a name) can be done with the del
keyword, but if there are other names to the same object that object will not be deleted.
--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
compared to:
--> test = 5
--> other is test # check that both name refer to the exact same object
True
--> del test # gets rid of test, but the object is still referenced by other
--> print(other)
5
Improving axiac's solution to avoid selecting multiple rows per group while also allowing for use of indexes
SELECT o.*
FROM `Persons` o
LEFT JOIN `Persons` b
ON o.Group = b.Group AND o.Age < b.Age
LEFT JOIN `Persons` c
ON o.Group = c.Group AND o.Age = c.Age and o.id < c.id
WHERE b.Age is NULL and c.id is null
Mac OS I tried a lot of codes but just this works on me
import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
pygame.mixer.music.play(loops=10, start=0.0)
time.sleep(10)*to protect from closing*
pygame.mixer.music.set_volume(10)
i = i + 1
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
At least write the code without the bushy tree:
#!/bin/bash
PASSED=$1
if [ -d "${PASSED}" ]
then echo "${PASSED} is a directory";
elif [ -f "${PASSED}" ]
then echo "${PASSED} is a file";
else echo "${PASSED} is not valid";
exit 1
fi
When I put that into a file "xx.sh" and create a file "xx sh", and run it, I get:
$ cp /dev/null "xx sh"
$ for file in . xx*; do sh "$file"; done
. is a directory
xx sh is a file
xx.sh is a file
$
Given that you are having problems, you should debug the script by adding:
ls -l "${PASSED}"
This will show you what ls
thinks about the names you pass the script.
This deeply copies arrays, objects, null and other scalar values, and also deeply copies any properties on non-native functions (which is pretty uncommon but possible). (For efficiency, we do not attempt to copy non-numeric properties on arrays.)
function deepClone (item) {
if (Array.isArray(item)) {
var newArr = [];
for (var i = item.length; i-- > 0;) {
newArr[i] = deepClone(item[i]);
}
return newArr;
}
if (typeof item === 'function' && !(/\(\) \{ \[native/).test(item.toString())) {
var obj;
eval('obj = '+ item.toString());
for (var k in item) {
obj[k] = deepClone(item[k]);
}
return obj;
}
if (item && typeof item === 'object') {
var obj = {};
for (var k in item) {
obj[k] = deepClone(item[k]);
}
return obj;
}
return item;
}
This is what solved my problem. ^M is a carriage return, and it can be easily avoided in a Perl script.
while(<INPUTFILE>)
{
chomp;
chop($_) if ($_ =~ m/\r$/);
}
To verify at server side using PHP. Two most important thing you need to consider.
1. $_POST['g-recaptcha-response']
2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';
$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
$response= json_decode($verifydata);
If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration
Change the project interpreter to ~/anaconda2/python/bin
by going to File -> Settings -> Project -> Project Interpreter
. Also update the run configuration to use the project default Python interpreter via Run -> Edit Configurations
. This makes PyCharm
use Anaconda
instead of the default Python interpreter under usr/bin/python27
.
Two options:
Use the LIKE
keyword, along with percent signs in the string
select * from table where field like '%a%' or field like '%b%'.
(note: If your search string contains percent signs, you'll need to escape them)
If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):
See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Of these, using LIKE
is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.
Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.
If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE
.
After 2 hours of searching it seems google still overrides the yellow color somehow but i for the fix for it. That's right. it will work for hover, focus etc as well. all you have to do is add !important to it.
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
-webkit-box-shadow: 0 0 0px 1000px white inset !important;
}
this will completely remove yellow from input fields
You can use the Series.to_list
method.
For example:
import pandas as pd
df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})
print(df['a'].to_list())
Output:
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
To drop duplicates you can do one of the following:
>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]
Yes it is possible as long as you don't set the position (top
or left
, etc.) of your fixed
element (you can still use margin
to set a relative position, though). Simon Bos posted about this a while ago.
However don't expect fixed element to scroll with non-fixed relatives.
See a demo here.
QTcreator obeys your kde-wide configurations. If you choose "obsidian-coast" as the system-wide color scheme qt creator will be all dark as well. I know it is a partial solution but it works.
If you happen to be using Windows 8 and up, here's how to get to it:
The newer Microsoft SQL Server Configuration Manager is a snap-in for the Microsoft Management Console program.
It is not a stand-alone program as used in the previous versions of Microsoft Windows operating systems.
SQL Server Configuration Manager doesn’t appear as an application when running Windows 8.
To open SQL Server Configuration Manager, in the Search charm, under Apps, type:
SQLServerManager15.msc
for [SQL Server 2019] or
SQLServerManager14.msc
for [SQL Server 2017] or
SQLServerManager13.msc
for [SQL Server 2016] or
SQLServerManager12.msc
for [SQL Server 2014] or
SQLServerManager11.msc
for [SQL Server 2012] or
SQLServerManager10.msc
for [SQL Server 2008], and then press Enter.
Text kindly reproduced from SQL Server Configuration Manager changes in Windows 8
Detailed info from MSDN: SQL Server Configuration Manager
That's a very complex question for a simple answer.
You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.
Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.
At the very top level I think quality REST API docs require at least the following:
Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.
Not with a regular statement, no.
What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.
After searching for hours i found it . just Change the password to something contains Upper case numeric and special characters in it.
I like to stay away from the marshaller.
Using CString newString(originalString);
Seems much cleaner and faster to me. No need to worry about creating and deleting a context.
There doesn't appear to be a way. You can fake it by using justify and then wrapping the last line of text in a span and setting just that to text align center. It works ok for small blocks of text but is not a useful approach to large quantities of text or dynamic text.
I suggest finding somebody at Adobe who's involved in their W3C work and nagging them to bring up right/left/center justification in their next meeting. If anyone's gonna be able to push for basic typography features in CSS it'd be Adobe.
Just want to add since it might be of interest to someone, that you may think about the problem the other way as well. I am not sure if that is of interest here, but I find it relevant.
What I mean by the other way is to say "strip anything that aren't what I am looking for, i.e. if you only want the 'ding' you could say:
var strippedText = ("1 ding ?").replace(/[^a-zA-Z]/g, '');
Which basically mean "remove anything which is nog a,b,c,d....Z (any letter).
What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm
-vs-fcgi
but more to the implementation of your httpd
).
For example, I had a quad-core machine running lighttpd
+ fcgi
humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd
every 30 minutes to keep the website up.
I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.
Is this due to php-fpm
being better than fcgi
? Not entirely, but how you hook into php-fpm
seems to be a whole heckuva lot more efficient than how you serve via fcgi
.
Perhaps a better way of handling errors in MVC is to apply the HandleError attribute to your controller or action and update the Shared/Error.aspx file to do what you want. The Model object on that page includes an Exception property as well as ControllerName and ActionName.
No need to initial value
! Because if no initial value
is passed, the callback function
is not invoked on the first element of the list, and the first element is instead passed as the initial value
. Very cOOl feature :)
[1, 2, 3, 4].reduce((a, x) => a + x) // 10
[1, 2, 3, 4].reduce((a, x) => a * x) // 24
[1, 2, 3, 4].reduce((a, x) => Math.max(a, x)) // 4
[1, 2, 3, 4].reduce((a, x) => Math.min(a, x)) // 1
here's a function i'm using to decide whether to show an "the app updated" page or not. It returns the build number, which i'm converting to an Int:
if let version: String = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
guard let intVersion = Int(version) else { return }
if UserDefaults.standard.integer(forKey: "lastVersion") < intVersion {
print("need to show popup")
} else {
print("Don't need to show popup")
}
UserDefaults.standard.set(intVersion, forKey: "lastVersion")
}
If never used before it will return 0 which is lower than the current build number. To not show such a screen to new users, just add the build number after the first login or when the on-boarding is complete.
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
Use the Apache XMLSerializer
here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '')
is faster.
see http://jsperf.com/cast-to-string/8
note - there are significant differences across browsers at this time.
Just remember that .equals(...)
has to be implemented by the class you are trying to compare. Otherwise, there isn't much of a point; the version of the method for the Object class does the same thing as the comparison operation: Object#equals.
The only time you really want to use the comparison operator for objects is wen you are comparing Enums. This is because there is only one instance of an Enum value at a time. For instance, given the enum
enum FooEnum {A, B, C}
You will never have more than one instance of A
at a time, and the same for B
and C
. This means that you can actually write a method like so:
public boolean compareFoos(FooEnum x, FooEnum y)
{
return (x == y);
}
And you will have no problems whatsoever.
Even if you don't control the server, you can still see the error messages by adding the following line to the Web.config file in your project (bewlow <system.web>
):
<customErrors mode="off" />
With the advent of the CSS Flexible Box, many of web designers' nightmares1 have been resolved. One of the most hacky ones, the vertical alignment. Now it is possible even in unknown heights.
"Two decades of layout hacks are coming to an end. Maybe not tomorrow, but soon, and for the rest of our lives."
— CSS Legendary Eric Meyer at W3Conf 2013
Flexible Box (or in short, Flexbox), is a new layout system that is specifically designed for layout purposes. The specification states:
Flex layout is superficially similar to block layout. It lacks many of the more complex text- or document-centric properties that can be used in block layout, such as floats and columns. In return it gains simple and powerful tools for distributing space and aligning content in ways that webapps and complex web pages often need.
How can it help in this case? Well, let's see.
Using Twitter Bootstrap we have .row
s having some .col-*
s. All we need to do is to display the desired .row
2 as a flex container box and then align all its flex items (the columns) vertically by align-items
property.
EXAMPLE HERE (Please read the comments with care)
<div class="container">
<div class="row vertical-align"> <!--
^-- Additional class -->
<div class="col-xs-6"> ... </div>
<div class="col-xs-6"> ... </div>
</div>
</div>
.vertical-align {
display: flex;
align-items: center;
}
Colored area displays the padding-box of columns.
align-items: center
8.3 Cross-axis Alignment: the
align-items
propertyFlex items can be aligned in the cross axis of the current line of the flex container, similar to
justify-content
but in the perpendicular direction.align-items
sets the default alignment for all of the flex container’s items, including anonymous flex items.
align-items: center;
By center value, the flex item’s margin box is centered in the cross axis within the line.
Important note #1: Twitter Bootstrap doesn't specify the width
of columns in extra small devices unless you give one of .col-xs-#
classes to the columns.
Therefore in this particular demo, I have used .col-xs-*
classes in order for columns to be displayed properly in mobile mode, because it specifies the width
of the column explicitly.
But alternatively you could switch off the Flexbox layout simply by changing display: flex;
to display: block;
in specific screen sizes. For instance:
/* Extra small devices (767px and down) */
@media (max-width: 767px) {
.row.vertical-align {
display: block; /* Turn off the flexible box layout */
}
}
Or you could specify .vertical-align
only on specific screen sizes like so:
/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {
.row.vertical-align {
display: flex;
align-items: center;
}
}
In that case, I'd go with @KevinNelson's approach.
Important note #2: Vendor prefixes omitted due to brevity. Flexbox syntax has been changed during the time. The new written syntax won't work on older versions of web browsers (but not that old as Internet Explorer 9! Flexbox is supported on Internet Explorer 10 and later).
This means you should also use vendor-prefixed properties like display: -webkit-box
and so on in production mode.
If you click on "Toggle Compiled View" in the Demo, you'll see the prefixed version of CSS declarations (thanks to Autoprefixer).
As you see in the previous demo, columns (the flex items) are no longer as high as their container (the flex container box. i.e. the .row
element).
This is because of using center
value for align-items
property. The default value is stretch
so that the items can fill the entire height of the parent element.
In order to fix that, you can add display: flex;
to the columns as well:
EXAMPLE HERE (Again, mind the comments)
.vertical-align {
display: flex;
flex-direction: row;
}
.vertical-align > [class^="col-"],
.vertical-align > [class*=" col-"] {
display: flex;
align-items: center; /* Align the flex-items vertically */
justify-content: center; /* Optional, to align inner flex-items
horizontally within the column */
}
Colored area displays the padding-box of columns.
Last, but not least, notice that the demos and code snippets here are meant to give you a different idea, to provide a modern approach to achieve the goal. Please mind the "Big Alert" section if you are going to use this approach in real world websites or applications.
For further reading including browser support, these resources would be useful:
1. Vertically align an image inside a div with responsive height
2. It's better to use an additional class in order not to alter Twitter Bootstrap's default .row
.
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;
}
UPDATE: As of Bootstrap 3.0, the input-*
classes described below for setting the width of input elements were removed. Instead use the col-*
classes to set the width of input elements. Examples are provided in the documentation.
In Bootstrap 2.3, you'd use the input classes for setting the width.
<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>?
<textarea class="input-block-level"></textarea>?
Do a find for "Control sizing" for examples in the documentation.
But for height I think you'd still use the rows attribute.
You need to specify it on the methods that can throw the exceptions. You just seperate them with a ',' if it can throw more than 1 type of exception. e.g.
public interface MyInterface {
public MyObject find(int x) throws MyExceptionA,MyExceptionB;
}
In your UITableViewCell
's XIB in Attribute Inspector set value of Selection
to None
.
I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:
We can create a tag for some past commit:
git tag [tag_name] [reference_of_commit]
eg:
git tag v1.0 5fcdb03
The fact is that your maven plugin try to connect to an https remote repository
(e.g https://repo.maven.apache.org/maven2/)
This is a new SSL connectivity for Maven Central was made available in august, 2014 !
So please, can you verify that your settings.xml has the correct configuration.
<settings>
<activeProfiles>
<!--make the profile active all the time -->
<activeProfile>securecentral</activeProfile>
</activeProfiles>
<profiles>
<profile>
<id>securecentral</id>
<!--Override the repository (and pluginRepository) "central" from the
Maven Super POM -->
<repositories>
<repository>
<id>central</id>
<url>http://repo1.maven.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://repo1.maven.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>
You can alternatively use the simple http maven repository like this
<pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
Please let me know if my solution works ;)
J.
I am new to Python. I got the code below working and made it easy to understand:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for str in my_list:
if 'abc' in str:
print(str)
C has 'for' and 'while' keywords. If a foreach statement in a language like C# looks like this ...
foreach (Element element in collection)
{
}
... then the equivalent of this foreach statement in C might be be like:
for (
Element* element = GetFirstElement(&collection);
element != 0;
element = GetNextElement(&collection, element)
)
{
//TODO: do something with this element instance ...
}
You can use the IFNULL
function inside the IF
. This will be a little shorter, and there will be fewer repetitions of the field name.
SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1
FROM tablename
note! there is a difference between e.clientX
& e.clientY
and e.pageX
and e.pageY
try them both out and make sure you are using the proper one. clientX
and clientY
change based on scrolling position
You are tryng to send js array with js object format.
Instead of use
var a = new array();
a['something']=...
try:
var a = new Object();
a.something = ...
If you are using uniform 1.5 then use this simple trick to add or remove attribute of check
Just add value="check" in your checkbox's input field.
Add this code in uniform.js
> function doCheckbox(elem){
> .click(function(){
if ( $(elem+':checked').val() == 'check' ) {
$(elem).attr('checked','checked');
}
else {
$(elem).removeAttr('checked');
}
if you not want to add value="check" in your input box because in some cases you add two checkboxes so use this
if ($(elem).is(':checked')) {
$(elem).attr('checked','checked');
}
else
{
$(elem).removeAttr('checked');
}
If you are using uniform 2.0 then use this simple trick to add or remove attribute of check
in this classUpdateChecked($tag, $el, options) {
function change
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
}
To
if ($el.prop) {
// jQuery 1.6+
$el.prop(c, isChecked);
if (isChecked) {
$el.attr(c, c);
} else {
$el.removeAttr(c);
}
}
One object may contain another as a part of its attribute.
So containment need not be physical. e.g., computer system has a warranty.
I would imagine that this would be covered by CSS Tables, a specification which, while mentioned on the CSS homepage, appears to currently be at a state of "not yet published in any form"
In practical terms, you can't achieve this at present.
I have the same issue with windows10, apache 2.2.25, php 5.2 Im trying to add GD to a working PHP.
how I turn around and change between forward and backward slash, plus trailing or not, I get some variant of ;
PHP Warning: PHP Startup: Unable to load dynamic library 'C:/php\php_gd2.dll' - Det g\xe5r inte att hitta den angivna modulen.\r\n in Unknown on line 0
(swedish translated: 'It is not possible to find the module' )
in this perticular case, the php.ini was: extension_dir = "C:/php"
the dll is put in two places C:\php and C:\php\ext
IS it possible that there is and "error" in the error log entry ? I.e. that the .dll IS found (as a file) but not of the right format, or something like that ??
With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.
You could define a clone function.
I use this one :
function goclone(source) {
if (Object.prototype.toString.call(source) === '[object Array]') {
var clone = [];
for (var i=0; i<source.length; i++) {
clone[i] = goclone(source[i]);
}
return clone;
} else if (typeof(source)=="object") {
var clone = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
clone[prop] = goclone(source[prop]);
}
}
return clone;
} else {
return source;
}
}
var B = goclone(A);
It doesn't copy the prototype, functions, and so on. But you should adapt it (and maybe simplify it) for you own need.
The real problem here is that there is a bug in hibernate where it uses select-list aliases in the where-clause:
http://opensource.atlassian.com/projects/hibernate/browse/HHH-817
Just in case someone lands here looking for answers, go look at the ticket. It took 5 years to fix but in theory it'll be in one of the next releases and then I suspect your issue will go away.
Differences
Use ArrayLists if there is no specific requirement to use Vectors.
Synchronization
If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or simply modifies an element. Structural modification means addition or deletion of element(s) from the list. Setting the value of an existing element is not a structural modification.
Collections.synchronizedList
is normally used at the time of creation of the list to avoid any accidental unsynchronized access to the list.
Data growth
Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Here's another solution. this one uses very simple syntax. The first example of the accepted solution did not work on older versions of Microsoft SQL (i.e 2000)
SELECT age, count(*)
FROM Students
GROUP by age
ORDER BY age
If you want to get key from value, its best to use bidimap (bi-directional maps) , you can get key from value in O(1) time.
But, the drawback with this is you can only use unique keyset and valueset.
There is a data structure called Table in java, which is nothing but map of maps like
Table< A, B , C > == map < A , map < B, C > >
Here you can get map<B,C>
by querying T.row(a);
, and you can also get map<A,C>
by querying T.column(b);
In your special case, insert C as some constant.
So, it like < a1, b1, 1 > < a2, b2 , 1 > , ...
So, if you find via T.row(a1) ---> returns map of --> get keyset this returned map.
If you need to find key value then, T.column(b2) --> returns map of --> get keyset of returned map.
Advantages over the previous case :
Simplest solution would be -
$('.selectpicker').trigger('change');
The default value for client_max_body_size
directive is 1 MiB.
It can be set in http
, server
and location
context — as in the most cases,
this directive in a nested block takes precedence over the same directive in the ancestors blocks.
Excerpt from the ngx_http_core_module documentation:
Syntax: client_max_body_size size; Default: client_max_body_size 1m; Context: http, server, location
Sets the maximum allowed size of the client request body, specified in the “Content-Length” request header field. If the size in a request exceeds the configured value, the 413 (Request Entity Too Large) error is returned to the client. Please be aware that browsers cannot correctly display this error. Setting size to 0 disables checking of client request body size.
Don't forget to reload configuration
by nginx -s reload
or service nginx reload
commands prepending with sudo
(if any).
"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:
<Button Content="Edit"
Command="{Binding EditCommand}"
CommandParameter="{Binding ViewModelItem}" >
And then this in your view model:
private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
get
{
return this._ViewModelItem;
}
set
{
this._ViewModelItem = value;
RaisePropertyChanged(() => this.ViewModelItem);
}
}
public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
... do something here...
}
Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.
Here is a permissively-licensed C library with a variety of different FFT implementations, each of which is in its own self-contained C-file.
You'll find a great tutorial here: bootstrap-3-grid-introduction and answer for your question is <div class="container-fluid"> ... </div>
As of version 1.3 there's a service in module ng: $interval
function countController($scope, $interval){
$scope.countDown = 10;
$interval(function(){console.log($scope.countDown--)},1000,0);
}??
Use with caution:
Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.
Using the same center in the view and subview is the simplest way of doing it. You can do something like this,
UIView *innerView = ....;
innerView.view.center = self.view.center;
[self.view addSubView:innerView];
As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.
var mockFileBrowser = new Mock<FileBrowser>();
instead of
var mockFileBrowser = new Mock<IFileBrowser>();
You need to intent
your current context
to another activity first with startActivity
. After that you can finish
your current activity
from where you redirect.
Intent intent = new Intent(this, FirstActivity.class);// New activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); // Call once you redirect to another activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
- Clears the activity stack. If you don't want to clear the activity stack. PLease don't use that flag then.
You can use .resize()
to get every time the width/height actually changes, like this:
$(window).resize(function() {
//resize just happened, pixels changed
});
You can view a working demo here, it takes the new height/width values and updates them in the page for you to see. Remember the event doesn't really start or end, it just "happens" when a resize occurs...there's nothing to say another one won't happen.
Edit: By comments it seems you want something like a "on-end" event, the solution you found does this, with a few exceptions (you can't distinguish between a mouse-up and a pause in a cross-browser way, the same for an end vs a pause). You can create that event though, to make it a bit cleaner, like this:
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
You could have this is a base file somewhere, whatever you want to do...then you can bind to that new resizeEnd
event you're triggering, like this:
$(window).bind('resizeEnd', function() {
//do something, window hasn't changed size in 500ms
});
It is bounded on the lower end by 2^(n/2)
and on the upper end by 2^n (as noted in other comments). And an interesting fact of that recursive implementation is that it has a tight asymptotic bound of Fib(n) itself. These facts can be summarized:
T(n) = O(2^(n/2)) (lower bound)
T(n) = O(2^n) (upper bound)
T(n) = T(Fib(n)) (tight bound)
The tight bound can be reduced further using its closed form if you like.
If you're looking to do this XCode 5+, I found this is the easiest method:
Install ios-sim:
npm install -g ios-sim
Then simply execute:
ios-sim launch ./mySample.app --devicetypeid com.apple.CoreSimulator.SimDeviceType.iPhone-6
In which you can switch up your device type. Simple, fast, and it actually works.
A little more robust version of what you're attempting:
str = str.replaceAll("(\r\n|\n\r|\r|\n)", "<br />");
Below is the code that read the data from the text file and sends it to the handler for processing and receive the response data from the handler and read it and store the data in the string builder class
//Get the data from text file that needs to be sent.
FileStream fileStream = new FileStream(@"G:\Papertest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
byte[] buffer = new byte[fileStream.Length];
int count = fileStream.Read(buffer, 0, buffer.Length);
//This is a handler would recieve the data and process it and sends back response.
WebRequest myWebRequest = WebRequest.Create(@"http://localhost/Provider/ProcessorHandler.ashx");
myWebRequest.ContentLength = buffer.Length;
myWebRequest.ContentType = "application/octet-stream";
myWebRequest.Method = "POST";
// get the stream object that holds request stream.
Stream stream = myWebRequest.GetRequestStream();
stream.Write(buffer, 0, buffer.Length);
stream.Close();
//Sends a web request and wait for response.
try
{
WebResponse webResponse = myWebRequest.GetResponse();
//get Stream Data from the response
Stream respData = webResponse.GetResponseStream();
//read the response from stream.
StreamReader streamReader = new StreamReader(respData);
string name;
StringBuilder str = new StringBuilder();
while ((name = streamReader.ReadLine()) != null)
{
str.Append(name); // Add to stringbuider when response contains multple lines data
}
}
catch (Exception ex)
{
throw ex;
}
Copy the key to your clipboard.
$ pbcopy < ~/.ssh/id_rsa.pub
# Copies the contents of the id_rsa.pub file to your clipboard
Warning: it's important to copy the key exactly without adding newlines or whitespace. Thankfully the pbcopy command makes it easy to perform this setup perfectly.
and paste it wherever you need.
More details on the process, check: Generating SSH Keys.
I just put them in their own file and export it for node and webpack:
// lodash-cherries.js
module.exports = {
defaults: require('lodash/defaults'),
isNil: require('lodash/isNil'),
isObject: require('lodash/isObject'),
isArray: require('lodash/isArray'),
isFunction: require('lodash/isFunction'),
isInteger: require('lodash/isInteger'),
isBoolean: require('lodash/isBoolean'),
keys: require('lodash/keys'),
set: require('lodash/set'),
get: require('lodash/get'),
}
You can take advantage of the fact that NSUserDefaults
are cleared by uninstallation of an app. For example:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Clear keychain on first run in case of reinstallation
if (![[NSUserDefaults standardUserDefaults] objectForKey:@"FirstRun"]) {
// Delete values from keychain here
[[NSUserDefaults standardUserDefaults] setValue:@"1strun" forKey:@"FirstRun"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
//...Other stuff that usually happens in didFinishLaunching
}
This checks for and sets a "FirstRun" key/value in NSUserDefaults
on the first run of your app if it's not already set. There's a comment where you should put code to delete values from the keychain. Synchronize can be called to make sure the "FirstRun" key/value is immediately persisted in case the user kills the app manually before the system persists it.
You can either use a double backslash each time
string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";
or use the @ symbol
string foo = @"D:\Projects\Some\Kind\Of\Pathproblem\wuhoo.xml";
FYI, you can kill the process in one command sudo fuser -k 3000/tcp
. This can be done for all other ports like 8000, 8080 or 9000 which are commonly used for development.
This works for me
var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });
console.log($(targetOption).val());
Thanks for all the posts.
I still think that Harry's answer is the simplest and completed but if you need something even simpler, then use:
struct AppError {
let message: String
init(message: String) {
self.message = message
}
}
extension AppError: LocalizedError {
var errorDescription: String? { return message }
// var failureReason: String? { get }
// var recoverySuggestion: String? { get }
// var helpAnchor: String? { get }
}
And use or test it like this:
printError(error: AppError(message: "My App Error!!!"))
func print(error: Error) {
print("We have an ERROR: ", error.localizedDescription)
}
Here is a flat design circle button:
.btn {_x000D_
height: 80px;_x000D_
line-height: 80px; _x000D_
width: 80px; _x000D_
font-size: 2em;_x000D_
font-weight: bold;_x000D_
border-radius: 50%;_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
text-align: center;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<div class="btn">+</div>
_x000D_
but the problem is that the +
might not be perfectly centered vertically in all browsers / platforms, because of font differences... see also this question (and its answer): Vertical alignement of span inside a div when the font-size is big
load your url helper when you create a function eg,
visibility function_name () {
$this->load->helper('url');
}
the it will show you errors or a view you loaded.
You could use the Chr(int) function
You want to use str.partition()
:
>>> my_string.partition("world")[2]
" , i'm a beginner "
because this option is faster than the alternatives.
Note that this produces an empty string if the delimiter is missing:
>>> my_string.partition("Monty")[2] # delimiter missing
''
If you want to have the original string, then test if the second value returned from str.partition()
is non-empty:
prefix, success, result = my_string.partition(delimiter)
if not success: result = prefix
You could also use str.split()
with a limit of 1:
>>> my_string.split("world", 1)[-1]
" , i'm a beginner "
>>> my_string.split("Monty", 1)[-1] # delimiter missing
"hello python world , i'm a beginner "
However, this option is slower. For a best-case scenario, str.partition()
is easily about 15% faster compared to str.split()
:
missing first lower upper last
str.partition(...)[2]: [3.745 usec] [0.434 usec] [1.533 usec] <3.543 usec> [4.075 usec]
str.partition(...) and test: 3.793 usec 0.445 usec 1.597 usec 3.208 usec 4.170 usec
str.split(..., 1)[-1]: <3.817 usec> <0.518 usec> <1.632 usec> [3.191 usec] <4.173 usec>
% best vs worst: 1.9% 16.2% 6.1% 9.9% 2.3%
This shows timings per execution with inputs here the delimiter is either missing (worst-case scenario), placed first (best case scenario), or in the lower half, upper half or last position. The fastest time is marked with [...]
and <...>
marks the worst.
The above table is produced by a comprehensive time trial for all three options, produced below. I ran the tests on Python 3.7.4 on a 2017 model 15" Macbook Pro with 2.9 GHz Intel Core i7 and 16 GB ram.
This script generates random sentences with and without the randomly selected delimiter present, and if present, at different positions in the generated sentence, runs the tests in random order with repeats (producing the fairest results accounting for random OS events taking place during testing), and then prints a table of the results:
import random
from itertools import product
from operator import itemgetter
from pathlib import Path
from timeit import Timer
setup = "from __main__ import sentence as s, delimiter as d"
tests = {
"str.partition(...)[2]": "r = s.partition(d)[2]",
"str.partition(...) and test": (
"prefix, success, result = s.partition(d)\n"
"if not success: result = prefix"
),
"str.split(..., 1)[-1]": "r = s.split(d, 1)[-1]",
}
placement = "missing first lower upper last".split()
delimiter_count = 3
wordfile = Path("/usr/dict/words") # Linux
if not wordfile.exists():
# macos
wordfile = Path("/usr/share/dict/words")
words = [w.strip() for w in wordfile.open()]
def gen_sentence(delimiter, where="missing", l=1000):
"""Generate a random sentence of length l
The delimiter is incorporated according to the value of where:
"missing": no delimiter
"first": delimiter is the first word
"lower": delimiter is present in the first half
"upper": delimiter is present in the second half
"last": delimiter is the last word
"""
possible = [w for w in words if delimiter not in w]
sentence = random.choices(possible, k=l)
half = l // 2
if where == "first":
# best case, at the start
sentence[0] = delimiter
elif where == "lower":
# lower half
sentence[random.randrange(1, half)] = delimiter
elif where == "upper":
sentence[random.randrange(half, l)] = delimiter
elif where == "last":
sentence[-1] = delimiter
# else: worst case, no delimiter
return " ".join(sentence)
delimiters = random.choices(words, k=delimiter_count)
timings = {}
sentences = [
# where, delimiter, sentence
(w, d, gen_sentence(d, w)) for d, w in product(delimiters, placement)
]
test_mix = [
# label, test, where, delimiter sentence
(*t, *s) for t, s in product(tests.items(), sentences)
]
random.shuffle(test_mix)
for i, (label, test, where, delimiter, sentence) in enumerate(test_mix, 1):
print(f"\rRunning timed tests, {i:2d}/{len(test_mix)}", end="")
t = Timer(test, setup)
number, _ = t.autorange()
results = t.repeat(5, number)
# best time for this specific random sentence and placement
timings.setdefault(
label, {}
).setdefault(
where, []
).append(min(dt / number for dt in results))
print()
scales = [(1.0, 'sec'), (0.001, 'msec'), (1e-06, 'usec'), (1e-09, 'nsec')]
width = max(map(len, timings))
rows = []
bestrow = dict.fromkeys(placement, (float("inf"), None))
worstrow = dict.fromkeys(placement, (float("-inf"), None))
for row, label in enumerate(tests):
columns = []
worst = float("-inf")
for p in placement:
timing = min(timings[label][p])
if timing < bestrow[p][0]:
bestrow[p] = (timing, row)
if timing > worstrow[p][0]:
worstrow[p] = (timing, row)
worst = max(timing, worst)
columns.append(timing)
scale, unit = next((s, u) for s, u in scales if worst >= s)
rows.append(
[f"{label:>{width}}:", *(f" {c / scale:.3f} {unit} " for c in columns)]
)
colwidth = max(len(c) for r in rows for c in r[1:])
print(' ' * (width + 1), *(p.center(colwidth) for p in placement), sep=" ")
for r, row in enumerate(rows):
for c, p in enumerate(placement, 1):
if bestrow[p][1] == r:
row[c] = f"[{row[c][1:-1]}]"
elif worstrow[p][1] == r:
row[c] = f"<{row[c][1:-1]}>"
print(*row, sep=" ")
percentages = []
for p in placement:
best, worst = bestrow[p][0], worstrow[p][0]
ratio = ((worst - best) / worst)
percentages.append(f"{ratio:{colwidth - 1}.1%} ")
print("% best vs worst:".rjust(width + 1), *percentages, sep=" ")
Actually Java supports 4 methods to parse XML out of the box:
DOM Parser/Builder: The whole XML structure is loaded into memory and you can use the well known DOM methods to work with it. DOM also allows you to write to the document with Xslt transformations. Example:
public static void parse() throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File("test.xml");
Document doc = builder.parse(file);
// Do something with the document here.
}
SAX Parser: Solely to read a XML document. The Sax parser runs through the document and calls callback methods of the user. There are methods for start/end of a document, element and so on. They're defined in org.xml.sax.ContentHandler and there's an empty helper class DefaultHandler.
public static void parse() throws ParserConfigurationException, SAXException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser saxParser = factory.newSAXParser();
File file = new File("test.xml");
saxParser.parse(file, new ElementHandler()); // specify handler
}
StAx Reader/Writer: This works with a datastream oriented interface. The program asks for the next element when it's ready just like a cursor/iterator. You can also create documents with it. Read document:
public static void parse() throws XMLStreamException, IOException {
try (FileInputStream fis = new FileInputStream("test.xml")) {
XMLInputFactory xmlInFact = XMLInputFactory.newInstance();
XMLStreamReader reader = xmlInFact.createXMLStreamReader(fis);
while(reader.hasNext()) {
reader.next(); // do something here
}
}
}
Write document:
public static void parse() throws XMLStreamException, IOException {
try (FileOutputStream fos = new FileOutputStream("test.xml")){
XMLOutputFactory xmlOutFact = XMLOutputFactory.newInstance();
XMLStreamWriter writer = xmlOutFact.createXMLStreamWriter(fos);
writer.writeStartDocument();
writer.writeStartElement("test");
// write stuff
writer.writeEndElement();
}
}
JAXB: The newest implementation to read XML documents: Is part of Java 6 in v2. This allows us to serialize java objects from a document. You read the document with a class that implements a interface to javax.xml.bind.Unmarshaller (you get a class for this from JAXBContext.newInstance). The context has to be initialized with the used classes, but you just have to specify the root classes and don't have to worry about static referenced classes. You use annotations to specify which classes should be elements (@XmlRootElement) and which fields are elements(@XmlElement) or attributes (@XmlAttribute, what a surprise!)
public static void parse() throws JAXBException, IOException {
try (FileInputStream adrFile = new FileInputStream("test")) {
JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
Unmarshaller um = ctx.createUnmarshaller();
RootElementClass rootElement = (RootElementClass) um.unmarshal(adrFile);
}
}
Write document:
public static void parse(RootElementClass out) throws IOException, JAXBException {
try (FileOutputStream adrFile = new FileOutputStream("test.xml")) {
JAXBContext ctx = JAXBContext.newInstance(RootElementClass.class);
Marshaller ma = ctx.createMarshaller();
ma.marshal(out, adrFile);
}
}
Examples shamelessly copied from some old lecture slides ;-)
Edit: About "which API should I use?". Well it depends - not all APIs have the same capabilities as you see, but if you have control over the classes you use to map the XML document JAXB is my personal favorite, really elegant and simple solution (though I haven't used it for really large documents, it could get a bit complex). SAX is pretty easy to use too and just stay away from DOM if you don't have a really good reason to use it - old, clunky API in my opinion. I don't think there are any modern 3rd party libraries that feature anything especially useful that's missing from the STL and the standard libraries have the usual advantages of being extremely well tested, documented and stable.
If you are getting the error as
Fatal error: Call to undefined function mysql_connect()
Kindly login to the cPanel >> Click on Select Php version >> select the extension MYSQL
LocalDate.parse(
"19/05/2009" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" )
)
The other Answers with java.util.Date
, java.sql.Date
, and SimpleDateFormat
are now outdated.
LocalDate
The modern way to do date-time is work with the java.time classes, specifically LocalDate
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter
To parse, or generate, a String representing a date-time value, use the DateTimeFormatter
class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );
Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate
, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.
You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.
DateTimeFormatter f =
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );
Dump to console.
System.out.println( "ld: " + ld + " | output: " + output );
ld: 2009-05-19 | output: mardi 19 mai 2009
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
On Mac, Shift+CMD+F for search and replace. Search for '\n' and replace with Shift+Enter.
Basically you are doing it the right way. However, you should use an instance of the DataContext
for querying (it's not obvious that DataContext
is an instance or the type name from your query):
var result = (from a in new DataContext().Persons
where a.Age > 18
select new Person { Name = a.Name, Age = a.Age }).ToList();
Apparently, the Person
class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:
class PersonInformation {
public string Name {get;set;}
public int Age {get;set;}
}
var result = (from a in new DataContext().Persons
where a.Age > 18
select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();
You can freely swap var
with List<PersonInformation>
here without affecting anything (as this is what the compiler does).
Otherwise, if you are working locally with the query, I suggest considering an anonymous type:
var result = (from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age }).ToList();
Note that in all of these cases, the result
is statically typed (it's type is known at compile time). The latter type is a List
of a compiler generated anonymous class similar to the PersonInformation
class I wrote above. As of C# 3.0, there's no dynamic typing in the language.
If you really want to return a List<Person>
(which might or might not be the best thing to do), you can do this:
var result = from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age };
List<Person> list = result.AsEnumerable()
.Select(o => new Person {
Name = o.Name,
Age = o.Age
}).ToList();
You can merge the above statements too, but I separated them for clarity.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
Try it from
ftp://ip_my_s5:2221/mnt/sdcard/Pictures/Screenshots
which point onto /storage/emulated/0
OMG I Got A Quick File Move Command form CMD
1)Command will move All Files and Sub Folders into another location in 1 second .
check command
C:\user>move "your source path " "your destination path"
Hint : For move all Files and Sub folders
C:\user>move "f:\wamp\www" "f:\wapm_3.2\www\old Projects"
you can see that it's before i try some other code that was not working due to more than 1 files and folder was there. when i try to execute code that is under line by red color then all folder move in 1 second.
now check this image. here Total 6.7GB data moved in 1 second... you can check date of post and move as well as Folder name.
i will soon make a windows app that will do same..
The recommended way to style the Toolbar for a Light.DarkActionBar
clone would be to use Theme.AppCompat.Light.DarkActionbar
as parent/app theme and add the following attributes to the style to hide the default ActionBar:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
Then use the following as your Toolbar:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
For further modifications, you would create styles extending ThemeOverlay.AppCompat.Dark.ActionBar
and ThemeOverlay.AppCompat.Light
replacing the ones within AppBarLayout->android:theme
and Toolbar->app:popupTheme
. Also note that this will pick up your ?attr/colorPrimary
if you have set it in your main style so you might get a different background color.
You will find a good example of this is in the current project template with an Empty Activity
of Android Studio (1.4+).
You have several options:
JS
var json_arr = JSON.stringify(arr);
PHP
$arr = json_decode($_POST['arr']);
Sending an array via FormData
.
JS
// Use <#> or any other delimiter you want
var serial_arr = arr.join("<#>");
PHP
$arr = explode("<#>", $_POST['arr']);
An object technically is a dictionary.
var myMappings = {
mykey1: 'myValue',
mykey2: 'myValue'
};
var myVal = myMappings['myKey1'];
alert(myVal); // myValue
You can even loop through one.
for(var key in myMappings) {
var myVal = myMappings[key];
alert(myVal);
}
There is no reason whatsoever to reinvent the wheel. And of course, assignment goes like:
myMappings['mykey3'] = 'my value';
And ContainsKey:
if (myMappings.hasOwnProperty('myKey3')) {
alert('key already exists!');
}
I suggest you follow this: http://javascriptissexy.com/how-to-learn-javascript-properly/
You can also do using CTE with clause.
WITH maps AS (Select ROW_NUMBER() OVER (ORDER BY Id) AS rownum,*
from maps006 )
SELECT rownum, * FROM maps WHERE rownum >49 and rownum <101
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
With the help of GoogleApiClient's LocationServices API we can get the current location of the user/device in specific time interval. This can be added into a background service which updates the Activity when onLocationChanged callbacks
The background service will keep running as long as the application exists in the memory and sticks to the notification drawer. The service handles the following functionalities,
Service With Location Listener
public class LocationMonitoringService extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
...
...
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest.setInterval(10000); //10 secs
mLocationRequest.setFastestInterval(5000); //5 secs
int priority = LocationRequest.PRIORITY_HIGH_ACCURACY; //by default
//PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, PRIORITY_NO_POWER are the other priority modes
mLocationRequest.setPriority(priority);
mLocationClient.connect();
//Make it stick to the notification panel so it is less prone to get cancelled by the Operating System.
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*
* LOCATION CALLBACKS
*/
@Override
public void onConnected(Bundle dataBundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
Log.d(TAG, "== Error On onConnected() Permission not granted");
//Permission not granted by user so cancel the further execution.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
Log.d(TAG, "Connected to Google API");
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "Connection suspended");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Failed to connect to Google API");
}
//to get the location change
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Location changed");
if (location != null) {
//Do something with the location details,
if (location != null) {
//call your API
callAPI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
}
}
}
}
See Complete Tutorial With source code and explanation in detail >>
By the way, a good tip on quickly selecting color on the newer versions of AS is simply to type #fff and then using the color picker on the side of the code to choose the one you want. Quick and easier than remembering all the color hexadecimals. For example:
android:background="#fff"
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
use below URL and replace myurl with your post url and you will get all the things
http://api.facebook.com/restserver.php?method=links.getStats&urls=myurl
but keep in mind it will give you response in XML format only
Example :
<share_count>1</share_count>
<like_count>8</like_count>
<comment_count>0</comment_count>
<total_count>9</total_count>
<click_count>0</click_count>
<comments_fbid>**************</comments_fbid>
<commentsbox_count>0</commentsbox_count>
You need to return true inside onInterceptTouchEvent()
when you handle click event.
Here I have grouped elements with "|" as a separator
import pandas as pd
df = pd.read_csv('input.csv')
df
Out[1]:
Area Keywords
0 A 1
1 A 2
2 B 5
3 B 5
4 B 4
5 C 6
df.dropna(inplace = True)
df['Area']=df['Area'].apply(lambda x:x.lower().strip())
print df.columns
df_op = df.groupby('Area').agg({"Keywords":lambda x : "|".join(x)})
df_op.to_csv('output.csv')
Out[2]:
df_op
Area Keywords
A [1| 2]
B [5| 5| 4]
C [6]