I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
Very interesting question.
I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.
But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
A couple of things:
(?:
not (:?
If you address the first problem, you won't need groups at all.
*That is, a blank or beginning/end of string.
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
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.
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
You cannot do new T()
due to type erasure. The default constructor can only be
public Navigation() { this("", "", null); }
You can create other constructors to provide default values for trigger and description. You need an concrete object of T
.
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
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.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
You can use Jquery's on method and listen for the scroll
event.
I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:
<ul> {% for page in site.pages %} {% if page.title != 'index' %} <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li> {% endif %} {% endfor %} </ul>
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.)
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -
eventually decided to use CLINT as an answer that was given there by great and smart people
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do
for (var i = myArray.length - 1; i >= 0; i--) { console.log(eval(myArray[i])); };
More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.
var result = {}; for (var i = myArray.length - 1; i >= 0; i--) { result[myArray[i]] = eval(myArray[i]); };
I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via
window['myVarName'] = 'namingCollisionsAreFun';
(per comment)
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
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.
{ "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 folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
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
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
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.
You need to append your variables to the echoed string. For example:
echo 'This is a string '.$PHPvariable.' and this is more string';
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
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
If the error is
Error: Node Sass version 5.0.0 is incompatible with ^4.0.0
Step1: stop the server
Step2: run commands are npm uninstall node-sass
Step3: check node-sass in package.json
if node-sass is available in the file then again run Step2.
Step4: npm install [email protected]
<=== run command
Step5: wait until the command successfully runs.
Step6: start-server using npm start
CASE - 1
We can change in api.php
and in web.php
files like below..
The current way we write syntax
is
Route::get('login', 'LoginController@login');
should be changed to
Route::get('login', [LoginController::class, 'login']);
CASE - 2
After trying and searching different solutions, I think the most safest way is adding the following code at the end of the Podfile
post_install do |pi|
pi.pods_project.targets.each do |t|
t.build_configurations.each do |bc|
bc.build_settings['ARCHS[sdk=iphonesimulator*]'] = `uname -m`
end
end
end
This way you only override the iOS simulator's compiler architecture as your current cpu's architecture. Compared to others, this solution will also work on computers with Apple Silicon.
Try to see if it works in Incognito Mode. If it does, then it's a bug in recent Chrome. On my computer the following fix worked:
Simply Update the Chrome browser to the latest version available.
For me I was working under Ubuntu
The error disappeared if I use sudo with ng
sudo ng build
sudo ng serve
I had this problem but didn't have a version conflict in my package.json.
My package-lock.json was somehow out of sync with package json though. Deleting and regenerating it worked for me.
In my case downgrading @angular/animations worked, if you can afford to do that, run the command
npm i @angular/[email protected]
Or use another version that might work for you from the Versions tab here: https://www.npmjs.com/package/@angular/animations
Effective January 15, 2020, The Central Repository no longer supports insecure communication over plain HTTP and requires that all requests to the repository are encrypted over HTTPS.
If you're receiving this error, then you need to replace all URL references to Maven Central with their canonical HTTPS counterparts.
(source)
We have made the following changes in my project's build.gradle:
Old:
repositories {
maven { url "http://repo.maven.apache.org/maven2" }
}
New:
repositories {
maven { url "https://repo.maven.apache.org/maven2" }
}
Took me a while to aggregate an actual solution, but here's how to get rid of this compile error.
Open IntelliJ preferences.
Search for "compiler" (or something like "compi").
Scroll down to Maven -->java compiler. In the right panel will be a list of modules and their associated java compile version "target bytecode version."
Select a version >1.5. You may need to upgrade your jdk if one is not available.
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
I had same problem & i have installed "create-react-app" globally on my machine. There is error :
"A template was not provided. This is likely because you're using an outdated version of create-react-app. Please note that global installs of create-react-app are no longer supported."
Then i removed previous install by using this command.
npm uninstall -g create-react-app
Then install new react app.
npx create-react-app new-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;
}
I was able to solve this by upgrading Python 3 via brew
brew upgrade python@3
import { MatDialogModule } from '@angular/material/dialog';
import { MatTableModule } from '@angular/material/table';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
You can update your python version to 3.8 in conda using the command
conda install -c anaconda python=3.8
as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running
conda update --all
may resolve some dependency failures. You can also create a new environment called py38 using this command
conda create -n py38 python=3.8
Edit - note that the conda install
option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).
According to the official doc (https://nodejs.org/api/esm.html#esm_code_import_code_statements):
import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to (https://nodejs.org/api/esm.html#esm_enabling):
In my case, it was WordPress that now requires PHP 7.4 and I was running 7.2.
As soon as I updated, the errors disappeared.
The error is triggered because the file you're linking to in your HTML file is the unbundled version of the file.
To get the full bundled version you'll have to install it with npm
:
npm install --save milsymbol
This downloads the full package to your node_modules
folder.
You can then access the standalone minified JavaScript file at node_modules/milsymbol/dist/milsymbol.js
You can do this in any directory, and then just copy the below file to your /src
directory.
>= PHP 7.3
setcookie('key', 'value', ['samesite' => 'None', 'secure' => true]);
< PHP 7.3
exploit the path
setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");
Emitting javascript
echo "<script>document.cookie('key=value; SameSite=None; Secure');</script>";
This is a setting in IntelliJ IDEA ($JAVA_HOME
and language level were set to 1.8):
File
> Settings
> Build, Execution, Deployment
> Gradle
> Gradle JVM
Select eg. Project SDK (corretto-1.8)
(or any other compatible version).
Then delete the build
directory and restart the IDE.
Remove ng.ps1
from the directory C:\Users\%username%\AppData\Roaming\npm\
then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\
It is simple , remove the code that you have used and use the below code :
const url = 'mongodb://localhost:27017';
var dbConn = mongodb.MongoClient.connect(url, {useUnifiedTopology: true});
change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:
data['label'] = data['label'].astype(np.uint8)
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
The most voted answer certainly works for me but it makes the Manage session window popping up again and again.
I've solved that by auto clicking the refresh button using browser console like below
function ClickRefresh(){
console.log("Clicked on refresh button");
document.querySelector("paper-icon-button").click()
}
setInterval(ClickRefresh, 60000)
Feel free to contribute more snippets for this at this gist https://gist.github.com/Subangkar/fd1ef276fd40dc374a7c80acc247613e
This is what it worked for me. The tsconfig.json
has an option noImplicitAny
that it was set to true
, I just simply set it to false
and now I can access properties in objects using strings.
if your using snap package dotnet-sdk on linux this can resolve by updating your ~.bashrc / etc. as follows:
#!/bin/bash
export DOTNET_ROOT=/snap/dotnet-sdk/current
export MSBuildSDKsPath=$DOTNET_ROOT/sdk/$(${DOTNET_ROOT}/dotnet --version)/Sdks
export PATH="${PATH}:${DOTNET_ROOT}"
export PATH="$PATH:$HOME/.dotnet/tools"
Add the path of python folder in environmental variable and it will work
1.search environmental variable
2.look for system variable section and find variable named path in it
3.double click on path and add new path which directs towards python folder and that's it.
the python folder is usually in C:\Users["user name"]\AppData\Local\Programs\Python\Python39
In Angular 8, ViewChild always takes 2 param, and second params always has static: true or static: false
You can try like this:
@ViewChild('nameInput', {static: false}) component
Also,the static: false
is going to be the default fallback behaviour in Angular 9.
What are static false/true: So as a rule of thumb you can go for the following:
{ static: true }
needs to be set when you want to access the
ViewChild in ngOnInit.
{ static: false }
can only be accessed in ngAfterViewInit. This is
also what you want to go for when you have a structural directive
(i.e. *ngIf) on your element in your template.
My case.... SOLUTION in HOOKS
const [cep, setCep] = useState('');
const mounted = useRef(false);
useEffect(() => {
if (mounted.current) {
fetchAPI();
} else {
mounted.current = true;
}
}, [cep]);
const setParams = (_cep) => {
if (cep !== _cep || cep === '') {
setCep(_cep);
}
};
Simple install
pip3 install PyQt5==5.9.2
It works for me.
Solved similar issue by doing this:
export interface IItem extends Record<string, any> {
itemId: string;
price: number;
}
const item: IItem = { itemId: 'someId', price: 200 };
const fieldId = 'someid';
// gives you no errors and proper typing
item[fieldId]
I have to say, if you don't want to change anything in package.json
file, try to update your Node.js version to latest. (currently 12.13.1 LTS)
import UIKit
extension UIViewController {
override open func awakeFromNib() {
super.awakeFromNib()
if #available(iOS 13.0, *) {
overrideUserInterfaceStyle = .light
}
}
}
Login Page design using SwiftUI
import SwiftUI
struct ContentView: View {
@State var email: String = "[email protected]"
@State var password: String = ""
@State static var labelTitle: String = ""
var body: some View {
VStack(alignment: .center){
//Label
Text("Login").font(.largeTitle).foregroundColor(.yellow).bold()
//TextField
TextField("Email", text: $email)
.textContentType(.emailAddress)
.foregroundColor(.blue)
.frame(minHeight: 40)
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
TextField("Password", text: $password) //Placeholder
.textContentType(.newPassword)
.frame(minHeight: 40)
.foregroundColor(.blue) // Text color
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
//Button
Button(action: {
}) {
HStack {
Image(uiImage: UIImage(named: "Login")!)
.renderingMode(.original)
.font(.title)
.foregroundColor(.blue)
Text("Login")
.font(.title)
.foregroundColor(.white)
}
.font(.headline)
.frame(minWidth: 0, maxWidth: .infinity)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
.padding(.horizontal, 20)
.frame(width: 200, height: 50, alignment: .center)
}
Spacer()
}.padding(10)
.frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity, minHeight: 0, idealHeight: .infinity, maxHeight: .infinity, alignment: .top)
.background(Color.gray)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs
@Bean
WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
}
}
}
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);
If your project is .net Core 3.1 API project.
update your Startup.cs in your .net core project to:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:53135",
"http://localhost:4200"
)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddDbContext<CIVDataContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CIVDatabaseConnection")));
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(MyAllowSpecificOrigins);
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
esModuleInterop
generates the helpers outlined in the docs. Looking at the generated code, we can see exactly what these do:
//ts
import React from 'react'
//js
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = __importDefault(require("react"));
__importDefault
: If the module is not an es
module then what is returned by require becomes the default. This means that if you use default import on a commonjs
module, the whole module is actually the default.
__importStar
is best described in this PR:
TypeScript treats a namespace import (i.e.
import * as foo from "foo"
) as equivalent toconst foo = require("foo")
. Things are simple here, but they don't work out if the primary object being imported is a primitive or a value with call/construct signatures. ECMAScript basically says a namespace record is a plain object.Babel first requires in the module, and checks for a property named
__esModule
. If__esModule
is set totrue
, then the behavior is the same as that of TypeScript, but otherwise, it synthesizes a namespace record where:
- All properties are plucked off of the require'd module and made available as named imports.
- The originally require'd module is made available as a default import.
So we get this:
// ts
import * as React from 'react'
// emitted js
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
allowSyntheticDefaultImports
is the companion to all of this, setting this to false will not change the emitted helpers (both of them will still look the same). But it will raise a typescript error if you are using default import for a commonjs module. So this import React from 'react'
will raise the error Module '".../node_modules/@types/react/index"' has no default export.
if allowSyntheticDefaultImports
is false
.
Add <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version> in property tag
problem resolve
https://medium.com/@saannjaay/unknown-error-in-pom-xml-66fb2414991b
I was getting this error on Windows 10. Turned out to be a corrupted roaming profile.
npm ERR! node v12.4.0
npm ERR! npm v3.3.12
npm ERR! primordials is not defined
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>
npm ERR! Please include the following file with any support request:
Deleting the C:\Users\{user}\AppData\Roaming\npm
folder fixed my issue.
You can try changing the flag's value
np.load(training_image_names_array,allow_pickle=True)
This issue might be helpful for you, it explains how to achieve TPUStrategy
, a popular functionality of tf.contrib
in TF<2.0.
So, in TF 1.X you could do the following:
resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.contrib.distribute.initialize_tpu_system(resolver)
strategy = tf.contrib.distribute.TPUStrategy(resolver)
And in TF>2.0, where tf.contrib
is deprecated, you achieve the same by:
tf.config.experimental_connect_to_host('grpc://' + os.environ['COLAB_TPU_ADDR'])
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver)
Make function name capital. This works for me.
export default function App() { }
const [mount, setMount] = useState(false)
const fetchBusinesses = () => {
//function defination
}
useEffect(() => {
if(!mount) {
setMount(true);
fetchBusinesses();
}
},[fetchBusinesses]);
This is solution is pretty simple and you don't need to override es-lint warnings. Just maintain a flag to check whether component is mounted or not.
delete react node_modules
rm -r node_modules
yarn or npm install
yarn start or npm start
if error occurs use this method again
Yes it's possible. Follow these steps:
Ended up to have a file named polyfill.js in projectpath\src\polyfill.js That file only contains this line: import 'core-js'; this polyfills not only es-6, but is the correct way to use core-js since version 3.0.0.
I added the polyfill.js to my webpack-file entry attribute like this:
entry: ['./src/main.scss', './src/polyfill.js', './src/main.jsx']
Works perfectly.
I also found some more information here : https://github.com/zloirock/core-js/issues/184
The library author (zloirock) claims:
ES6 changes behaviour almost all features added in ES5, so core-js/es6 entry point includes almost all of them. Also, as you wrote, it's required for fixing broken browser implementations.
(Quotation https://github.com/zloirock/core-js/issues/184 from zloirock)
So I think import 'core-js'; is just fine.
In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).
Initialize Model Structure in Constructor:
this.newForm = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
});
If you want to update all fields of form:
this.newForm.setValue({
firstName: 'abc',
lastName: 'def'
});
If you want to update specific field of form:
this.newForm.controls.firstName.setValue('abc');
Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.
If you want to update some/ specific fields of form:
this.newForm.patchValue({
firstName: 'abc'
});
Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.
You can prevent from this error by using hooks inside a function
I got the same error when I am using robot framework (Selenium based framework) in a Docker instance. The reason was docker was using cached google-chrome-stable_current_amd64.deb
for Chrome but it has installed latest chrome driver which was a later version.
Then I used below command and error resolved.
docker-compose build --no-cache
Hope this helps someone.
mainly this type of error generate, 1.first check a code, in code, we define @csrf
<form method ="post" action={{url('project'')}}
@csrf
......
2.when we define a wrong variable name, that time also happened this type of problem.
ex. if your database field name "xyz" and you use a "wxyz"
3.if our method is wrong in form,so plz check our method.
ex. <form method="post">
For TF2.x
, you can do like this.
import tensorflow as tf
with tf.compat.v1.Session() as sess:
hello = tf.constant('hello world')
print(sess.run(hello))
>>> b'hello world
useEffect are isolated within its own scope and gets rendered accordingly. Image from https://reactjs.org/docs/hooks-custom.html
This is the easiest way.
I did not need to open a new notebook. Instead, I reopened the tree, and reconnected the kernel. At some point I also restarted the kernel. – user650654 Oct 9 '19 at 0:17
Another way to achieve this:
const [Name, setName] = useState({val:"", callback: null});_x000D_
React.useEffect(()=>{_x000D_
console.log(Name)_x000D_
const {callback} = Name;_x000D_
callback && callback();_x000D_
}, [Name]);_x000D_
setName({val:'foo', callback: ()=>setName({val: 'then bar'})})
_x000D_
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
Instead of specifying a deployment target in pod post install, you can delete the pod deployment target, which causes the deployment target to be inherited from the podfile platform.
You may need to run pod install for the effect to take place.
platform :ios, '12.0'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
end
end
end
sudo apt update
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.7
sudo apt install python3-pip
python3.7 -m pip install pip
sudo update-alternatives --install /usr/local/bin/python python /usr/bin/python3.7 10
sudo update-alternatives --install /usr/local/bin/pip pip /home/your_username/.local/bin/pip3.7 10
source ~/.bashrc
python --version
pip --version
If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!
countDownTimer() async {
int timerCount;
for (int x = 5; x > 0; x--) {
await Future.delayed(Duration(seconds: 1)).then((_) {
setState(() {
timerCount -= 1;
});
});
}
}
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name
A.B
designates a submodule namedB
in a package namedA
....
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring
, from unintentionally hiding valid modules that occur later on the module search path.
You need to set it up to something like this:
man
|- __init__.py
|- Mans
|- __init__.py
|- man1.py
|- MansTest
|- __init.__.py
|- SoftLib
|- Soft
|- __init__.py
|- SoftWork
|- __init__.py
|- manModules.py
|- Unittests
|- __init__.py
|- man1test.py
SECOND, for the "ModuleNotFoundError: No module named 'Soft'
" error caused by from ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py to sys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path
directly, you can also modify PYTHONPATH
:
sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
THIRD, for from ...MansTest.SoftLib import Soft
which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.
With that said, here's how I got it to work.
man1.py:
from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH
def foo():
print("called foo in man1.py")
print("foo call module1 from manModules: " + module1())
man1test.py
# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1
man1.foo()
manModules.py
def module1():
return "module1 in manModules"
Terminal output:
$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
...
from ...Mans import man1
File "/temp/man/Mans/man1.py", line 2, in <module>
from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'
$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).
This error could also be because you are not subscribing to the Observable.
Example, instead of:
this.products = this.productService.getProducts();
do this:
this.productService.getProducts().subscribe({
next: products=>this.products = products,
error: err=>this.errorMessage = err
});
To disable auto activation of conda base environment in terminal:
conda config --set auto_activate_base false
To activate conda base environment:
conda activate
I ran into the same issue in Ubuntu 18.04.3 LTS. In my case, apt installed gradle version 4.4.1. The already-install java version was 11.0.4
The build message I got was
Could not determine java version from '11.0.4'.
At the time, most of the online docs referenced gradle version 5.6, so I did the following:
sudo add-apt-repository ppa:cwchien/gradle
sudo apt update
sudo apt upgrade gradle
Then I repeated the project initialiation (using "gradle init" with the defaults). After that, "./gradlew build" worked correctly.
I later read a comment regarding a change in format of the output from "java --version" that caused gradle to break, which was fixed in a later version of gradle.
Tried this on Android Studio and it worked for me:
Tools > SDK Manager (Make sure to check Show Packages below)
Or download composer.phar from site: "https://getcomposer.org/download/" (manual download), and use command:
php composer.phar require your/package
You can pass new value like this
setExampleState({...exampleState, masterField2: {
fieldOne: "c",
fieldTwo: {
fieldTwoOne: "d",
fieldTwoTwo: "e"
}
},
}})
2021 Jan.12th
the whole point for me is to explicitly specify the version as java 11 in my pom.xml, and I solved the problem by taking the following steps.
open terminal and input: java -version, then i got 1.8, and i went to .bash_profile to switch the java version to 11.2 as i have multiple java version installed. please remember "restart" your terminal and check your java version again to confirm switch is successful.
Then i went to File -> Project Structure to make sure my IntelliJ using the same version as my env, which is 11.2.
RESTART your Intellij, mvn clean install, solved, hope this could help someone with this issue, thanks.
Windows Users need to set below paths:
..\Anaconda3
..\Anaconda3\scripts
..\Anaconda3\Library\bin
Per user:
System wide (requires restart):
Looks like the NoCoffee Vision Simulator extension for Chrome will also cause this error. Just adding it as a prospective cause for people looking in their own instance.
useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.
object and array spread or rest will not work inside useEffect.
React.useEffect(() => {
console.log("effect");
(async () => {
try {
let result = await fetch("/query/countries");
const res = await result.json();
let result1 = await fetch("/query/projects");
const res1 = await result1.json();
let result11 = await fetch("/query/regions");
const res11 = await result11.json();
setData({
countries: res,
projects: res1,
regions: res11
});
} catch {}
})(data)
}, [setData])
# or use this
useEffect(() => {
(async () => {
try {
await Promise.all([
fetch("/query/countries").then((response) => response.json()),
fetch("/query/projects").then((response) => response.json()),
fetch("/query/regions").then((response) => response.json())
]).then(([country, project, region]) => {
// console.log(country, project, region);
setData({
countries: country,
projects: project,
regions: region
});
})
} catch {
console.log("data fetch error")
}
})()
}, [setData]);
Open angular.json file and find budgets
keyword.
It should look like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
As you’ve probably guessed you can increase the maximumWarning
value to prevent this warning, i.e.:
"budgets": [
{
"type": "initial",
"maximumWarning": "4mb", <===
"maximumError": "5mb"
}
]
A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.
In our case budget is the limit for bundle sizes.
See also:
I encountered the same problem after freshly installing git on Windows 10 and running it for the first time. Restarting the bash window solved the problem.
The solution from @ford04 didn't worked to me and specially if you need to use the isMounted in multiple places (multiple useEffect for instance), it's recommended to useRef, as bellow:
"dependencies":
{
"react": "17.0.1",
}
"devDependencies": {
"typescript": "4.1.5",
}
export const SubscriptionsView: React.FC = () => {
const [data, setData] = useState<Subscription[]>();
const isMounted = React.useRef(true);
React.useEffect(() => {
if (isMounted.current) {
// fetch data
// setData (fetch result)
return () => {
isMounted.current = false;
};
}
}
});
I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem
If someone happens to be as moronic as me, the following worked.
Old folder structure:
awesome_code.py
__init__.py
src/
__init__.py
stuff1.py
stuff2.py
New structure:
awesome_code.py
src/
__init__.py
stuff1.py
stuff2.py
The accepted answer shows the correct way to setState but it does not lead to a well functioning select box.
import React, { useState } from "react";
import ReactDOM from "react-dom";
const initialValue = { id: 0,value: " --- Select a State ---" };
const options = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const StateSelector = () => {
const [ selected, setSelected ] = useState(initialValue);
return (
<div>
<label>Select a State:</label>
<select value={selected}>
{selected === initialValue &&
<option disabled value={initialValue}>{initialValue.value}</option>}
{options.map((localState, index) => (
<option key={localState.id} value={localState}>
{localState.value}
</option>
))}
</select>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
I have met this problem because I edit the Program.cs and I delete the Run function. Just add it again:
In my case the cause was Ubuntu version no longer supported by Canonical. I was able to upgrade to still supported LTS with 2 steps:
1) Manually update repo links from "in.ubuntu" to "old-releases.ubuntu".
1.1) Installed all outstanding updates
2) do-release-upgrade
was able to take from this point and do actual upgrade
IMHO, this is safer method then just updating repositories to next supported ubuntu, since do-release-upgrade
have chance to prevent upgrade that could fail, and may be able to diagnose a problem for you.
useEffect
can hook on a certain prop or state. so, the thing you need to do to avoid infinite loop hook is binding some variable or state to effect
For Example:
useEffect(myeffectCallback, [])
above effect will fire only once the component has rendered. this is similar to componentDidMount
lifecycle
const [something, setSomething] = withState(0)
const [myState, setMyState] = withState(0)
useEffect(() => {
setSomething(0)
}, myState)
above effect will fire only my state has changed this is similar to componentDidUpdate
except not every changing state will fire it.
You can read more detail though this link
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
As a type that contains children, I'm using:
type ChildrenContainer = Pick<JSX.IntrinsicElements["div"], "children">
This children container type is generic enough to support all the different cases and also aligned with the ReactJS API.
So, for your example it would be something like:
const layout = ({ children }: ChildrenContainer) => (
<Aux>
<div>Toolbar, SideDrawer, Backdrop</div>
<main>
{children}
</main>
<Aux/>
)
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
This post aims to give readers a primer on SQL-flavored merging with pandas, how to use it, and when not to use it.
In particular, here's what this post will go through:
The basics - types of joins (LEFT, RIGHT, OUTER, INNER)
What this post (and other posts by me on this thread) will not go through:
Note
Most examples default to INNER JOIN operations while demonstrating various features, unless otherwise specified.Furthermore, all the DataFrames here can be copied and replicated so you can play with them. Also, see this post on how to read DataFrames from your clipboard.
Lastly, all visual representation of JOIN operations have been hand-drawn using Google Drawings. Inspiration from here.
merge
!np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})
right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
left
key value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right
key value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
For the sake of simplicity, the key column has the same name (for now).
An INNER JOIN is represented by
Note
This, along with the forthcoming figures all follow this convention:
- blue indicates rows that are present in the merge result
- red indicates rows that are excluded from the result (i.e., removed)
- green indicates missing values that are replaced with
NaN
s in the result
To perform an INNER JOIN, call merge
on the left DataFrame, specifying the right DataFrame and the join key (at the very least) as arguments.
left.merge(right, on='key')
# Or, if you want to be explicit
# left.merge(right, on='key', how='inner')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
This returns only rows from left
and right
which share a common key (in this example, "B" and "D).
A LEFT OUTER JOIN, or LEFT JOIN is represented by
This can be performed by specifying how='left'
.
left.merge(right, on='key', how='left')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
Carefully note the placement of NaNs here. If you specify how='left'
, then only keys from left
are used, and missing data from right
is replaced by NaN.
And similarly, for a RIGHT OUTER JOIN, or RIGHT JOIN which is...
...specify how='right'
:
left.merge(right, on='key', how='right')
key value_x value_y
0 B 0.400157 1.867558
1 D 2.240893 -0.977278
2 E NaN 0.950088
3 F NaN -0.151357
Here, keys from right
are used, and missing data from left
is replaced by NaN.
Finally, for the FULL OUTER JOIN, given by
specify how='outer'
.
left.merge(right, on='key', how='outer')
key value_x value_y
0 A 1.764052 NaN
1 B 0.400157 1.867558
2 C 0.978738 NaN
3 D 2.240893 -0.977278
4 E NaN 0.950088
5 F NaN -0.151357
This uses the keys from both frames, and NaNs are inserted for missing rows in both.
The documentation summarizes these various merges nicely:
If you need LEFT-Excluding JOINs and RIGHT-Excluding JOINs in two steps.
For LEFT-Excluding JOIN, represented as
Start by performing a LEFT OUTER JOIN and then filtering (excluding!) rows coming from left
only,
(left.merge(right, on='key', how='left', indicator=True)
.query('_merge == "left_only"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
Where,
left.merge(right, on='key', how='left', indicator=True)
key value_x value_y _merge
0 A 1.764052 NaN left_only
1 B 0.400157 1.867558 both
2 C 0.978738 NaN left_only
3 D 2.240893 -0.977278 both
And similarly, for a RIGHT-Excluding JOIN,
(left.merge(right, on='key', how='right', indicator=True)
.query('_merge == "right_only"')
.drop('_merge', 1))
key value_x value_y
2 E NaN 0.950088
3 F NaN -0.151357
Lastly, if you are required to do a merge that only retains keys from the left or right, but not both (IOW, performing an ANTI-JOIN),
You can do this in similar fashion—
(left.merge(right, on='key', how='outer', indicator=True)
.query('_merge != "both"')
.drop('_merge', 1))
key value_x value_y
0 A 1.764052 NaN
2 C 0.978738 NaN
4 E NaN 0.950088
5 F NaN -0.151357
If the key columns are named differently—for example, left
has keyLeft
, and right
has keyRight
instead of key
—then you will have to specify left_on
and right_on
as arguments instead of on
:
left2 = left.rename({'key':'keyLeft'}, axis=1)
right2 = right.rename({'key':'keyRight'}, axis=1)
left2
keyLeft value
0 A 1.764052
1 B 0.400157
2 C 0.978738
3 D 2.240893
right2
keyRight value
0 B 1.867558
1 D -0.977278
2 E 0.950088
3 F -0.151357
left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')
keyLeft value_x keyRight value_y
0 B 0.400157 B 1.867558
1 D 2.240893 D -0.977278
When merging on keyLeft
from left
and keyRight
from right
, if you only want either of the keyLeft
or keyRight
(but not both) in the output, you can start by setting the index as a preliminary step.
left3 = left2.set_index('keyLeft')
left3.merge(right2, left_index=True, right_on='keyRight')
value_x keyRight value_y
0 0.400157 B 1.867558
1 2.240893 D -0.977278
Contrast this with the output of the command just before (that is, the output of left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')
), you'll notice keyLeft
is missing. You can figure out what column to keep based on which frame's index is set as the key. This may matter when, say, performing some OUTER JOIN operation.
DataFrames
For example, consider
right3 = right.assign(newcol=np.arange(len(right)))
right3
key value newcol
0 B 1.867558 0
1 D -0.977278 1
2 E 0.950088 2
3 F -0.151357 3
If you are required to merge only "new_val" (without any of the other columns), you can usually just subset columns before merging:
left.merge(right3[['key', 'newcol']], on='key')
key value newcol
0 B 0.400157 0
1 D 2.240893 1
If you're doing a LEFT OUTER JOIN, a more performant solution would involve map
:
# left['newcol'] = left['key'].map(right3.set_index('key')['newcol']))
left.assign(newcol=left['key'].map(right3.set_index('key')['newcol']))
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
As mentioned, this is similar to, but faster than
left.merge(right3[['key', 'newcol']], on='key', how='left')
key value newcol
0 A 1.764052 NaN
1 B 0.400157 0.0
2 C 0.978738 NaN
3 D 2.240893 1.0
To join on more than one column, specify a list for on
(or left_on
and right_on
, as appropriate).
left.merge(right, on=['key1', 'key2'] ...)
Or, in the event the names are different,
left.merge(right, left_on=['lkey1', 'lkey2'], right_on=['rkey1', 'rkey2'])
merge*
operations and functionsMerging a DataFrame with Series on index: See this answer.
Besides merge
, DataFrame.update
and DataFrame.combine_first
are also used in certain cases to update one DataFrame with another.
pd.merge_ordered
is a useful function for ordered JOINs.
pd.merge_asof
(read: merge_asOf) is useful for approximate joins.
This section only covers the very basics, and is designed to only whet your appetite. For more examples and cases, see the documentation on merge
, join
, and concat
as well as the links to the function specs.
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
All the answers above are correct, but when I use windows and disable the Prettier ESLint extension rvest.vs-code-prettier-eslint
the issue will be fixed.
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
Using .multiply() (ufunc multiply)
a_1 = np.array([1.0, 2.0, 3.0])
a_2 = np.array([[1., 2.], [3., 4.]])
b = 2.0
np.multiply(a_1,b)
# array([2., 4., 6.])
np.multiply(a_2,b)
# array([[2., 4.],[6., 8.]])
Just simply add an empty dependenncy array in useEffect it will works as componentDidMount
.
useEffect(() => {
// Your code here
console.log("componentDidMount")
}, []);
You can use useImmer opposed to useState and access the state. Example: https://css-tricks.com/build-a-chat-app-using-react-hooks-in-100-lines-of-code/
I read through this question, and feel the best way to implement useEffect is not mentioned in the answers. Let's say you have a network call, and would like to do something once you have the response. For the sake of simplicity, let's store the network response in a state variable. One might want to use action/reducer to update the store with the network response.
const [data, setData] = useState(null);
/* This would be called on initial page load */
useEffect(()=>{
fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(data => {
setData(data);
})
.catch(err => {
/* perform error handling if desired */
});
}, [])
/* This would be called when store/state data is updated */
useEffect(()=>{
if (data) {
setPosts(data.children.map(it => {
/* do what you want */
}));
}
}, [data]);
Reference => https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
i had the same issue, but I just typed export
on top and erased the default one on the bottom. Scroll down and check the comments.
import React, { Component } from "react";
export class Counter extends Component { // type this
export default Counter; // this is eliminated
The only thing that worked for me was creating a new application in the IIS, mapping it to exactly the same physical path, and changing only the authentication to be Anonymous.
For me the reason was while changing name of app I added a single quote ' in name. I tried different solution and ran into different errors, but at last, while renaming app, I did not include ' single quote and it solved the problem.
My variation of forceUpdate
is not via a counter
but rather via an object:
// Emulates `forceUpdate()`
const [unusedState, setUnusedState] = useState()
const forceUpdate = useCallback(() => setUnusedState({}), [])
Because {} !== {}
every time.
On Ubuntu 18.04, I ran into this issue because the apt
package for wheel
does not include the wheel
command. I think pip tries to import the wheel
python package, and if that succeeds assumes that the wheel
command is also available. Ubuntu breaks that assumption.
The apt python3 code package is named python3-wheel
. This is installed automatically because python3-pip
recommends it.
The apt python3 wheel command package is named python-wheel-common
. Installing this too fixes the "failed building wheel" errors for me.
useState() is an example built-in React hook that lets you use states in your functional components. This was not possible before React 16.7.
The useState function is a built in hook that can be imported from the react package. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.
Running a function only once after component mounts is such a common pattern that it justifies a hook of it's own that hides implementation details.
const useMountEffect = (fun) => useEffect(fun, [])
Use it in any functional component.
function MyComponent() {
useMountEffect(function) // function will run only once after it has mounted.
return <div>...</div>;
}
About the useMountEffect hook
When using useEffect
with a second array argument, React will run the callback after mounting (initial render) and after values in the array have changed. Since we pass an empty array, it will run only after mounting.
Make sure that both the chromedriver
and google-chrome
executable have execute permissions
sudo chmod -x "/usr/bin/chromedriver"
sudo chmod -x "/usr/bin/google-chrome"
If you're using scss for your styles you can use a mixin to help generate the code. Your styles will quickly get out of hand if you put all the properties every time.
This is a very simple example - really nothing more than a proof of concept, you can extend this with multiple properties and rules as needed.
@mixin mat-table-columns($columns)
{
.mat-column-
{
@each $colName, $props in $columns {
$width: map-get($props, 'width');
&#{$colName}
{
flex: $width;
min-width: $width;
@if map-has-key($props, 'color')
{
color: map-get($props, 'color');
}
}
}
}
}
Then in your component where your table is defined you just do this:
@include mat-table-columns((
orderid: (width: 6rem, color: gray),
date: (width: 9rem),
items: (width: 20rem)
));
This generates something like this:
.mat-column-orderid[_ngcontent-c15] {
flex: 6rem;
min-width: 6rem;
color: gray; }
.mat-column-date[_ngcontent-c15] {
flex: 9rem;
min-width: 9rem; }
In this version width
becomes flex: value; min-width: value
.
For your specific example you could add wrap: true
or something like that as a new parameter.
If You're using JSX inside a function with curly braces you need to modify it to parenthesis.
Wrong Code
return this.props.todos.map((todo) => {
<h3> {todo.author} </h3>;
});
Correct Code
//Change Curly Brace To Paranthesis change {} to => ()
return this.props.todos.map((todo) => (
<h3> {todo.author} </h3>;
));
I was experiencing this issue with nextcloud which would fail to create thumbnails for pdf files.
However, none of the suggested steps would solve the issue for me.
Eventually I found the reason: The accepted answer did work but I had to also restart php-fpm after editing the policy.xml file:
sudo systemctl restart php7.2-fpm.service
Placing your list view in a Flexible widget may also help,
Flexible( fit: FlexFit.tight, child: _buildYourListWidget(..),)
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.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
Just change .env
SESSION_DRIVER=cookie
For those using Catalina and Xcode-beta:
sudo xcode-select -s /Applications/Xcode-beta.app/Contents/Developer
From the comment by @ZhekaKozlov: ojdkbuild has OpenJDK builds (currently 8 and 11) for Windows (zip
and msi
).
sudo apt-get install openjdk-11-jdk
after this, try
java -version
to make sure java version is 1.11.x, if found old one or different, check below command to see the available jdks,
sudo update-java-alternatives --list
you should see something like below,
java-1.11.0-openjdk-amd64 1111 /usr/lib/jvm/java-1.11.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1081 /usr/lib/jvm/java-1.8.0-openjdk-amd64
you can see java 1.11 available from above list, use below command to set java 11 to default,
sudo update-alternatives --config java
for above command, you will get something like below and also, will ask for an option to set,
There are 3 choices for the alternative java (providing /usr/bin/java).
Selection Path Priority Status
0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 auto mode
1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 manual mode
*2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode
3 /usr/lib/jvm/jdk1.8.0_211/bin/java 0 manual mode
Press to keep the current choice[*], or type selection number:
you can select desired selection number, my case it's 0
for javac,
sudo update-alternatives --config javac
will result something like below,
There are 3 choices for the alternative javac (providing /usr/bin/javac).
Selection Path Priority Status
0 /usr/lib/jvm/java-11-openjdk-amd64/bin/javac 1111 auto mode
1 /usr/lib/jvm/java-11-openjdk-amd64/bin/javac 1111 manual mode
*2 /usr/lib/jvm/java-8-openjdk-amd64/bin/javac 1081 manual mode
3 /usr/lib/jvm/jdk1.8.0_211/bin/javac 0 manual modePress to keep the current choice[*], or type selection number:
in my case, it's 0 again
after above steps, try
java -version
it will display something like below,
openjdk version "11.0.4" 2019-07-16
OpenJDK Runtime Environment (build 11.0.4+11-post-Ubuntu-1ubuntu218.04.3)
OpenJDK 64-Bit Server VM (build 11.0.4+11-post-Ubuntu-1ubuntu218.04.3, mixed > mode, sharing)
Go back from classpath 'com.android.tools.build:gradle:3.3.0-alpha13' to classpath 'com.android.tools.build:gradle:3.2.0'
this worked for me
The issue that JavaFX is no longer part of JDK 11. The following solution works using IntelliJ (haven't tried it with NetBeans):
Add JavaFX Global Library as a dependency:
Settings -> Project Structure -> Module. In module go to the Dependencies tab, and click the add "+" sign -> Library -> Java-> choose JavaFX from the list and click Add Selected, then Apply settings.
Right click source file (src) in your JavaFX project, and create a new module-info.java file. Inside the file write the following code :
module YourProjectName {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens sample;
}
These 2 steps will solve all your issues with JavaFX, I assure you.
Reference : There's a You Tube tutorial made by The Learn Programming channel, will explain all the details above in just 5 minutes. I also recommend watching it to solve your problem: https://www.youtube.com/watch?v=WtOgoomDewo
In short:
Explanation:
Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.
OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.
OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.
Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.
AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.
OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.
Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".
Donald Smith, Java product manager at Oracle writes:
Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.
---------------------------------------------------------------------------------------- | Provider | Free Builds | Free Binary | Extended | Commercial | Permissive | | | from Source | Distributions | Updates | Support | License | |--------------------------------------------------------------------------------------| | AdoptOpenJDK | Yes | Yes | Yes | No | Yes | | Amazon – Corretto | Yes | Yes | Yes | No | Yes | | Azul Zulu | No | Yes | Yes | Yes | Yes | | BellSoft Liberica | No | Yes | Yes | Yes | Yes | | IBM | No | No | Yes | Yes | Yes | | jClarity | No | No | Yes | Yes | Yes | | OpenJDK | Yes | Yes | Yes | No | Yes | | Oracle JDK | No | Yes | No** | Yes | No | | Oracle OpenJDK | Yes | Yes | No | No | Yes | | ojdkbuild | Yes | Yes | No | No | Yes | | RedHat | Yes | Yes | Yes | Yes | Yes | | SapMachine | Yes | Yes | Yes | Yes | Yes | ----------------------------------------------------------------------------------------
Free Builds from Source - the distribution source code is publicly available and one can assemble its own build
Free Binary Distributions - the distribution binaries are publicly available for download and usage
Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle
Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)
Permissive License - the distribution license is non-protective, e.g. Apache 2.0
In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.
What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.
Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).
If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.
Additional information
Time to look beyond Oracle's JDK by Stephen Colebourne
Java Is Still Free by Java Champions community (published on September 17, 2018)
Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)
Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)
In My case, I had a added async at app.js like shown below.
const App = async() => {
return(
<Text>Hello world</Text>
)
}
But it was not necessary, when testing something I had added it and it was no longer required. After removing it, as shown below, things started working.
const App =() => {
return(
<Text>Hello world</Text>
)
}
[edit] Note 2020: I used to manual sign this project. In projects where I automatically signed, I never had this issue. [/edit]
I had the same problem, and spent hours searching for an answer, removing profiles, cleaning project, and so on.
Have you distributed your app? You need to switch back to your developer profile, but not in General under the project settings, but in Build settings.
Under Signing, look at your Code Signing Identity.
Make sure that both your Debug and Release are set your iOS Developer, and not iOS Distribution; or your iOS Developer Provisioning profile, if not set to the automatic values.
The same goes with Provisioning Profile. It should be your developing profile, and not your distribution profile.
Hope this will help future developers in need.
After i copied two .aiff files in a .scnassets group, this error occured. Deletion of the files and a "Clean Build Folder" solves the problem in my case.
I have solved following this way
import { Router, ActivatedRoute } from '@angular/router';
constructor(private router: Router
, private activeRoute: ActivatedRoute) {
}
reloadCurrentPage(){
let currentUrl = this.router.url;
this.router.navigateByUrl('/', {skipLocationChange: true}).then(() => {
this.router.navigate([currentUrl]);
});
}
For me, just cleaning project works using ShiftCommandK & OptionShiftCommandK.
You should install python 3.6 version because python 3.7 version doesn't support pyaudio
1 step : Then download the .whl file
according to your python version and the configuration of your machine in your python folder which is newly installed. For me it is python 3.6 and 64 bit machine. Download the file from here
(https://www.lfd.uci.edu/~gohlke/pythonlibs/)
2 step : run your cmd and type " pip install your downloaded file name here "
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.
Try this:
window.open(this.url+'/create-account')
No need to use '_blank'
. window.open
by default opens a link in a new tab.
yarn add --dev @babel/plugin-proposal-class-properties
or
npm install @babel/plugin-proposal-class-properties --save-dev
.babelrc
The use of the deprecated new Buffer()
constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.
According to the deprecation warning new Buffer()
should be replaced with one of:
Buffer.alloc()
Buffer.allocUnsafe()
or Buffer.from()
Another option in order to avoid this issue would be using the safe-buffer package instead.
You can also try (when using yarn..):
yarn global add yarn
as mentioned here: Link
Another suggestion from the comments (thx to gkiely): self-update
Note: self-update is not available. See policies for enforcing versions within a project
In order to update your version of Yarn, run
curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
I solved the problem by changing the StartupType of the ssh-agent to Manual
via Set-Service ssh-agent -StartupType Manual
.
Then I was able to start the service via Start-Service ssh-agent
or just ssh-agent.exe
.
Because of your initialization wrong.
Don't do like this,
MethodName _methodName;
Do like this,
MethodName _methodName = MethodName();
I used these two lines of code in application tag in manifest.xml and it worked.
tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
Source: https://github.com/android/android-ktx/issues/576#issuecomment-437145192
In case you need the []
syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:
[routerLink]="['edit', business._id]"
As for an "about page" with no parameters like yours,
[routerLink]="/about"
or
[routerLink]=['about']
will do the trick.
In your scenario, converting a string to a boolean can be done via something like someString === 'true'
(as was already answered).
However, let me try to address your main issue: dealing with the local storage.
The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.
A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.
The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.
function setItemInStorage(key, item) {
localStorage.setItem(key, JSON.stringify(item));
}
function getItemFromStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
Your example could then be rewritten as:
setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);
And:
if (getItemFromStorage('CheckOutPageReload')) {
const pageLoadParams = getItemFromStorage('CheckOutPageReload');
this.btnLoginNumOne = pageLoadParams[0];
this.btnLoginEdit = pageLoadParams[1];
}
- 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!
In a project of mine I wrap Text
instances around Container
s. This particular code sample features two stacked Text objects.
Here's a code sample.
//80% of screen width
double c_width = MediaQuery.of(context).size.width*0.8;
return new Container (
padding: const EdgeInsets.all(16.0),
width: c_width,
child: new Column (
children: <Widget>[
new Text ("Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 Long text 1 ", textAlign: TextAlign.left),
new Text ("Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2, Long Text 2", textAlign: TextAlign.left),
],
),
);
[edit] Added a width constraint to the container
You can use
nditer
Here I calculated no. of positive and negative coefficients in a logistic regression:
b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
if i>0:
pos_coef=pos_coef+1
else:
neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))
Output:
no. of positive coefficients is : 85035
no. of negative coefficients is : 36199
Step 1 - Open anaconda prompt with administrator privileges.
Step 2 - check pip version pip --version
Step 3 - enter this command
**python -m pip install --upgrade pip**
You are using material library which is part of AndroidX. If you are not aware of AndroidX, please go through this answer.
One app should use either AndroidX or old Android Support libraries. That's why you faced this issue.
For example -
In your gradle, you are using
com.android.support:appcompat-v7
(Part of old --Android Support Library--)com.google.android.material:material
(Part of AndroidX) (AndroidX build artifact of com.android.support:design
)So the solution is to use either AndroidX or old Support Library. I recommend to use AndroidX, because Android will not update support libraries after version 28.0.0. See release notes of Support Library.
Just migrate to AndroidX.Here is my detailed answer to migrate to AndroidX. I am putting here the needful steps from that answer.
Before you migrate, it is strongly recommended to backup your project.
Existing project
New project
Put these flags in your gradle.properties
android.enableJetifier=true
android.useAndroidX=true
Check @Library mappings for equal AndroidX package.
Check @Official page of Migrate to AndroidX
function solution(A = []) {
return (A && A
.filter(num => num > 0)
.sort((a, b) => a - b)
.reduce((acc, curr, idx, arr) =>
!arr.includes(acc + 1) ? acc : curr, 0)
) + 1;
}
solution(); // 1 solution(null); // 1 solution([]); // 1 solution([0, 0, 0]); // 1
I ended up here when searching for ”rxjs download file using post”.
This was my final product. It uses the file name and type given in the server response.
import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
downloadPost(url: string, data: any) {
return ajax({
url: url,
method: 'POST',
responseType: 'blob',
body: data,
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain, */*',
'Cache-Control': 'no-cache',
}
}).pipe(
map(handleDownloadSuccess),
);
}
handleDownloadSuccess(response: AjaxResponse) {
const downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(response.response);
const disposition = response.xhr.getResponseHeader('Content-Disposition');
if (disposition) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
const filename = matches[1].replace(/['"]/g, '');
downloadLink.setAttribute('download', filename);
}
}
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
textAlign
property only works when there is a more space left for the Text
's content. Below are 2 examples which shows when textAlign has impact and when not.
For instance, in this example, it won't have any impact because there is no extra space for the content of the Text
.
Text(
"Hello",
textAlign: TextAlign.end, // no impact
),
If you wrap it in a Container
and provide extra width
such that it has more extra space.
Container(
width: 200,
color: Colors.orange,
child: Text(
"Hello",
textAlign: TextAlign.end, // has impact
),
)
Single method for Reactive Forms
TYPESCRIPT
// All is this method
onPasswordChange() {
if (this.confirm_password.value == this.password.value) {
this.confirm_password.setErrors(null);
} else {
this.confirm_password.setErrors({ mismatch: true });
}
}
// getting the form control elements
get password(): AbstractControl {
return this.form.controls['password'];
}
get confirm_password(): AbstractControl {
return this.form.controls['confirm_password'];
}
HTML
// PASSWORD FIELD
<input type="password" formControlName="password" />
// CONFIRM PASSWORD FIELD
<input type="password" formControlName="confirm_password" (change)="onPasswordChange()" />
// SHOW ERROR IF MISMATCH
<span *ngIf="confirm_password.hasError('mismatch')">Password do not match.</span>
you can use localStorage for storing the json data:
the example is given below:-
let JSONDatas = [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"}
]
localStorage.setItem("datas", JSON.stringify(JSONDatas));
let data = JSON.parse(localStorage.getItem("datas"));
console.log(data);
Replacing CRLF with LF using Notepad++
Rebuild and run the docker image should solve your problem.
While several of the solutions here will work, none handle overlap well and end up moving one item to below the other. If you are trying to layout data that will be dynamically bound you won't know until runtime that it looks bad.
What I like to do is simply create a single row table and apply the right float on the second cell. No need to apply a left-align on the first, that happens by default. This handles overlap perfectly by word-wrapping.
HTML
<table style="width: 100%;">
<tr><td>Left aligned stuff</td>
<td class="alignRight">Right aligned stuff</td></tr>
</table>
CSS
.alignRight {
float: right;
}
SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
Use dev.new()
. (See this related question.)
plot(1:10)
dev.new(width=5, height=4)
plot(1:20)
To be more specific which units are used:
dev.new(width=5, height=4, unit="in")
plot(1:20)
dev.new(width = 550, height = 330, unit = "px")
plot(1:15)
edit additional argument for Rstudio (May 2020), (thanks user Soren Havelund Welling)
For Rstudio, add dev.new(width=5,height=4,noRStudioGD = TRUE)
Try to minimize the use of <br>
as much as you possibly can. HTML is supposed to carry content and structure, <br>
is neither. A simple workaround is to wrap your input elements in <p>
elements, like so:
<form name="publish" id="publish" action="publishprocess.php" method="post">
<p><input type="text" id="title" name="title" size="60" maxlength="110" value="<?php echo $title ?>" /> - Title</p>
<p><input type="text" id="contact" name="contact" size="24" maxlength="30" value="<?php echo $contact ?>" /> - Contact</p>
<p>Task description (you may include task description, requirements on bidders, time requirements, etc):</p>
<p><textarea name="detail" id="detail" rows="7" cols="60" style="font-family:Arial, Helvetica, sans-serif"><?php echo $detail ?></textarea></p>
<p><input type="text" id="price" name="price" size="10" maxlength="20" value="<?php echo $price ?>" /> - Price</p>
<p><input class="tagvalidate" type="text" id="tag" name="tag" size="40" maxlength="60" value="<?php echo $tag ?>" /> - Skill or Knowledge Tags</p>
<p>Combine multiple words into single-words, space to separate up to 3 tags (example:photoshop quantum-physics computer-programming)</p>
<p>District Restriction:<?php echo $locationtext.$cityname; ?></p>
<p><input type="submit" id="submit" value="Submit" /></p>
</form>
This solution works for me, simple and effective (with 126 too)
CONVERT(NVARCHAR(MAX), CAST(GETDATE() as date), 120)
In order to checkout a git tag , you would execute the following command
git checkout tags/tag-name -b branch-name
eg as mentioned below.
git checkout tags/v1.0 -b v1.0-branch
To fetch the all tags use the command
git fetch --all --tags
I would like to add to the answer provided by Sangam Belose. Here's his code:
select ('id') as id, ('time') as time, ('unit') as unit
UNION ALL
SELECT * INTO OUTFILE 'C:/Users/User/Downloads/data.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM sensor
However, if you have not set up your "secure_file_priv"
within the variables, it may not work. For that, check the folder set on that variable by:
SHOW VARIABLES LIKE "secure_file_priv"
The output should look like this:
mysql> show variables like "%secure_file_priv%";
+------------------+------------------------------------------------+
| Variable_name | Value |
+------------------+------------------------------------------------+
| secure_file_priv | C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ |
+------------------+------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
You can either change this variable or change the query to output the file to the default path showing.
If using Python 2.5, you may need to import simplejson
:
try:
import json
except ImportError:
import simplejson as json
Is there any other way to convert that array into string ?
Yes there is. serialize()
. It can convert various data types (including object and arrays) into a string representation which you can unserialize()
at a later time. Serializing an associative array such as Array(18 => 'Somthing')
will preserve both keys and values:
<?php
$a = array(18 => 'Something');
echo serialize($a); // a:1:{i:18;s:9:"Something";}
var_dump(unserialize('a:1:{i:18;s:9:"Something";}')); // array(1) {
// [18]=>
// string(9) "Something"
// }
In ES6 you can do something like this:
function foo(...args) _x000D_
{_x000D_
let [a,b,...c] = args;_x000D_
_x000D_
console.log(a,b,c);_x000D_
}_x000D_
_x000D_
_x000D_
foo(1, null,"x",true, undefined);
_x000D_
For newer versions of Windows (including but not limited to both Windows 10 and Windows Server 2016), the event IDs are:
Locking and unlocking a workstation also involve the following logon and logoff events:
When using a Terminal Services session, locking and unlocking may also involve the following events if the session is disconnected, and event 4778 may replace event 4801:
Events 4800 and 4801 are not audited by default, and must be enabled using either Local Group Policy Editor (gpedit.msc
) or Local Security Policy (secpol.msc
).
The path for the policy using Local Group Policy Editor is:
The path for the policy using Local Security Policy is the following subset of the path for Local Group Policy Editor:
Actually, depth first (or indeed breadth first) search isn't quite enough. You need a sightly more complex algorithm.
For instance, suppose there is graph with nodes {a,b,c,d} and edges {(a,b),(b,c),(b,d),(d,c)} where an edge (x,y) is an edge from x to y. (looks something like this, with all edges directed downwards.)
(a)
|
|
(b)
/ \
(d) |
| |
\ /
(c)
Then doing depth first search may visit node (a), then (b), then (c), then backtrack to (b), then visit (d), and finally visit (c) again and conclude there is a cycle -- when there isn't. A similar thing happens with breadth first.
What you need to do is keep track of which nodes your in the middle of visiting. In the example above, when the algorithm reaches (d) it has finished visiting (c) but not (a) or (b). So revisiting a finished node is fine, but visiting an unfinished node means you have a cycle. The usual way to do this is colour each node white(not yet visited), grey(visiting descendants) or black(finished visiting).
here is some pseudo code!
define visit(node n):
if n.colour == grey: //if we're still visiting this node or its descendants
throw exception("Cycle found")
n.colour = grey //to indicate this node is being visited
for node child in n.children():
if child.colour == white: //if the child is unexplored
visit(child)
n.colour = black //to show we're done visiting this node
return
then running visit(root_node) will throw an exception if and only if there is a cycle (initially all nodes should be white).
mysql -uroot -p -hslavedb.mydomain.com mydb_production -e "select * from users;"
From the usage printout:
-e
,--execute=name
Execute command and quit. (Disables--force
and history file)
If I understand you correctly, you're talking about doing a
svn merge -rn:n-1
to back out of an earlier commit, in which case, you're probably looking for
git revert
select the index then select the ones needed then select sql and click action then click rebuild
Use df[df['B']==3]['A'].values
if you just want item itself without the brackets
And this:
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
suppose to be solution of deprecated:
FirebaseInstanceId.getInstance().getToken()
EDIT
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
can produce exception if the task is not yet completed, so the method witch Nilesh Rathod described (with .addOnSuccessListener
) is correct way to do it.
Kotlin:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
}
Acknowledging the fact that the asker specifically requested jQuery and that the answer selected is correct, it should be noted that this problem doesn't actually need jQuery per say. If one desires to solve this problem without it, one can simply set the onClick
attribute of the checkboxes that he or she wants to add additional functionality to, like so:
HTML:
<form id="myform">
<input type="checkbox" name="check1" value="check1" onClick="cbChanged(this);">
<input type="checkbox" name="check2" value="check2" onClick="cbChanged(this);">
</form>
javascript:
function cbChanged(checkboxElem) {
if (checkboxElem.checked) {
// Do something special
} else {
// Do something else
}
}
Fiddle: http://jsfiddle.net/Y9f66/1/
select convert(varchar(8), getdate(), 3)
simply use this for dd/mm/yy and this
select convert(varchar(8), getdate(), 1)
for mm/dd/yy
Using md5deep
:
md5deep -r FOLDER | awk '{print $1}' | sort | md5sum
According to the FAQ:
Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.
There are two reasons for having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.
I don't necessarily agree with this for various reasons not worth going into. It is what it is, and it's not likely to change in the near future.
For packages, there's the goimports
tool which automatically adds missing packages and removes unused ones. For example:
# Install it
$ go get golang.org/x/tools/cmd/goimports
# -w to write the source file instead of stdout
$ goimports -w my_file.go
You should be able to run this from any half-way decent editor - for example for Vim:
:!goimports -w %
The goimports
page lists some commands for other editors, and you typically set it to be run automatically when you save the buffer to disk.
Note that goimports
will also run gofmt
.
As was already mentioned, for variables the easiest way is to (temporarily) assign them to _
:
// No errors
tasty := "ice cream"
horrible := "marmite"
// Commented out for debugging
//eat(tasty, horrible)
_, _ = tasty, horrible
Adding to Gisheri's answer
Following code worked for me
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
},
markerOptions: {
icon: 'images/beachflag.png'
},
circleOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
//console.log(polygon.overlay.latLngs.j[0].j);return false;
$.each(polygon.overlay.latLngs.j[0].j, function(key, LatLongsObject){
var LatLongs = LatLongsObject;
var lat = LatLongs.k;
var lon = LatLongs.B;
console.log("Lat is: "+lat+" Long is: "+lon); //do something with the coordinates
});
The simple solution given by Jonathan works with a modification to cheat Pandoc. Instead of direct Latex commands such as
\begin{center}
Text
\end{center}
you can define your own commands in the YAML header:
header-includes:
- \newcommand{\bcenter}{\begin{center}}
- \newcommand{\ecenter}{\end{center}}
And then you use:
\bcenter
Text and more
\ecenter
This works for me for centering a whole document with many code chunks and markdown commands in between.
Remove the unwanted , sign in the function. you will get the solution.
Refer this
http://blog.favrik.com/2007/11/29/ie7-error-expected-identifier-string-or-number/
There's no need to use a lib specific API if you use python-benedict
. Just initialize a new instance from your XML and manage it easily since it is a dict
subclass.
Installation is easy: pip install python-benedict
from benedict import benedict as bdict
# data-source can be an url, a filepath or data-string (as in this example)
data_source = """
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>"""
data = bdict.from_xml(data_source)
t_list = data['foo.bar'] # yes, keypath supported
for t in t_list:
print(t['@foobar'])
It supports and normalizes I/O operations with many formats: Base64
, CSV
, JSON
, TOML
, XML
, YAML
and query-string
.
It is well tested and open-source on GitHub. Disclosure: I am the author.
Hope this helps;
df1 = data.frame(CustomerId=c(1:10),
Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))
df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1), rep("Cal", 2)),
like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))
df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))
Assuming df1$Hobby
and df2$like
mean the same thing.
On newer kernels you could also possibly use the the /sys/devices/system/cpu/
interface to get a bit more information:
$ ls /sys/devices/system/cpu/
cpu0 cpufreq kernel_max offline possible present release
cpu1 cpuidle modalias online power probe uevent
$ cat /sys/devices/system/cpu/kernel_max
255
$ cat /sys/devices/system/cpu/offline
2-63
$ cat /sys/devices/system/cpu/possible
0-63
$ cat /sys/devices/system/cpu/present
0-1
$ cat /sys/devices/system/cpu/online
0-1
See the official docs for more information on what all these mean.
Do not use >
; it messes up the character encoding. Use:
Get-Content files.* | Set-Content newfile.file
Considering not letters in the words
public static boolean palindromeWords(String s ){
int left=0;
int right=s.length()-1;
while(left<=right){
while(left<right && !Character.isLetter(s.charAt(left))){
left++;
}
while(right>0 && !Character.isLetter(s.charAt(right))){
right--;
}
if((s.charAt(left++))!=(s.charAt(right--))){
return false;
}
}
return true;
}
———
@Test
public void testPalindromeWords(){
assertTrue(StringExercise.palindromeWords("ece"));
assertTrue(StringExercise.palindromeWords("kavak"));
assertFalse(StringExercise.palindromeWords("kavakdf"));
assertTrue(StringExercise.palindromeWords("akka"));
assertTrue(StringExercise.palindromeWords("??e@@c_--e"));
}
yes - take a look at setInterval
and setTimeout
for executing code at certain times. setInterval would be the one to use to execute code periodically.
See a demo and answer here for usage
In my case, I just put the aar file in libs, and add
dependencies {
...
api fileTree(dir: 'libs', include: ['*.aar'])
...
}
in build.gradle and it works. I think it is similar with default generated dependency:
implementation fileTree(dir: 'libs', include: ['*.jar'])
In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).
Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184
Change the property WindowState
to System.Windows.Forms.FormWindowState.Maximized
, in some cases if the older answers doesn't works.
So the window will be maximized, and the other parts are in the other answers.
use regular expression ...
Regex re = new Regex(@"\d+");
Match m = re.Match("test 66");
if (m.Success)
{
Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
}
else
{
Console.WriteLine("You didn't enter a string containing a number!");
}
Based on the List Members Instance docs, the easiest way is to use a PUT
request which according to the docs either "adds a new list member or updates the member if the email already exists on the list".
Furthermore apikey
is definitely not part of the json schema and there's no point in including it in your json request.
Also, as noted in @TooMuchPete's comment, you can use CURLOPT_USERPWD
for basic http auth as illustrated in below.
I'm using the following function to add and update list members. You may need to include a slightly different set of merge_fields
depending on your list parameters.
$data = [
'email' => '[email protected]',
'status' => 'subscribed',
'firstname' => 'john',
'lastname' => 'doe'
];
syncMailchimp($data);
function syncMailchimp($data) {
$apiKey = 'your api key';
$listId = 'your list id';
$memberId = md5(strtolower($data['email']));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
$json = json_encode([
'email_address' => $data['email'],
'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => [
'FNAME' => $data['firstname'],
'LNAME' => $data['lastname']
]
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.
var optionsPie = {
tooltipTemplate: "<%= label %> - <%= value %>"
}
If you want the tooltip to be always shown you can make some other edits to the options:
var optionsPie = {
tooltipEvents: [],
showTooltips: true,
onAnimationComplete: function() {
this.showTooltip(this.segments, true);
},
tooltipTemplate: "<%= label %> - <%= value %>"
}
In your data items, you have to add the desired label property and value and that's all.
data = [
{
value: 480000,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Tobacco"
}
];
Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie)
and you are done.
This probably works best for pies which are not very small in size.
Integer.toString
calls the static method in the class Integer
. It does not need an instance of Integer
.
If you call new Integer(i)
you create an instance of type Integer
, which is a full Java object encapsulating the value of your int. Then you call the toString
method on it to ask it to return a string representation of itself.
If all you want is to print an int
, you'd use the first one because it's lighter, faster and doesn't use extra memory (aside from the returned string).
If you want an object representing an integer value—to put it inside a collection for example—you'd use the second one, since it gives you a full-fledged object to do all sort of things that you cannot do with a bare int
.
First of all we will make a class that will check the connectivity of the network state. So lets create a class :
public class AppStatus {
private static AppStatus instance = new AppStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static AppStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
}
Now Make a new Broadcast receiver class :
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (AppStatus.getInstance(context).isOnline()) {
Intent intent1=new Intent(context,DisplayAct.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
} else {
Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();
}
}
}
and Now register your broadcast receiver on manifest:
<receiver android:name=".ConnectivityReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model:
public ActionResult Index()
{
var xyzComponent = Request.Headers["xyzComponent"];
var model = new MyModel
{
IsCustomHeaderSet = (xyzComponent != null)
}
return View(model);
}
My attempt - I'd start with the max mark and build from there
Schema:
CREATE TABLE Student (
StudentId int,
Name nvarchar(30),
Details nvarchar(30)
)
CREATE TABLE Subject (
SubjectId int,
Name nvarchar(30)
)
CREATE TABLE Marks (
StudentId int,
SubjectId int,
Mark int
)
Data:
INSERT INTO Student (StudentId, Name, Details)
VALUES (1,'Alfred','AA'), (2,'Betty','BB'), (3,'Chris','CC')
INSERT INTO Subject (SubjectId, Name)
VALUES (1,'Maths'), (2, 'Science'), (3, 'English')
INSERT INTO Marks (StudentId, SubjectId, Mark)
VALUES
(1,1,61),(1,2,75),(1,3,87),
(2,1,82),(2,2,64),(2,3,77),
(3,1,82),(3,2,83),(3,3,67)
GO
My query would have been:
;WITH MaxMarks AS (
SELECT SubjectId, MAX(Mark) as MaxMark
FROM Marks
GROUP BY SubjectId
)
SELECT s.Name as [StudentName], sub.Name AS [SubjectName],m.Mark
FROM MaxMarks mm
INNER JOIN Marks m
ON m.SubjectId = mm.SubjectId
AND m.Mark = mm.MaxMark
INNER JOIN Student s
ON s.StudentId = m.StudentId
INNER JOIN Subject sub
ON sub.SubjectId = mm.SubjectId
Marks
, Student
and Subject
to find the relevant details of that highest markThis also take care of duplicate students with the highest mark
Results:
STUDENTNAME SUBJECTNAME MARK
Alfred English 87
Betty Maths 82
Chris Maths 82
Chris Science 83
This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,
class Myclass {
int a;
class SubClass {
int b;
}
}
With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,
MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String
Now you can pass this String across activities as a StringExtra with the activity intent.
Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);
Then in the receiving activity, create the original object from the string representation.
String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object
It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.
UPDATE
While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.
One new and update answer: Many apps that were removed this October(2018) for the lack of Privacy Policy are unable to receive ads after they get back in Play Store. You must use this form to request a "reset" for that app's ads. https://support.google.com/admob/contact/appeal_policy_violation
Took me a few days to realize and find the answer. Hope you get your ads back.
The solution suggested
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.
A more sensible solution is to include this in your web.config:
<system.webServer>
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
</system.webServer>
Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.
Use the .Select()
after grouping:
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyContractID, // required by your view model. should be omited
// in most cases because group by primary key
// makes no sense.
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyContractID = ac.Key.AgencyContractID,
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Amount = ac.Sum(acs => acs.Amount),
Fee = ac.Sum(acs => acs.Fee)
});
I wrote a shell function for a similar use case I encounter daily on projects. This is basically a shortcut for keeping local branches up to date with a common branch like develop before opening a PR, etc.
Posting this even though you don't want to use
checkout
, in case others don't mind that constraint.
glmh
("git pull and merge here") will automatically checkout branchB
, pull
the latest, re-checkout branchA
, and merge branchB
.
Doesn't address the need to keep a local copy of branchA, but could easily be modified to do so by adding a step before checking out branchB. Something like...
git branch ${branchA}-no-branchB ${branchA}
For simple fast-forward merges, this skips to the commit message prompt.
For non fast-forward merges, this places your branch in the conflict resolution state (you likely need to intervene).
.bashrc
or .zshrc
, etc:glmh() {
branchB=$1
[ $# -eq 0 ] && { branchB="develop" }
branchA="$(git branch | grep '*' | sed 's/* //g')"
git checkout ${branchB} && git pull
git checkout ${branchA} && git merge ${branchB}
}
# No argument given, will assume "develop"
> glmh
# Pass an argument to pull and merge a specific branch
> glmh your-other-branch
Note: This is not robust enough to hand-off of args beyond branch name to
git merge
Nuget Gallery
provides a GUI similar to the full Visual Studio. See below.
How To Use:
Nuget Gallery
from extension marketplace.View > Command Palette
or ??P (Ctrl+Shift+P on Windows and Linux). Type Nuget: Open Gallery
..csproj file
checkbox is selected, select version from dropdown, and click install button.UPDATE
Earlier versions, as noted in the comments, had an issue where the .csproj
checkbox was not visible when a package in the csproj file was missing a version number like below.
<PackageReference Include="Microsoft.AspNetCore.App" />
This has been fixed in newer versions of the extension so if you have an older version with this issue, please update it to the latest version.
php.net says:
Microseconds (added in PHP 5.2.2). Note that
date()
will always generate000000
since it takes an integer parameter, whereasDateTime::format()
does support microseconds ifDateTime
was created with microseconds.
So use as simple:
$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";
Recommended and use dateTime()
class from referenced:
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
print $d->format("Y-m-d H:i:s.u"); // note at point on "u"
Note u
is microseconds (1 seconds = 1000000 µs).
Another example from php.net:
$d2=new DateTime("2012-07-08 11:14:15.889342");
Reference of dateTime()
on php.net
I've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds
A large reason is that video games require direct knowledge of the hardware underneath, often times, and there really is no great implementation for many architectures. It's the knowledge of the underlying hardware architecture that allows developers to squeeze every ounce of performance out of a gaming system. Why would you take the time to port Java to a gaming platform, and then write a game on top of that port when you could just write the game?
edit: this is to say that it's more than a "speed" or "don't have the right libraries" issue. Those two things go hand-in-hand with this, but it's more a matter of "how do I make a system like the cell b.e. run my java code? there aren't really any good java compilers that can manage the pipelines and vectors like i need.."
The solution, as Dennis Smolek said, is dead simple. Set window.location.href
to the URL you want to switch to and it just works.
For example, if you had this method in your component's class file (controller):
goCNN() {
window.location.href='http://www.cnn.com/';
}
Then you could call it quite simply with the appropriate (click)
call on a button (or whatever) in your template:
<button (click)="goCNN()">Go to CNN</button>
Another option if you want greater control over how rows are deemed to be invalid is
final <- final[!(is.na(final$rnor)) | !(is.na(rawdata$cfam)),]
Using the above, this:
gene hsap mmul mmus rnor cfam
1 ENSG00000208234 0 NA NA NA 2
2 ENSG00000199674 0 2 2 2 2
3 ENSG00000221622 0 NA NA 2 NA
4 ENSG00000207604 0 NA NA 1 2
5 ENSG00000207431 0 NA NA NA NA
6 ENSG00000221312 0 1 2 3 2
Becomes:
gene hsap mmul mmus rnor cfam
1 ENSG00000208234 0 NA NA NA 2
2 ENSG00000199674 0 2 2 2 2
3 ENSG00000221622 0 NA NA 2 NA
4 ENSG00000207604 0 NA NA 1 2
6 ENSG00000221312 0 1 2 3 2
...where only row 5 is removed since it is the only row containing NAs for both rnor
AND cfam
. The boolean logic can then be changed to fit specific requirements.
This might help someone:
I am installing the latest Java on my system for development, and currently it's Java SE 7. Now, let's dive into this "madness", as you put it...
All of these are the same (when developers are talking about Java for development):
Starting with Java v1.5:
And we can assume this will remain for future versions.
Next, for developers, download JDK, not JRE.
JDK will contain JRE. If you need JDK and JRE, get JDK. Both will be installed from the single JDK install, as you will see below.
As someone above mentioned:
Here's the step by step links I followed (one step leads to the next, this is all for a single download) to download Java for development (JDK):
Keep in mind the above links are for reference purposes only, to show you the step by step method of what it takes to download the JDK.
And install with default settings to:
Remember from above that JDK contains JRE, which makes sense if you know what they both are. Again, see above.
After your install, double check “C:\Program Files\Java” to see both these folders. Now you know what they are and why they are there.
I know I wrote this for newbies, but I enjoy knowing things in full detail, so I hope this helps.
Just want to point out that in case you have a MemoryStream you already have memorystream.ToArray()
for that.
Also, if you are dealing with streams of unknown or different subtypes and you can receive a MemoryStream
, you can relay on said method for those cases and still use the accepted answer for the others, like this:
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
// Jon Skeet's accepted answer
return ReadFully(stream);
}
}
For example, I get date/time in format Spanish.
$('#timePicker').datetimepicker({
defaultDate: new Date(),
format:'DD/MM/YYYY HH:mm'
});
You can always access child views via View.findViewById() http://developer.android.com/reference/android/view/View.html#findViewById(int).
For example, within an activity / view:
...
private void init() {
View child1 = findViewById(R.id.child1);
}
...
or if you have a reference to a view:
...
private void init(View root) {
View child2 = root.findViewById(R.id.child2);
}
Add an id column to the csv file and leave it blank:
id,Name,Address
,name1,addr test 1
,name2,addr test 2
Remove KEEPIDENTITY keyword from query:
BULK INSERT Employee FROM 'path\tempFile.csv '
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');
The id identity field will be auto-incremented.
If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.
Writing JSON Parser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject
and looping through each json item. Below i am creating an instance of JSONParser
class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
some_view.xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackgroundBorderless"
android:focusable="true"
android:src="@drawable/up_arrow"
android:theme="@style/SomeButtonTheme"/>
some_style.xml
<style name="SomeButtonTheme" >
<item name="colorControlHighlight">@color/someColor</item>
</style>
Context is a reference to the current object as this. Also context allows access to information about the application environment.
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);
that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)
There's an easier way to think about this. Start with 1 bit. This can obviously represent 2 values (0 or 1). What happens when we add a bit? We can now represent twice as many values: the values we could represent before with a 0 appended and the values we could represent before with a 1 appended.
So the the number of values we can represent with n bits is just 2^n (2 to the power n)
Private Sub CommandButton1_Click()
Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption
Me.Hide
Run "filename"
End Sub
Private Sub MUN_Change()
Dim r As Integer
r = 2
While Range("m" & CStr(r)).Value <> ""
If Range("m" & CStr(r)).Value = MUN.Text Then
Label5.Caption = Range("n" & CStr(r)).Value
End If
r = r + 1
Wend
End Sub
Private Sub PROV_Change()
If PROV.Text = "LAGUNA" Then
MUN.Text = ""
MUN.RowSource = "Menu!M26:M56"
ElseIf PROV.Text = "CAVITE" Then
MUN.Text = ""
MUN.RowSource = "Menu!M2:M25"
ElseIf PROV.Text = "QUEZON" Then
MUN.Text = ""
MUN.RowSource = "Menu!M57:M97"
End If
End Sub
I know this thread is somewhat old, but there are a lot of really hacky answers on here, so I'd like to provide something that is a lot simpler and a lot cleaner:
select {
overflow-y: auto;
}
As you can see in this fiddle, this solution provides you with flexibility if you don't know the exact number of select options you are going to have. It hides the scrollbar in the case that you don't need it without hiding possible extra option elements in the other case. Don't do all this hacky overlapping div
stuff. It just makes for unreadable markup.
This can be done for a normal subview
inside a larger UIView
, but it doesn't work automatically for headerViews
. The height of a headerView
is determined by what's returned by tableView:heightForHeaderInSection:
so you have to calculate the height
based on the height
of the UILabel
plus space for the UIButton
and any padding
you need. You need to do something like this:
-(CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
NSString *s = self.headeString[indexPath.section];
CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 60;
}
Here headerString
is whatever string you want to populate the UILabel
, and the 281 number is the width
of the UILabel
(as setup in Interface Builder
)
You do this by using mysqli_fetch_field
method.
session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
$value = mysqli_fetch_field($result);
$_SESSION['myid'] = $value;
}
Note: you can do that by using mysql_fetch_field()
method as well, but it will be deprecated in php v5.5
Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.
Hope this example helps too
I have done java coding in a similar way for the below json array example as follows :
following is the json data format : stored as "EMPJSONDATA.json"
[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},
{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},
{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}
{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]
public class Jsonminiproject {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
for (Object o : a)
{
JSONObject employee = (JSONObject) o;
Long no = (Long) employee.get("EMPNO");
System.out.println("Employee Number : " + no);
String st = (String) employee.get("EMP_NAME");
System.out.println("Employee Name : " + st);
String dob = (String) employee.get("DOB");
System.out.println("Employee DOB : " + dob);
String doj = (String) employee.get("DOJ");
System.out.println("Employee DOJ : " + doj);
String role = (String) employee.get("ROLE");
System.out.println("Employee Role : " + role);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// abobjects.com, parvez ahmad ab bulk mailer
use below script
function isValidCreditCard2(type, ccnum) {
if (type == "Visa") {
// Visa: length 16, prefix 4, dashes optional.
var re = /^4\d{3}?\d{4}?\d{4}?\d{4}$/;
} else if (type == "MasterCard") {
// Mastercard: length 16, prefix 51-55, dashes optional.
var re = /^5[1-5]\d{2}?\d{4}?\d{4}?\d{4}$/;
} else if (type == "Discover") {
// Discover: length 16, prefix 6011, dashes optional.
var re = /^6011?\d{4}?\d{4}?\d{4}$/;
} else if (type == "AmEx") {
// American Express: length 15, prefix 34 or 37.
var re = /^3[4,7]\d{13}$/;
} else if (type == "Diners") {
// Diners: length 14, prefix 30, 36, or 38.
var re = /^3[0,6,8]\d{12}$/;
}
if (!re.test(ccnum)) return false;
return true;
/*
// Remove all dashes for the checksum checks to eliminate negative numbers
ccnum = ccnum.split("-").join("");
// Checksum ("Mod 10")
// Add even digits in even length strings or odd digits in odd length strings.
var checksum = 0;
for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
checksum += parseInt(ccnum.charAt(i-1));
}
// Analyze odd digits in even length strings or even digits in odd length strings.
for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
var digit = parseInt(ccnum.charAt(i-1)) * 2;
if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
}
if ((checksum % 10) == 0) return true; else return false;
*/
}
jQuery.validator.addMethod("isValidCreditCard", function(postalcode, element) {
return isValidCreditCard2($("#cardType").val(), $("#cardNum").val());
}, "<br>credit card is invalid");
Type</td>
<td class="text"> <form:select path="cardType" cssclass="fields" style="border: 1px solid #D5D5D5;padding: 0px 0px 0px 0px;width: 130px;height: 22px;">
<option value="SELECT">SELECT</option>
<option value="MasterCard">Mastercard</option>
<option value="Visa">Visa</option>
<option value="AmEx">American Express</option>
<option value="Discover">Discover</option>
</form:select> <font color="#FF0000">*</font>
$("#signupForm").validate({
rules:{
companyName:{required: true},
address1:{required: true},
city:{required: true},
state:{required: true},
zip:{required: true},
country:{required: true},
chkAgree:{required: true},
confPassword:{required: true},
lastName:{required: true},
firstName:{required: true},
ccAddress1:{required: true},
ccZip:{
postalcode : true
},
phone:{required: true},
email:{
required: true,
email: true
},
userName:{
required: true,
minlength: 6
},
password:{
required: true,
minlength: 6
},
cardNum:{
isValidCreditCard : true
},
Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:
REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"
You'll see an output like :
0 REG_SZ Lucida Console
00 REG_SZ Consolas
936 REG_SZ *???
932 REG_SZ *MS ????
Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"
Now we implement UTF-8 support:
REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f
Set default font to "Courier New":
REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f
Set font size to 20 :
REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f
Enable quick edit if you like :
REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f
var args = [ 'p0', 'p1', 'p2' ];
function call_me (param0, param1, param2 ) {
// ...
}
// Calling the function using the array with apply()
call_me.apply(this, args);
And here a link to the original post that I personally liked for its readability
I found this example and incorporated it into a function:
public static int solution1(int A, int B)
{
// Check if A and B are in [0...999,999,999]
if ( (A >= 0 && A <= 999999999) && (B >= 0 && B <= 999999999))
{
if (A == 0 && B == 0)
{
return 0;
}
// Make sure A < B
if (A < B)
{
// Convert A and B to strings
string a = A.ToString();
string b = B.ToString();
int index = 0;
// See if A is a substring of B
if (b.Contains(a))
{
// Find index where A is
if (b.IndexOf(a) != -1)
{
while ((index = b.IndexOf(a, index)) != -1)
{
Console.WriteLine(A + " found at position " + index);
index++;
}
Console.ReadLine();
return b.IndexOf(a);
}
else
return -1;
}
else
{
Console.WriteLine(A + " is not in " + B + ".");
Console.ReadLine();
return -1;
}
}
else
{
Console.WriteLine(A + " must be less than " + B + ".");
// Console.ReadLine();
return -1;
}
}
else
{
Console.WriteLine("A or B is out of range.");
//Console.ReadLine();
return -1;
}
}
static void Main(string[] args)
{
int A = 53, B = 1953786;
int C = 78, D = 195378678;
int E = 57, F = 153786;
solution1(A, B);
solution1(C, D);
solution1(E, F);
Console.WriteLine();
}
Returns:
53 found at position 2
78 found at position 4
78 found at position 7
57 is not in 153786
If you're running PHP 5.3+ this will do the trick, place it at the topmost of your page:
if (get_magic_quotes_gpc() === 1)
{
$_GET = json_decode(stripslashes(json_encode($_GET, JSON_HEX_APOS)), true);
$_POST = json_decode(stripslashes(json_encode($_POST, JSON_HEX_APOS)), true);
$_COOKIE = json_decode(stripslashes(json_encode($_COOKIE, JSON_HEX_APOS)), true);
$_REQUEST = json_decode(stripslashes(json_encode($_REQUEST, JSON_HEX_APOS)), true);
}
Handles keys, values and multi-dimensional arrays.
It seems ridiculous that you can't set/reset an identity column with a single command to cover both cases of whether or not the table has had records inserted. I couldn't understand the behavior I was experiencing until I stumbled across this question on SO!
My solution (ugly but works) is to explicitly check the sys.identity_columns.last_value
table (which tells you whether or not the table has had records inserted) and call the appropriate DBCC CHECKIDENT
command in each case. It is as follows:
DECLARE @last_value INT = CONVERT(INT, (SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MyTable'));
IF @last_value IS NULL
BEGIN
-- Table newly created and no rows inserted yet; start the IDs off from 1
DBCC CHECKIDENT ('MyTable', RESEED, 1);
END
ELSE
BEGIN
-- Table has rows; ensure the IDs continue from the last ID used
DECLARE @lastValUsed INT = (SELECT ISNULL(MAX(ID),0) FROM MyTable);
DBCC CHECKIDENT ('MyTable', RESEED, @lastValUsed);
END
You can replace those in your Manifest application tag:
<application
tools:replace="android:icon, android:label, android:theme, android:name,android:allowBackup"
android:allowBackup="false"...>
and will work for you.
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
**The activity should implements LocationListener
In onCreate(), write the following code **
Boolean network = haveNetworkConnection();
Log.e("network", "---------->" + network);
if (!network) {
Toast.makeText(getApplicationContext(), "Network is not available",
3000).show();
}
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
&& !locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
TextView title = new TextView(context);
title.setText("Location Services Not Active");
title.setBackgroundColor(Color.BLACK);
title.setPadding(10, 15, 15, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(22);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCustomTitle(title);
// builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("Turn on",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface,
int i) {
// Show location settings when the user acknowledges
// the alert dialog
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
builder.show();
}
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location == null) {
Toast.makeText(getApplicationContext(), "GPS signal not found",
3000).show();
}
if (location != null) {
Log.e("locatin", "location--" + location);
Log.e("latitude at beginning",
"@@@@@@@@@@@@@@@" + location.getLatitude());
onLocationChanged(location);
}
Write a method haveNetworkConnection
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Current LOC")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
The list from 2020-05-23 is:
31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22
The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:
whois -h whois.radb.net -- '-i origin AS32934' | grep ^route
For those who get Package not found
error try sudo apt-get install php7-intl
then run composer install
in your project directory.
Windows : ctrl + F12
MacOS : cmd + F12
Above commands will show the functions/methods in the current class.
Press SHIFT TWO times if you want to search both class and method in the whole project.
For a side note, I personally use [Foo new]
if I want something in init to be done without using it's return value anywhere. If you do not use the return of [[Foo alloc] init]
anywhere then you will get a warning. More or less, I use [Foo new]
for eye candy.
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
For preventing naming conflicts, only import the variables that you need:
variableInFile () {
variable="${1}"
file="${2}"
echo $(
source "${file}";
eval echo \$\{${variable}\}
)
}
For getting straight to "who is blocked/blocking" I combined/abbreviated sp_who and sp_lock into a single query which gives a nice overview of who has what object locked to what level.
--Create Procedure WhoLock
--AS
set nocount on
if object_id('tempdb..#locksummary') is not null Drop table #locksummary
if object_id('tempdb..#lock') is not null Drop table #lock
create table #lock ( spid int, dbid int, objId int, indId int, Type char(4), resource nchar(32), Mode char(8), status char(6))
Insert into #lock exec sp_lock
if object_id('tempdb..#who') is not null Drop table #who
create table #who ( spid int, ecid int, status char(30),
loginame char(128), hostname char(128),
blk char(5), dbname char(128), cmd char(16)
--
, request_id INT --Needed for SQL 2008 onwards
--
)
Insert into #who exec sp_who
Print '-----------------------------------------'
Print 'Lock Summary for ' + @@servername + ' (excluding tempdb):'
Print '-----------------------------------------' + Char(10)
Select left(loginame, 28) as loginame,
left(db_name(dbid),128) as DB,
left(object_name(objID),30) as object,
max(mode) as [ToLevel],
Count(*) as [How Many],
Max(Case When mode= 'X' Then cmd Else null End) as [Xclusive lock for command],
l.spid, hostname
into #LockSummary
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and l.status='GRANT'
group by dbID, objID, l.spid, hostname, loginame
Select * from #LockSummary order by [ToLevel] Desc, [How Many] Desc, loginame, DB, object
Print '--------'
Print 'Who is blocking:'
Print '--------' + char(10)
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, p.loginame
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM master..sysprocesses p
JOIN master..sysdatabases d ON p.dbid = d.dbid
WHERE EXISTS ( SELECT 1
FROM master..sysprocesses p2
WHERE p2.blocked = p.spid )
Print '--------'
Print 'Details:'
Print '--------' + char(10)
Select left(loginame, 30) as loginame, l.spid,
left(db_name(dbid),15) as DB,
left(object_name(objID),40) as object,
mode ,
blk,
l.status
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and blk <>0
Order by mode desc, blk, loginame, dbID, objID, l.status
(For what the lock level abbreviations mean, see e.g. https://technet.microsoft.com/en-us/library/ms175519%28v=sql.105%29.aspx)
Copied from: sp_WhoLock – a T-SQL stored proc combining sp_who and sp_lock...
NB the [Xclusive lock for command] column can be misleading -- it shows the current command for that spid; but the X lock could have been triggered by an earlier command in the transaction.
While its true that git commits don't have a specific field called "username", a git repo does have users, and the users do have names. ;) If what you want is the github username, then knittl's answer is right. But since your question asked about git cli and not github, here's how you get a git user's email address using the command line:
To see a list of all users in a git repo using the git cli:
git log --format="%an %ae" | sort | uniq
To search for a specific user by name, e.g., "John":
git log --format="%an %ae" | sort | uniq | grep -i john
Warning: This might inflate executable file size a little bit and cost a little runtime performance. IMO, this would be better if golang has such feature like macro or function decorator.
If you want to mock functions without changing its API, the easiest way is to change the implementation a little bit:
func getPage(url string) string {
if GetPageMock != nil {
return GetPageMock()
}
// getPage real implementation goes here!
}
func downloader() {
if GetPageMock != nil {
return GetPageMock()
}
// getPage real implementation goes here!
}
var GetPageMock func(url string) string = nil
var DownloaderMock func() = nil
This way we can actually mock one function out of the others. For more convenient we can provide such mocking boilerplate:
// download.go
func getPage(url string) string {
if m.GetPageMock != nil {
return m.GetPageMock()
}
// getPage real implementation goes here!
}
func downloader() {
if m.GetPageMock != nil {
return m.GetPageMock()
}
// getPage real implementation goes here!
}
type MockHandler struct {
GetPage func(url string) string
Downloader func()
}
var m *MockHandler = new(MockHandler)
func Mock(handler *MockHandler) {
m = handler
}
In test file:
// download_test.go
func GetPageMock(url string) string {
// ...
}
func TestDownloader(t *testing.T) {
Mock(&MockHandler{
GetPage: GetPageMock,
})
// Test implementation goes here!
Mock(new(MockHandler)) // Reset mocked functions
}
this sorting funciton can be use for all object sorting,
object
deepObject
you can also do assending or desending sort by passing 1,-1 as param
Object.defineProperty(Object.prototype, 'deepVal', {_x000D_
enumerable: false,_x000D_
writable: true,_x000D_
value: function (propertyChain) {_x000D_
var levels = propertyChain.split('.');_x000D_
parent = this;_x000D_
for (var i = 0; i < levels.length; i++) {_x000D_
if (!parent[levels[i]])_x000D_
return undefined;_x000D_
parent = parent[levels[i]];_x000D_
}_x000D_
return parent;_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
function dynamicSortAll(property,sortOrders=1) {_x000D_
_x000D_
/**default sorting will be ascending order if you need descending order_x000D_
sording you have to pass -1 as param**/_x000D_
_x000D_
var sortOrder = sortOrders;_x000D_
_x000D_
return function (a,b) {_x000D_
_x000D_
var result =(property? ((a.deepVal(property) > b.deepVal(property)) ? 1 : (a.deepVal(property) < b.deepVal(property)) ? -1 : 0) :((a > b) ? 1 : (a < b) ? -1 : 0))_x000D_
_x000D_
return result * sortOrder;_x000D_
_x000D_
_x000D_
}_x000D_
}_x000D_
_x000D_
deepObj = [_x000D_
{_x000D_
a: { a: 1, b: 2, c: 3 },_x000D_
b: { a: 4, b: 5, c: 6 }_x000D_
},_x000D_
{ _x000D_
a: { a: 3, b: 2, c: 1 },_x000D_
b: { a: 6, b: 5, c: 4 }_x000D_
}];_x000D_
_x000D_
let deepobjResult=deepObj.sort(dynamicSortAll('a.a',1))_x000D_
console.log('deepobjResult :'+ JSON.stringify(deepobjResult))_x000D_
var obj = [ _x000D_
{ first_nom: 'Lazslo', last_nom: 'Jamf' },_x000D_
{ first_nom: 'Pig', last_nom: 'Bodine' },_x000D_
{ first_nom: 'Pirate', last_nom: 'Prentice' }_x000D_
];_x000D_
let objResult=obj.sort(dynamicSortAll('last_nom',1))_x000D_
console.log('objResult :'+ JSON.stringify(objResult))_x000D_
_x000D_
var numericObj=[1,2,3,4,5,6]_x000D_
_x000D_
let numResult=numericObj.sort(dynamicSortAll(null,-1))_x000D_
console.log('numResult :'+ JSON.stringify(numResult))_x000D_
_x000D_
let stringSortResult='helloworld'.split('').sort(dynamicSortAll(null,1))_x000D_
_x000D_
console.log('stringSortResult:'+ JSON.stringify(stringSortResult))_x000D_
_x000D_
let uniqueStringOrger=[...new Set(stringSortResult)]; _x000D_
console.log('uniqueStringOrger:'+ JSON.stringify(uniqueStringOrger))
_x000D_
If your images are small, consider storing them as base64 in a plain text field.
The reason is that while base64 has an overhead of 33%, with compression that mostly goes away. (See What is the space overhead of Base64 encoding?) Your database will be bigger, but the packets your webserver sends to the client won't be. In html, you can inline base64 in an <img src=""> tag, which can possibly simplify your app because you won't have to serve up the images as binary in a separate browser fetch. Handling images as text also simplifies things when you have to send/receive json, which doesn't handle binary very well.
Yes, I understand you could store the binary in the database and convert it to/from text on the way in and out of the database, but sometimes ORMs make that a hassle. It can be simpler just to treat it as straight text just like all your other fields.
This is definitely the right way to handle thumbnails.
(OP's images are not small, so this is not really an answer to his question.)
First you need to import svg
files by following simple steps.
If image is available in your computer
then select local svg
file.
After that select the image path
and an option to change the size of the image is also available at the right side of dialog if you want to .
in this way svg
image is imported in your project
After that for using this image use the same procedure
@drawable/yourimagename
find
will find all files that match a pattern:
find . -name "*foo"
However, if you want a picture:
tree -P "*foo"
Hope this helps!
In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:
If your mysql was previously working and has stopped suddenly just "reboot" the server.
Was facing this issue on my CentOS VPS.->
Was constantly getting
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'(2)
Tried all techniques, finally restarting the server fixed the issues ->
shutdown -r now
Hope this helps !!
It's not a programmatic solution but you can run
java -verbose:class ....
and the JVM will dump out what it's loading, and from where.
[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]
[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
See here for more details.
Starting with TypeScript 2.2 using dot notation to access indexed properties is allowed. You won't get error TS2339 on your example.
See Dotted property for types with string index signatures in TypeScript 2.2 release note.
Adding @Manbroski answer here that worked for me:
try Ctrl-Shift-P
Editor: Toggle Soft Tabs
From the man
page:
-d delim The first character of delim is used to terminate the input line, rather than newline.
You are using -d,
which will terminate the input line on the comma. It will not read the rest of the line. That's why $y is empty.
I just encountered the same issue after adding the bin folder to .gitignore, not sure if that caused the issue.
I solved it by going to Project/Properties/Build Path and I removed the scr folder and added it again.
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
have you tried this?
-
name: Jack
age: 32
-
name: Claudia
age: 25
I get this: [{"name"=>"Jack", "age"=>32}, {"name"=>"Claudia", "age"=>25}]
(I use the YAML
Ruby class).
Basically you can sort arrays with method sort, but if you want to sort objects then you have to pass function to sort method of array, so I will give you an example using your array
user = [{
bio: "<null>",
email: "[email protected]",
firstname: 'Anna',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "[email protected]",
firstname: 'Senad',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "[email protected]",
firstname: 'Muhamed',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
}];
var ar = user.sort(function(a, b)
{
var nA = a.firstname.toLowerCase();
var nB = b.firstname.toLowerCase();
if(nA < nB)
return -1;
else if(nA > nB)
return 1;
return 0;
});
In case you use jQuery you need to wait for $(window).load
, because the embedded SVG document might not be yet loaded at $(document).ready
$(window).load(function () {
//alert("Document loaded, including graphics and embedded documents (like SVG)");
var a = document.getElementById("alphasvg");
//get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
//get the inner element by id
var delta = svgDoc.getElementById("delta");
delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});
I know I'm a bit late for that one, but I'll share what I did too, in case it helps someone else :
HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
String key = entry.getKey();
HashMap value = entry.getValue();
// do what you have to do here
// In your case, another loop.
}
If you use MAMP, make sure it's started. :)
I just ran into this problem, and after starting MAMP the error went away. Not my finest moment.
When you really want to write an i-test for a spring data repository you can do it like this:
@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories(basePackageClasses = WebBookingRepository.class)
@EntityScan(basePackageClasses = WebBooking.class)
public class WebBookingRepositoryIntegrationTest {
@Autowired
private WebBookingRepository repository;
@Test
public void testSaveAndFindAll() {
WebBooking webBooking = new WebBooking();
webBooking.setUuid("some uuid");
webBooking.setItems(Arrays.asList(new WebBookingItem()));
repository.save(webBooking);
Iterable<WebBooking> findAll = repository.findAll();
assertThat(findAll).hasSize(1);
webBooking.setId(1L);
assertThat(findAll).containsOnly(webBooking);
}
}
To follow this example you have to use these dependencies:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
An alternative one liner:
((((y % 4) + (int((y - (y % 100)) / y) * ((y % 400) / 100))) - 1) < 0)
This was something that I put together for fun (?) that is also 1:1 compatible with C.
(y % 4)
>>>It first checks if the year is a leap year via the typical mod-4 check.
(int((y - (y % 100)) / y)
>>>It then accounts for those years divisible by 100. If the year is evenly divisible by 100, this will result in a value of 1, otherwise it will result in a value of 0.
((y % 400) / 100)))
>>>Next, the year is divided by 400 (and subsequently 100, to return 1, 2, or 3 if it is not.
These two values
(int(y - (y % 100)) / y)
&
((y % 400) / 100)))
are then multiplied together. If the year is not divisible by 100, this will always equal 0, otherwise if it is divisible by 100, but not by 400, it will result in 1, 2, or 3. If it is divisible by both 100 and 400, it will result in 0.
This value is added to (y % 4)
, which will only be equal to 0 if the year is a leap year after accounting for the edge-cases.
Finally, 1 is subtracted from this remaining value, resulting in -1 if the year is a leap year, and either 0, 1, or 2 if it is not. This value is compared against 0 with the less-than operator. If the year is a leap year this will result in True (or 1, if used in C), otherwise it will return False (or 0, if used in C).
Please note: this code is horribly inefficient, incredibly unreadable, and a detriment to any code attempting to follow proper practices. This was an exercise of mine to see if I could do so, and nothing more.
Further, be aware that ZeroDivisionErrors are a consequence of the input year equaling 0, and must be accounted for.
For example, a VERY basic timeit comparison of 1000 executions shows that, when compared against an equivalent codeblock utilizing simple if-statements and the modulus operator, this one-liner is roughly 5 times slower than its if-block equivalent.
That being said, I do find it highly entertaining!
In Bootstrap.css change the background attribute (position
) of Modal from fixed
to absolute
No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.
For negative infinity:
-math.inf
For positive infinity (just for the sake of completeness):
math.inf
You can also combine the two env_keep
statements in Ahmed Aswani's answer into a single statement like this:
Defaults env_keep += "http_proxy https_proxy"
You should also consider specifying env_keep
for only a single command like this:
Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"
To go twice as fast by using multiple processor cores HPCsharp nuget package provides:
list.ToArrayPar();
Add following line in you .bashrc file
############################
# Environment path setting #
############################
export PATH=/c/Python27:/c/Python27/Scripts:$PATH
If you have selective revisions to merge, say A, C, F, J from A,B,C,D,E,F,G,H,I,J commits, simply use below command:
git cherry-pick A C F J
$("#button").click(function () {
$("#frame").attr("src", "http://www.example.com/");
});
HTML:
<div id="mydiv">
<iframe id="frame" src="" width="100%" height="300">
</iframe>
</div>
<button id="button">Load</button>
We have a react application and our development machines are both mac and pc. The start command doesn't work for PC so here is how we got around it:
"start": "PORT=3001 react-scripts start",
"start-pc": "set PORT=3001&& react-scripts start",
On my mac:
npm start
On my pc:
npm run start-pc
The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.
One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.
String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);
However, I would not suggest the above method. You should really be using a List<String>
. Lists allow you to add and remove items from any index. That would look similar to the following:
List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item
There's a new API introduced in API 19 (KitKat): ActivityManager.clearApplicationUserData().
I highly recommend using it in new applications:
import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
.clearApplicationUserData(); // note: it has a return value!
} else {
// use old hacky way, which can be removed
// once minSdkVersion goes above 19 in a few years.
}
If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.
Knowledge of this method is mandatory for anyone using android:manageSpaceActivity
.
Whenever I use this, I do so from a manageSpaceActivity
which has android:process=":manager"
. There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.
private static void killProcessesAround(Activity activity) throws NameNotFoundException {
ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
String myProcessPrefix = activity.getApplicationInfo().processName;
String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
android.os.Process.killProcess(proc.pid);
}
}
}
An instance is probably still running. This will fix it.
killall node
Update: This command will only work on Linux/Ubuntu & Mac.
Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:
sudo apt install vlc ffmpeg
In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.
I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.
You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:
ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'
For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:
ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554
Check the User-Agent and in case it's Mobile Safari, open a myprotocol:// URL to (attempt) to open the iPhone app and have it open Mobile iTunes to the download of the app in case the attempt fails
This sounds a reasonable approach to me, but I don't think you'll be able to get it to open mobile itunes as a second resort. I think you'll have to pick one or the other - either redirect to your app or to itunes.
i.e. if you redirect to myprotocol://, and the app isn't on the phone, you won't get a second chance to redirect to itunes.
You could perhaps first redirect to an (iphone optimised) landing page and give the user the option to click through to your app, or to itunes to get the app if they don't have it? But, you'll be relying on the user to do the right thing there. (Edit: though you could set a cookie so that is a first-time thing only?)
There is already a correct answer from Adam, but you have another option to refactor your code:
if (Age.GetValueOrDefault() == 0)
{
// it's null or 0
}
And what about trying not to delete but hide that row?
there are lots of compression methods that work recursively command line and its good to know who the end audience is.
i.e. if it is to be sent to someone running windows then zip would probably be best:
zip -r file.zip folder_to_zip
unzip filenname.zip
for other linux users or your self tar is great
tar -cvzf filename.tar.gz folder
tar -cvjf filename.tar.bz2 folder # even more compression
#change the -c to -x to above to extract
One must be careful with tar and how things are tarred up/extracted, for example if I run
cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd
pwd
/home/myusername
tar -xvzf passwd.tar.gz
this will create /home/myusername/etc/passwd
unsure if all versions of tar do this:
Removing leading `/' from member names
I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:
"undefined is not a function"
I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.
@MvcHtmlString.Create(
@SquishIt.Framework.Bundle.JavaScript()
.Add("~/Scripts/Libraries/jquery-1.8.2.min.js")
.Add("~/Scripts/Libraries/jquery-ui-1.9.1.custom.min.js")
.Add("~/Scripts/Libraries/jquery.unobtrusive-ajax.min.js")
.Add("~/Scripts/Libraries/jquery.validate.js")
.Add("~/Scripts/Libraries/jquery.validate.unobtrusive.js")
... more files
I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as @Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you're bundling with.
SAP is really a big Company that offers incredible solutions oriented to medium-large companies.
Actually, I can say that the main IT products are: ERP, WEB, Human Resources, Integration, BI, Reports, Machine Learning, Mobile, Cloud, Robotics, and so on.
On the cloud, you can even find solutions using Cloud Foundry, NodeJS, HTML5, Java, etc.
It's really huge the solutions that offers to their customers.
I have been fighting the same thing for a while.
after all the research, this is the best solution.....
add the following to your resolve.conf file /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4
https://serverfault.com/questions/717226/ubuntu14-04-unable-to-apt-get-update/771826#771826
Try WooCommerce Product Filter, plugin developed by Mihajlovicnenad.com. You can filter your products by any criteria. Also, it integrates with your Shop and archive pages perfectly. Here is a screenshot. And this is just one of the layouts, you can customize and make your own. Look at demo site. Thanks!
because your jQuery code is wrong. Correctly would be:
var theParent = $(this).parent().get(0);
$(theParent).css('z-index', 3000);
This can also be set in the configuration file matplotlibrc
(as explained in the error message), for instance:
# The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
backend : Agg
That way, the backend does not need to be hardcoded if the code is shared with other people. For more information, check the documentation.
The previous answers are all correct. I go one step further and make C# work for me by defining an extension method on String:
public static class Extensions
{
public static string[] Split(this string toSplit, string splitOn) {
return toSplit.Split(new string[] { splitOn }, StringSplitOptions.None);
}
}
That way I can call it on any string in the simple way I naively expected the first time I tried to accomplish this:
"a big long string with stuff to split on".Split("g str");
For setting the Socket timeout, you need to follow these steps:
import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.
To stop a service, you have to find service name using:
adb shell dumpsys activity services <your package>
for example: adb shell dumpsys activity services com.xyz.something
This will list services running for your package.
Output should be similar to:
ServiceRecord{xxxxx u0 com.xyz.something.beta/xyz.something.abc.XYZService}
Now select your service and run:
adb shell am stopservice <service_name>
For example:
adb shell am stopservice com.xyz.something.beta/xyz.something.abc.XYZService
similarly, to start service:
adb shell am startservice <service_name>
To access service, your service(in AndroidManifest.xml) should set exported="true"
<!-- Service declared in manifest -->
<service
android:name=".YourServiceName"
android:exported="true"
android:launchMode="singleTop">
<intent-filter>
<action android:name="com.your.package.name.YourServiceName"/>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
I think you can remove all your log with switch from full to simple recovery. Right click on your Database and select Properties
and select Options
and change
Recovery mode
to Simple
Containment type
to None
I use supervisor to run Nginx and Gunicorn side by side on a Docker container.
This was the configuration used for supervisor :
[supervisord]
nodaemon=true
[program:gunicorn]
command = /project/start.sh
user = www-data
[program:nginx]
command=/usr/sbin/nginx
The problem was how I launched Ngnix : by default it runs on the foreground. This makes supervise retry to run another instance of Nginx.
By adding -g 'daemon off;'
to the command line, Nginx stayed in the foreground, supervisor stopped trying to run another instance.
To summarize the excellent detailed explanations above, and in the simplest way I can think of, this is due to the limitations of the JVM built-in monitor, which 1) is acquired on the entire synchronization unit (block or object) and 2) does not discriminate about the specific condition being waited/notified on/about.
This means that if multiple threads are waiting on different conditions and notify() is used, the selected thread may not be the one which would make progress on the newly fulfilled condition - causing that thread (and other currently still waiting threads which would be able to fulfill the condition, etc..) not to be able to make progress, and eventually starvation or program hangup.
In contrast, notifyAll() enables all waiting threads to eventually re-acquire the lock and check for their respective condition, thereby eventually allowing progress to be made.
So notify() can be used safely only if any waiting thread is guaranteed to allow progress to be made should it be selected, which in general is satisfied when all threads within the same monitor check for only one and the same condition - a fairly rare case in real world applications.
Does not work if you have nulls.
You can get around this by modifying your select statement to plop something into nulls:
phonenumber = CASE
WHEN (isnull(phonenumber, '')='') THEN '(blank)'
ELSE phonenumber
END
anotherfunc(*extraArgs)
Settings > Repository > Default Branch
You can use cv2.rectangle()
:
cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)
Draws a simple, thick, or filled up-right rectangle.
The function rectangle draws a rectangle outline or a filled rectangle
whose two opposite corners are pt1 and pt2.
Parameters
img Image.
pt1 Vertex of the rectangle.
pt2 Vertex of the rectangle opposite to pt1 .
color Rectangle color or brightness (grayscale image).
thickness Thickness of lines that make up the rectangle. Negative values,
like CV_FILLED , mean that the function has to draw a filled rectangle.
lineType Type of the line. See the line description.
shift Number of fractional bits in the point coordinates.
I have a PIL Image object and I want to draw rectangle on this image, but PIL's ImageDraw.rectangle() method does not have the ability to specify line width. I need to convert Image object to opencv2's image format and draw rectangle and convert back to Image object. Here is how I do it:
# im is a PIL Image object
im_arr = np.asarray(im)
# convert rgb array to opencv's bgr format
im_arr_bgr = cv2.cvtColor(im_arr, cv2.COLOR_RGB2BGR)
# pts1 and pts2 are the upper left and bottom right coordinates of the rectangle
cv2.rectangle(im_arr_bgr, pts1, pts2,
color=(0, 255, 0), thickness=3)
im_arr = cv2.cvtColor(im_arr_bgr, cv2.COLOR_BGR2RGB)
# convert back to Image object
im = Image.fromarray(im_arr)
Aggregated List of Libraries
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions
variable
or
foreach($questions as &$question){
Adding the &
will keep the $questions
updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach
documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Based upon which, IIS 7.5 Application Pool's identity use one of the following.
IIS AppPool\AppPoolName
and grant it Full control
. Replace "AppPoolName" with the name of your application pool (sometimes IIS_IUSRS
)Update based upon @Phil Hale comment:
Beware, if you're on a domain, your domain will be selected by default in the 'from location box'. Make sure to change that to "Local Computer". Change the location to "Local Computer" to view the app pool identities.
Construct a Calendar object and use the method add(Calendar.DATE, 1);
If you are also interested in the case where the user closes the date selection dialog without selecting a date (in my case choosing no date also has meaning) you can bind to the onClose
event:
$('#datePickerElement').datepicker({
onClose: function (dateText, inst) {
//you will get here once the user is done "choosing" - in the dateText you will have
//the new date or "" if no date has been selected
});
When it comes to float
numbers, you can use format specifiers:
f'{value:{width}.{precision}}'
where:
value
is any expression that evaluates to a numberwidth
specifies the number of characters used in total to display, but if value
needs more space than the width specifies then the additional space is used. precision
indicates the number of characters used after the decimal pointWhat you are missing is the type specifier for your decimal value. In this link, you an find the available presentation types for floating point and decimal.
Here you have some examples, using the f
(Fixed point) presentation type:
# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: ' 5.500'
# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}'
Out[2]: '3001.7'
In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'
# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}'
Out[4]: '7.234'
# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'
Not OP's case, but - for anyone who wants to assert intersection in dicts and ended up here due to poor googling (e.g. me) - you need to work with dict.items
:
>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False
That's because dict.items
returns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable
I'm surprised that no one thought of this simple non-recursive method, which can delete directories containing read only files, without needing to change read only attribute of each of them.
Process.Start("cmd.exe", "/c " + @"rmdir /s/q C:\Test\TestDirectoryContainingReadOnlyFiles");
(Change a bit to not to fire a cmd window momentarily, which is available all over the internet)
Long solved I'm sure but this might help some other poor soul.
This error can ocurre if the DLL you are deploying in the install package is not the same as the DLL you are referencing (these will have different IDs)
Sounds obvious but can easily happen if you make a small change to the dll and have previously installed the app on your own machine which reregisters the dll.
As a supplement to the question and above answers there is also an important difference between plt.subplots()
and plt.subplot()
, notice the missing 's'
at the end.
One can use plt.subplots()
to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.
# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)
Whereas, you can use plt.subplot()
if you want to add the subplots separately. It returns only the axis of one subplot.
fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1)
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)
However, plt.subplots()
is preferred because it gives you easier options to directly customize your whole figure
# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)
whereas, with plt.subplot()
, one will have to specify individually for each axis which can become cumbersome.
I've encountered string, which had mixings of English, Russian and some other alphabets, which caused exception. I need only Russian and English, and this currently works for me:
ec1 = Encoding::Converter.new "UTF-8","Windows-1251",:invalid=>:replace,:undef=>:replace,:replace=>""
ec2 = Encoding::Converter.new "Windows-1251","UTF-8",:invalid=>:replace,:undef=>:replace,:replace=>""
t = ec2.convert ec1.convert t
If you know the key name simply do like this:
delete array['key_name']
I'm using the latest Bootstrap 3 DateTime Picker (http://eonasdan.github.io/bootstrap-datetimepicker/)
This is how you should use DateTime Picker inline:
var selectedDate = $("#datetimepicker").find(".active").data("day");
The above returned: 03/23/2017
It's a reference to the current event object
To make the code portable to any system, I would use:
public static String newline = System.getProperty("line.separator");
This is important because different OSs use different notations for newline: Windows uses "\r\n", Classic Mac uses "\r", and Mac and Linux both use "\n".
Commentors - please correct me if I'm wrong on this...
feof()
is not very intuitive. In my very humble opinion, the FILE
's end-of-file state should be set to true
if any read operation results in the end of file being reached. Instead, you have to manually check if the end of file has been reached after each read operation. For example, something like this will work if reading from a text file using fgetc()
:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *in = fopen("testfile.txt", "r");
while(1) {
char c = fgetc(in);
if (feof(in)) break;
printf("%c", c);
}
fclose(in);
return 0;
}
It would be great if something like this would work instead:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *in = fopen("testfile.txt", "r");
while(!feof(in)) {
printf("%c", fgetc(in));
}
fclose(in);
return 0;
}
Start GDB on your project.
Go to project directory, where you've already compiled the project executable. Issue the command gdb and the name of the executable as below:
gdb projectExecutablename
This starts up gdb, prints the following: GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.04) 7.11.1 Copyright (C) 2016 Free Software Foundation, Inc. ................................................. Type "apropos word" to search for commands related to "word"... Reading symbols from projectExecutablename...done. (gdb)
Before you start your program running, you want to set up your breakpoints. The break command allows you to do so. To set a breakpoint at the beginning of the function named main:
(gdb) b main
Once you've have the (gdb) prompt, the run command starts the executable running. If the program you are debugging requires any command-line arguments, you specify them to the run command. If you wanted to run my program on the "xfiles" file (which is in a folder "mulder" in the project directory), you'd do the following:
(gdb) r mulder/xfiles
Hope this helps.
Disclaimer: This solution is not mine, it is adapted from https://web.stanford.edu/class/cs107/guide_gdb.html This short guide to gdb was, most probably, developed at Stanford University.
If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs()
:
>>> abs(-1)
1
>>> abs(1)
1
FOR IMAGE VIEW (set these parameters)
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:scaleType = "fitCenter"
android:adjustViewBounds = "true"
Now whatever the size of the image is there, it's width will match the parent and height will be according to match the ratio. I have tested this and I am 100% sure.
// Results will be:
Image width -> stretched as match parent
Image height -> according to image width (maximum to aspect ratio)
// like the first one
Code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra array is not:
import java.util.*;
public class Main{
public static char[] removeDupes(char[] arr){
if (arr == null || arr.length < 2)
return arr;
int len = arr.length;
int tail = 1;
for(int x = 1; x < len; x++){
int y;
for(y = 0; y < tail; y++){
if (arr[x] == arr[y]) break;
}
if (y == tail){
arr[tail] = arr[x];
tail++;
}
}
return Arrays.copyOfRange(arr, 0, tail);
}
public static char[] bigArr(int len){
char[] arr = new char[len];
Random r = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+[]{}|;:',.<>/?`~";
for(int x = 0; x < len; x++){
arr[x] = alphabet.charAt(r.nextInt(alphabet.length()));
}
return arr;
}
public static void main(String args[]){
String result = new String(removeDupes(new char[]{'a', 'b', 'c', 'd', 'a'}));
assert "abcd".equals(result) : "abcda should return abcd but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'a', 'a'}));
assert "a".equals(result) : "aaaa should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'c', 'a'}));
assert "abc".equals(result) : "abca should return abc but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'a', 'b', 'b'}));
assert "ab".equals(result) : "aabb should return ab but it returns: " + result;
result = new String(removeDupes(new char[]{'a'}));
assert "a".equals(result) : "a should return a but it returns: " + result;
result = new String(removeDupes(new char[]{'a', 'b', 'b', 'a'}));
assert "ab".equals(result) : "abba should return ab but it returns: " + result;
char[] arr = bigArr(5000000);
long startTime = System.nanoTime();
System.out.println("2: " + new String(removeDupes(arr)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Program took: " + duration + " nanoseconds");
System.out.println("Program took: " + duration/1000000000 + " seconds");
}
}
How to read and talk about the above code:
Explain how this code works:
The first part of the array passed in is used as the repository for the unique characters that are ultimately returned. At the beginning of the function the answer is: "the characters between 0 and 1" as between 0 and tail.
We define the variable y outside of the loop because we want to find the first location where the array index that we are looking at has been duplicated in our repository. When a duplicate is found, it breaks out and quits, the y==tail returns false and the repository is not contributed to.
when the index x that we are peeking at is not represented in our repository, then we pull that one and add it to the end of our repository at index tail and increment tail.
At the end, we return the array between the points 0 and tail, which should be smaller or equal to in length to the original array.
Talking points exercise for coder interviews:
Will the program behave differently if you change the y++ to ++y? Why or why not.
Does the array copy at the end represent another 'N' pass through the entire array making runtime complexity O(n*n) instead of O(n) ? Why or why not.
Can you replace the double equals comparing primitive characters with a .equals? Why or why not?
Can this method be changed in order to do the replacements "by reference" instead of as it is now, "by value"? Why or why not?
Can you increase the efficiency of this algorithm by sorting the repository of unique values at the beginning of 'arr'? Under which circumstances would it be more efficient?
I think you want something along the line of:
Parent:
<Editor name={this.state.fileData} />
Editor:
var Editor = React.createClass({
displayName: 'Editor',
propTypes: {
name: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
value: this.props.name
};
},
handleChange: function(event) {
this.setState({value: event.target.value});
},
render: function() {
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
});
This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html
Update for React 16.8:
import React, { useState } from 'react';
const Editor = (props) => {
const [value, setValue] = useState(props.name);
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<form id="noter-save-form" method="POST">
<textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
<input type="submit" value="Save" />
</form>
);
}
Editor.propTypes = {
name: PropTypes.string.isRequired
};
This is the best way, because if user not back more than two seconds then reset backpressed value.
declare one global variable.
private boolean backPressToExit = false;
Override
onBackPressed
Method.
@Override
public void onBackPressed() {
if (backPressToExit) {
super.onBackPressed();
return;
}
this.backPressToExit = true;
Snackbar.make(findViewById(R.id.yourview), getString(R.string.exit_msg), Snackbar.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
backPressToExit = false;
}
}, 2000);
}
Modifying Aleksandar's answer to make it as jquery plugin and accepts maxwidth and maxheight as arguments, suggested by Nathan.
$.fn.resize = function(maxWidth,maxHeight) {
return this.each(function() {
var ratio = 0;
var width = $(this).width();
var height = $(this).height();
if(width > maxWidth){
ratio = maxWidth / width;
$(this).css("width", maxWidth);
$(this).css("height", height * ratio);
height = height * ratio;
}
var width = $(this).width();
var height = $(this).height();
if(height > maxHeight){
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
});
};
Used as $('.imgClass').resize(300,50);
You can try very easy code for this:
display: flex;
align-items: center;
justify-content: center;
.box{_x000D_
height: 90px;_x000D_
width: 90px;_x000D_
background: green;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="box">_x000D_
Lorem_x000D_
</div>
_x000D_
Codepen link: http://codepen.io/santoshkhalse/pen/xRmZwr
There are two ways. In case of doubt, you can always just try it. If it does not work, you can add extra braces to make sure, like that:
if not ((u0 <= u) and (u < u0+step)):
Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}
Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)
EXAMPLE to get lat/lng:
var lat = '';
var lng = '';
var address = {zipcode} or {city and state};
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
alert('Latitude: ' + lat + ' Logitude: ' + lng);
One option is to work with profiles. Create a file called application-test.yml, move all properties you need for those tests to that file and then add the @ActiveProfiles
annotation to your test class:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@ActiveProfiles("test") // Like this
public class MyIntTest{
}
Be aware, it will additionally load the application-test.yml, so all properties that are in application.yml are still going to be applied as well. If you don't want that, either use a profile for those as well, or override them in your application-test.yml.
here is something i did.
function foreach(o, f) {
for(var i = 0; i < o.length; i++) { // simple for loop
f(o[i], i); // execute a function and make the obj, objIndex available
}
}
this is how you would use it
this will work on arrays and objects( such as a list of HTML elements )
foreach(o, function(obj, i) { // for each obj in o
alert(obj); // obj
alert(i); // obj index
/*
say if you were dealing with an html element may be you have a collection of divs
*/
if(typeof obj == 'object') {
obj.style.marginLeft = '20px';
}
});
I just made this so I'm open to suggestions :)
Here is a cross platform solution to clearing docker container logs:
docker run --rm -v /var/lib/docker:/var/lib/docker alpine sh -c "echo '' > $(docker inspect --format='{{.LogPath}}' CONTAINER_NAME)"
Paste this into your terminal and change CONTAINER_NAME
to desired container name or id.
From DateTime on msdn:
Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.
Use parseexact with the format string "yyyy-dd-MM hh:mm tt"
instead.
The & operator takes the intersection of two sets.
{1, 2, 3} & {2, 3, 4}
Out[1]: {2, 3}
You're trying to create a tuple, but you're just parenthesizing a string :)
Add an extra ',':
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,)) # <- note extra ','
processThread.start()
Or use brackets to make a list:
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved]) # <- 1 element list
processThread.start()
If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)
The *self.__args
turns your string into a list of characters, passing them to the processLine
function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.
Install ILMerge as the other threads tell you to
Then go to the installation folder, by default
C:\Program Files (x86)\Microsoft\ILMerge
Drag your Dll's and Exes to that folder
Shift-Rightclick in that folder and choose open command prompt
Write
ilmerge myExe.exe Dll1.dll /out:merged.exe
Note that you should write your exe first.
There you got your merged exe. This might not be the best way if your going to do this multiple times, but the simplest one for a one time use, I would recommend putting Ilmerge to your path.
You can also get it from Chocolatey:
You can do this easily manually for each column like this:
df['A_perc'] = df['A']/df['sum']
If you want to do this in one step for all columns, you can use the div
method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):
ds.div(ds['sum'], axis=0)
And if you want this in one step added to the same dataframe:
>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
A B C D sum A_perc B_perc \
1 0.151722 0.935917 1.033526 0.941962 3.063127 0.049532 0.305543
2 0.033761 1.087302 1.110695 1.401260 3.633017 0.009293 0.299283
3 0.761368 0.484268 0.026837 1.276130 2.548603 0.298739 0.190013
C_perc D_perc sum_perc
1 0.337409 0.307517 1
2 0.305722 0.385701 1
3 0.010530 0.500718 1
You don't need a wrapper, just use the body as the wrapper.
CSS:
body {
margin:0 auto;
width:200px;
}
HTML:
<body>
<p>some content</p>
<body>
Given there is only one (or with this solution potentially not even one) submit button, here is jQuery based solution that will work for multiple forms on the same page...
<script type="text/javascript">
$(document).ready(function () {
var makeAllFormSubmitOnEnter = function () {
$('form input, form select').live('keypress', function (e) {
if (e.which && e.which == 13) {
$(this).parents('form').submit();
return false;
} else {
return true;
}
});
};
makeAllFormSubmitOnEnter();
});
</script>
Things have changed in HTML5:
ASPX:
<asp:TextBox ID="txtBox" runat="server" maxlength="2000" TextMode="MultiLine"></asp:TextBox>
C#:
if (!IsPostBack)
{
txtBox.Attributes.Add("maxlength", txtBox.MaxLength.ToString());
}
Rendered HTML:
<textarea name="ctl00$DemoContentPlaceHolder$txtBox" id="txtBox" maxlength="2000"></textarea>
The metadata for Attributes
:
Summary: Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.
Returns: A
System.Web.UI.AttributeCollection
of name and value pairs.
HTML 5 invites you give add a lot of semantic value to your code. What's more, there are natives solution to embed multimedia content.
The rest is important, but it's more technical sugar that will save you from doing the same stuff with a client programming language.
This might help
lsof -n -i4TCP:8080
The PID is the second field in the output.
Or try:
lsof -i -P
You should clear out your listbbox prior to binding:
Me.ddl2.Items.Clear()
' now set datasource and bind
I prefer using an adjacency list of Indices ( not pointers )
typedef std::vector< Vertex > Vertices;
typedef std::set <int> Neighbours;
struct Vertex {
private:
int data;
public:
Neighbours neighbours;
Vertex( int d ): data(d) {}
Vertex( ): data(-1) {}
bool operator<( const Vertex& ref ) const {
return ( ref.data < data );
}
bool operator==( const Vertex& ref ) const {
return ( ref.data == data );
}
};
class Graph
{
private :
Vertices vertices;
}
void Graph::addEdgeIndices ( int index1, int index2 ) {
vertices[ index1 ].neighbours.insert( index2 );
}
Vertices::iterator Graph::findVertexIndex( int val, bool& res )
{
std::vector<Vertex>::iterator it;
Vertex v(val);
it = std::find( vertices.begin(), vertices.end(), v );
if (it != vertices.end()){
res = true;
return it;
} else {
res = false;
return vertices.end();
}
}
void Graph::addEdge ( int n1, int n2 ) {
bool foundNet1 = false, foundNet2 = false;
Vertices::iterator vit1 = findVertexIndex( n1, foundNet1 );
int node1Index = -1, node2Index = -1;
if ( !foundNet1 ) {
Vertex v1( n1 );
vertices.push_back( v1 );
node1Index = vertices.size() - 1;
} else {
node1Index = vit1 - vertices.begin();
}
Vertices::iterator vit2 = findVertexIndex( n2, foundNet2);
if ( !foundNet2 ) {
Vertex v2( n2 );
vertices.push_back( v2 );
node2Index = vertices.size() - 1;
} else {
node2Index = vit2 - vertices.begin();
}
assert( ( node1Index > -1 ) && ( node1Index < vertices.size()));
assert( ( node2Index > -1 ) && ( node2Index < vertices.size()));
addEdgeIndices( node1Index, node2Index );
}
SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();
There is no memory limit imposed by Python. However, you will get a MemoryError
if you run out of RAM. You say you have 20301 elements in the list
. This seems too small to cause a memory error for simple data types (e.g. int
), but if each element itself is an object that takes up a lot of memory, you may well be running out of memory.
The IndexError
however is probably caused because your ListTemp
has got only 19767 elements (indexed 0 to 19766), and you are trying to access past the last element.
It is hard to say what you can do to avoid hitting the limit without knowing exactly what it is that you are trying to do. Using numpy
might help. It looks like you are storing a huge amount of data. It may be that you don't need to store all of it at every stage. But it is impossible to say without knowing.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
It will be hard to work in C# without knowing how to work with strings and booleans. But anyway:
String str = "ABC";
if (str.Contains('A'))
{
//...
}
if (str.Contains("AB"))
{
//...
}
From your Obc-C code I think you want to set an Image for button so try this way:
let playButton = UIButton(type: .Custom)
if let image = UIImage(named: "play.png") {
playButton.setImage(image, forState: .Normal)
}
In Short:
playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
For Swift 3:
let playButton = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)
I'm not sure about this, but give it a shot.
In your strings.xml define:
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>
In your layout:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="@array/array_name"
/>
I've heard this doesn't always work on the designer, but it compiles fine.
You can do it without having to keep track of the previous scroll top, as all the other examples require:
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
console.log('Scroll up');
}
else {
console.log('Scroll down');
}
});
I am not an expert on this so feel free to research it further, but it appears that when you use $(element).scroll
, the event being listened for is a 'scroll' event.
But if you specifically listen for a mousewheel
event by using bind, the originalEvent
attribute of the event parameter to your callback contains different information. Part of that information is wheelDelta
. If it's positive, you moved the mousewheel up. If it's negative, you moved the mousewheel down.
My guess is that mousewheel
events will fire when the mouse wheel turns, even if the page does not scroll; a case in which 'scroll' events probably are not fired. If you want, you can call event.preventDefault()
at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.
if(sender is TextBox) {
var text = (sender as TextBox).Text;
}
This function return a sub and sorted array based in second parameter $keys
function array_sub_sort(array $values, array $keys){
$keys = array_flip($keys);
return array_merge(array_intersect_key($keys, $values), array_intersect_key($values, $keys));
}
Example:
$array_complete = [
'a' => 1,
'c' => 3,
'd' => 4,
'e' => 5,
'b' => 2
];
$array_sub_sorted = array_sub_sort($array_complete, ['a', 'b', 'c']);//return ['a' => 1, 'b' => 2, 'c' => 3];
You can use Smartface for developing your app with javascript and deploy to stores directly without a Mac. What they say is below.
With the Cloud Build module, Smartface removes all the hassle of application deployment. You don’t need to worry about managing code signing certificates and having a Mac to sign your apps. Smartface Cloud can store all your iOS certificates and Android keystores in one place and signing and building is fully in the cloud. No matter which operating system you use, you can get store-ready (or enterprise distribution) binaries. Smartface frees you from the lock-in to Mac and allows you to use your favorite operating system for development.
There's a neat NPM package that does it for you (and it should work cross platform).
Install it with: npm install -g git-removed-branches
And then git removed-branches
will show you all the stale local branches, and git removed-branches --prune
to actually delete them.
As seen in the revision column of the Android SDK Manager, the latest published version of the Support Library is 22.2.1. You'll have to wait until 23.0.0 is published.
Edit: API 23 is already published. So u can use 23.0.0
const timeObject = new Date();
timeObject = new Date(timeObject.getTime() + 1000 * 10);
console.log(timeObject);
Also please refer: How to add 30 minutes to a JavaScript Date object?
For what its worth I got the following error trying to ssh into my local machine, running Ubuntu 16.04 Xenial, from a vm.
ssh: connect to host 192.168.144.18 port 22: Connection refused
It got immediately fixed with:
sudo apt-get install ssh
Take note, Before fix: 'which sshd' returned nothing and 'which ssh' returned
/usr/bin/ssh
And After the fix: 'which sshd' returned
/usr/sbin/sshd
Setup ANDROID_HOME , JAVA_HOME enviromental variable on Mac OS X
Add In .bash_profile file
export JAVA_HOME=$(/usr/libexec/java_home)
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
For Test
echo $ANDROID_HOME
echo $JAVA_HOME
const int* ptr;
is a pointer to constant (content). You are allowed to modify the pointer. e.g. ptr = NULL
, ptr++
, but modification of the content is not possible.
int * const ptr;
Is a constant pointer. The opposite is possible. You are not allowed to modify the pointer, but you are allowed to modify what it points to e.g. *ptr += 5
.
You want instanceof
:
if (value instanceof Integer)
This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do
if (value.getClass() == Integer.class)
or
if (Integer.class.equals(value.getClass())