_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d7901
train
You can simply loop over the related Document objects from the Event object itself by using document_set (the default related_name for Document i.e. the model name in lowercase with _set appended). Also you can optimise the number of queries made by using prefetch_related [Django docs]: In your view: @login_required def consultant_home(request): consultant_pr = Consultant_Profile.objects.get(user_id=request.user) events = Event.objects.filter(consultant_id=consultant_pr.pk).prefetch_related('document_set') context = {'events': event, 'consultant_pr': consultant_pr} return render(request, 'Consultant/consultant_documents.html', context) In your template: {% for event in events %} <p>Event id: {{ event.event_id }}</p> {% for document in event.document_set.all %} <p>document name: {{ document.document_name }}</p> <!-- Use document.path.url instead of manually rendering its url --> <p>path: <a href="{{ document.path.url }}">{{ document.path }} </a></p> {% endfor%} {% endfor %}
unknown
d7902
train
Universal answer (with explanation): BeginInvoke is function that send a message 'this function should be executed in different thread' and then directly leaves to continue execution in current thread. The function is executed at a later time, when the target thread has 'free time' (messages posted before are processed). When you need the result of the function, use Invoke. The Invoke function is 'slower', or better to say it blocks current thread until the executed function finishes. (I newer really tested this in C#, but it s possible, that the Invoke function is prioritized; e.g. when you call BeginInvoke and directly after it Invoke to the same thread, the function from Invoke will probably be executed before the function from BeginInvoke.) Use this alternative when you need the function to be executed before the next instruction are processed (when you need the result of the invoked function). Simple (tl;dr): When you need to need to only set a value (e.g. set text of edit box), use BeginInvoke, but when you need a result (e.g. get text from edit box) use always Invoke. In your case you need the result (bitmap to be drawn) therefore you need to wait for the function to end. (There are also other possible options, but in this case the simple way is the better way.)
unknown
d7903
train
Can I easily build a JSON-RPC consumer in .NET? Yes. JSON-RPC services are simple to consume as long as you have a robust JSON parser or formatter. Jayrock provides a simple client implementation JsonRpcClicnet that you can use to build a consumer. There is also a small demo sample included. Are JSON-RPC web services self documenting and discoverable, like a SOAP WSDL? No, there is nothing standardized but there are ideas being floated around like Service Mapping Description Proposal. Can I easily add a Web Reference in Visual Studio to a JSON-RPC web service? This can work if the server-side implementation provides a WSDL-based description of the JSON-RPC service but none are known to provide this to date. A: Check out Jayrock. Jayrock is a modest and an open source (LGPL) implementation of JSON and JSON-RPC for the Microsoft .NET Framework, including ASP.NET. What can you do with Jayrock? In a few words, Jayrock allows clients, typically JavaScript in web pages, to be able to call into server-side methods using JSON as the wire format and JSON-RPC as the procedure invocation protocol. The methods can be called synchronously or asynchronously. A: Can I easily build a JSON-RPC consumer in .NET? Shouldn't be difficult as long as you know what you're doing. Are JSON-RPC web services self documenting and discoverable, like a SOAP WSDL? Discoverable yes, documenting in as much as you can get function names and parameter lists. (not entirely sure what you're asking for as far as documentation goes). Can I easily add a Web Reference in Visual Studio to a JSON-RPC web service? I don't think so, no. (Though, I have no idea, it's possible. My experience with JSON-RPC is in PHP/JS mostly) Relevant links: * *http://json-rpc.org/wiki/specification *http://json.org/ *http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html A: Maybe you could have a look at json-wsp which is much like json-rpc but with a discription specification. It is implemented as an interface in Ladon for python. http://pypi.python.org/pypi/ladon A: I have some sample Json-Rpc 2.0 clients for .net and windows phone 7 in the Json-RPC.NET sources. Check them out: .Net Client and WP7 Client
unknown
d7904
train
I had the same problem with justhost and I solved it without adding any redirect. I set my rails app public folder to be the main site public folder. * *I renamed the original "public_html" to "public_html_backup", just in case. *Added a symlink ln -s ~/myRailsApp/public ~/public_html *in my htaccess I changed RailsBaseURI /myRailsApp to RailsBaseURI /, resulting in: <IfModule mod_passenger.c> Options -MultiViews PassengerResolveSymlinksInDocumentRoot on RailsEnv production RackBaseURI / SetEnv GEM_HOME /yourUserPath.../ruby/gems </IfModule> I hope this can help you. Cheers
unknown
d7905
train
First install ImageMagick and GNU Parallel with homebrew: brew install imagemagick brew install parallel Then go to the directory where the images are and create an output directory: cd where/the/images/are mkdir output Now run ImageMagick from GNU Parallel find . -name "*.jpg" -print0 | parallel -0 magick {} -define jpeg:extent=80kb output/{}
unknown
d7906
train
To pass data when you submit a form, you have to include that data in a form input field (hidden, visible, doesn't matter). A: You can add hidden fields in your HTML form like this <input type="hidden" id="Data_ID"> <input type="hidden" id="Data_Type"> and then set the values in your javascript function and then submit (?) <script type="text/javascript"> function Service_Add(Data_ID,Data_Type) { document.getElelementByID("Data_ID").value=Data_ID; document.getElelementByID("Data_Type").value=Data_Type; document.miformulario.submit(); } </script>
unknown
d7907
train
Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45 unsigned long alpha = 0x45 unsigned long pixel = 0x12345678; pixel = ((pixel & 0x00FFFFFF) | (alpha << 24)); The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel. A: Bitmasks are used when you want to encode multiple layers of information in a single number. So (assuming unix file permissions) if you want to store 3 levels of access restriction (read, write, execute) you could check for each level by checking the corresponding bit. rwx --- 110 110 in base 2 translates to 6 in base 10. So you can easily check if someone is allowed to e.g. read the file by and'ing the permission field with the wanted permission. Pseudocode: PERM_READ = 4 PERM_WRITE = 2 PERM_EXEC = 1 user_permissions = 6 if ((user_permissions & PERM_READ) == PERM_READ) then // this will be reached, as 6 & 4 is true fi You need a working understanding of binary representation of numbers and logical operators to understand bit fields. A: Bit masking is "useful" to use when you want to store (and subsequently extract) different data within a single data value. An example application I've used before is imagine you were storing colour RGB values in a 16 bit value. So something that looks like this: RRRR RGGG GGGB BBBB You could then use bit masking to retrieve the colour components as follows: const unsigned short redMask = 0xF800; const unsigned short greenMask = 0x07E0; const unsigned short blueMask = 0x001F; unsigned short lightGray = 0x7BEF; unsigned short redComponent = (lightGray & redMask) >> 11; unsigned short greenComponent = (lightGray & greenMask) >> 5; unsigned short blueComponent = (lightGray & blueMask); A: Briefly, a bitmask helps to manipulate the position of multiple values. There is a good example here; Bitflags are a method of storing multiple values, which are not mutually exclusive, in one variable. You've probably seen them before. Each flag is a bit position which can be set on or off. You then have a bunch of bitmasks #defined for each bit position so you can easily manipulate it: #define LOG_ERRORS 1 // 2^0, bit 0 #define LOG_WARNINGS 2 // 2^1, bit 1 #define LOG_NOTICES 4 // 2^2, bit 2 #define LOG_INCOMING 8 // 2^3, bit 3 #define LOG_OUTGOING 16 // 2^4, bit 4 #define LOG_LOOPBACK 32 // and so on... // Only 6 flags/bits used, so a char is fine unsigned char flags; // Initialising the flags, // Note that assigning a value will clobber any other flags, so you // it should generally only use the = operator when initialising variables. flags = LOG_ERRORS; // Sets to 1 i.e. bit 0 // Initialising to multiple values with OR (|) flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING; // sets to 1 + 2 + 8 i.e. bits 0, 1 and 3 // Setting one flag on, leaving the rest untouched // OR bitmask with the current value flags |= LOG_INCOMING; // Testing for a flag // AND with the bitmask before testing with == if ((flags & LOG_WARNINGS) == LOG_WARNINGS) ... // Testing for multiple flags // As above, OR the bitmasks if ((flags & (LOG_INCOMING | LOG_OUTGOING)) == (LOG_INCOMING | LOG_OUTGOING)) ... // Removing a flag, leaving the rest untouched // AND with the inverse (NOT) of the bitmask flags &= ~LOG_OUTGOING; // Toggling a flag, leaving the rest untouched flags ^= LOG_LOOPBACK; ** WARNING: DO NOT use the equality operator (i.e. bitflags == bitmask) for testing if a flag is set - that expression will only be true if that flag is set and all others are unset. To test for a single flag you need to use & and == : ** if (flags == LOG_WARNINGS) //DON'T DO THIS ... if ((flags & LOG_WARNINGS) == LOG_WARNINGS) // The right way ... if ((flags & (LOG_INCOMING | LOG_OUTGOING)) // Test for multiple flags set == (LOG_INCOMING | LOG_OUTGOING)) ... You can also search C++ Tricks.
unknown
d7908
train
1) Limit the rows to only rows with date inside the window. 2) Sort the result by date descending (putting the most recent at the top) 3) Select the first row DECLARE @CheckDate DATETIME = '07-07-2015', @ProjectId INT = 1234 -- To ignore time, set the check date to the first millisecond of the -- next day and use a less than operator SET @CheckDate = DATEADD(dd, DATEDIFF(dd, 0, @CheckDate) + 1, 0) SELECT TOP 1 [Status] FROM [Project] WHERE [ProjectId] = @ProjectId AND [Date] < @CheckDate ORDER BY [Date] DESC A: If you have 2012 or later, you can do this with Lead as follows: declare @date datetime = '7-2-15' --or whatever select ProjectID, Status from ( select * , lead(date) over (partition by projectID order by date) as NextEvent from MyTable) a where @date between [date] and isnull(NextEvent, @date + 1) Otherwise, you can approximate lead using row_number and a self-join. Note, depending on how precise your dates are, you may want to use something like where @date >= date and @date < isnull(NextEvent, @date + 1) instead of between.
unknown
d7909
train
It's pretty easy to remove continue from the loop. What you need is two indexes in your loop. One for the position in the source array and one for the position in the array to copy to. Then you put the copy operation inside the if statement so if there is no copy you do nothing to go to the next iteration. That would make you loop look like for (int source_index = 0, copy_index = 0; source_index < n; ++source_index) { // increment source_index always if (!strchr(vowels,s[i])) { // this isn't a vowel so copy and increment copy_index afterElimination[copy_index++] = s[i]; } // now this is the continue but we don't need to say it } A: This is a typical approach to filtering letters from a given string. #include <string.h> char s[20] = "something"; char no_vowels[20] = {0}; int i = 0; int j = 0; const char *vowels = "aeiou"; while (s[i]) { if (!strchr(vowels, s[i])) { no_vowels[j] = s[i]; j++; } i++; } Here's a working example.
unknown
d7910
train
An old question still in need of an answer... One approach is to create an empty Matrix of the required dimensions and then populate it: m12.dimnames<-list(union(rownames(sparse_m1),rownames(sparse_m2)),c(colnames(sparse_m1),colnames(sparse_m2))) m12<- Matrix(0,nrow=length(m12.dimnames[[1]]),ncol=length(m12.dimnames[[2]]),dimnames=m12.dimnames) m12[rownames(sparse_m2),colnames(sparse_m2)]<-sparse_m1 m12[rownames(sparse_m2),colnames(sparse_m2)]<-sparse_m2 A: recently bumped in the same issue, and nowadays you can install.packages("Matrix.utils") library(Matrix.utils) sparse_filled <- rBind.fill(sparse_m1, sparse_m2)
unknown
d7911
train
SELECT month(time) as `month`, SUM(kw*tdsecs) as `sum` FROM data WHERE year(time) = year(CURDATE()) group by month(time) order by month(time) A: SELECT month(time), SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) group by month(time); A: mysql_query("SELECT month(time),SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) in (1,2,3,4,5,6,7,8,9,10,11,12) group by month(time)") A: A simple solution (not the best) would be to loop through the months and store the results in a array: for($month=1; $month<=12; $month++) { $query = mysql_query( "SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = $month"); $result = mysql_fetch_array($query); $kwm[$month] = $result[0] / 60; $kwh[$month] = round($kwm[$month] / 60,2); }
unknown
d7912
train
Rather than using the lock() keywords I'd suggested seeing if you can use the Interlocked class which is designed for small operations. It's got much less overhead than lock, in fact can be down to a single CPU instruction on some CPUs. There are a couple of methods of interest for you, Exchange and Read, both of which are thread safe. A: You want to look into the Lock keyword. Also you might want to this tutorial to Threading in C#. A: As Filip said, lock is useful here. Not only should you lock on provider.SetNumber(currentNumber), you also need to lock on any conditional that the setter depends on. lock(someObject) { if(provider.CanPassNumber(false, currentNumber)) { currentNumber++; provider.SetNumber(currentNumber); } } as well as if(condition) { lock(someObject) { provider.SetNumber(numberToSet); } } If condition is reliant on numberToSet, you should take the lock statement around the whole block. Also note that someObject must be the same object. A: You can use the lock statement, to enter a critical section with mutual exclusion. The lock will use the object's reference to differentiate one critical section from another, you must have the same reference for all your lock if it accesses to the same elements. // Define an object which can be locked in your class. object locker = new object(); // Add around your critical sections the following : lock (locker) { /* ... */ } That will change your code to : int currentNumber = provider.GetCurrentNumber(); lock (locker) { if(provider.CanPassNumber(false, currentNumber)) { currentNumber++; provider.SetNumber(currentNumber); } } And : if(condition) { lock (locker) { provider.SetNumber(numberToSet); } } A: Well first of im not so good with threading but a critical section is a part of your code that can only be accessed my one thread at a time not the other way around.. To create a critical section is easy Lock(this) { //Only one thread can run this at a time } note: that this should be replaced with some internal object... A: In your SetNumber method you can simply use a lock statement: public class MyProvider { object numberLock = new object(); ... public void SetNumber(int num) { lock(numberLock) { // Do Stuff } } } Also, note that in your example currentNumber is a primitive (int), which means that variable's value won't be overwritten should your provider's actual data member's value change.
unknown
d7913
train
Space complexity: Identify data that occurs "in large quantities" or "repeatedly". Assign numbers to these quantities, e.g., N = number of lines in a file, or M = number of elements in an array. Add these quantities. Watch out for the dynamic creation of data structures: if you have an array of N numbers and another one of M numbers and you create a table of all the products, then the space complexity of the table is... Time complexity: Identify repeated actions. Some may be hidden (as in Perl), some are explicit, e.g. in a for loop. Use the results of space complexity to quantify these repetititions. A loop may be terminated early: then you must estimate the average time of execution. Loops occurring one after the other add up. If you know that a loop body is executed N times and this body contains an inner loop that executes M times, then the body of that inner loop is executed - how often? Very frequently it's just a simple exercise of counting, bookkeeping and simple arithmetic, although there are several examples where a good answer requires heavy math. Not in your case!
unknown
d7914
train
It is because you remove and recreate the canvases when switching canvas. Below is a modified code based on yours: * *create canvases once *use place() instead of pack() on canvases *create a class method to raise a canvas to the front from tkinter import * from PIL import Image, ImageTk from functools import partial class DiceGame(Tk): def __init__(self): super(DiceGame, self).__init__() self.title("Dice Cricket") self.geometry('980x660+200-60') self.state('zoomed') self.font1 = ('Algerian', 95, 'bold') self.font2 = ('Comic Sans MS', 50, 'bold') self.font3 = ('Comic Sans MS', 40, 'bold') self.font4 = ('Comic Sans MS', 30, 'bold') self.font5 = ('Comic Sans MS', 25, 'bold') self.font6 = ('Comic Sans MS', 15, 'bold') self.bgcolor = '#366649' self.background1 = PhotoImage(file = 'dicepic9.png') self.back_image = PhotoImage(file = "back arrow.png").subsample(7,7) self.MainMenu_Canvas = self.NewGameMenu_Canvas = None ### self.MainMenu() def gameTitle(self, root): title_Label = Label(root, text = "Dice Cricket", font = self.font1, bg = self.bgcolor, fg = 'yellow') title_Label.grid(row = 0, column = 1, pady = 15, ipadx = 100) def createLabels(self, frame, LabelList, Labeltexts): for i in range(len(Labeltexts)): label = Label(frame, text = Labeltexts[i], font = self.font4, fg = 'light green', bg = 'gray10') label.pack(fill = X) LabelList.append(label) LabelList[0].pack_configure(pady = (10,0)) self.selection(LabelList) def selection(self, LabelList): for label in LabelList: label.bind("<Enter>", partial(self.color_config, label, "maroon", "pink")) label.bind("<Leave>", partial(self.color_config, label, "light green", "grey10")) def color_config(self, widget, color1, color2, event): widget.configure(foreground = color1, bg = color2) def backbutton(self, root): self.back_Label = Label(root, text = "Back", font = self.font5, fg = "Yellow", bg = self.bgcolor, image = self.back_image, compound = LEFT) return self.back_Label ### raise a canvas to the front def raise_canvas(self, canvas): canvas.tk.call("raise", canvas) def MainMenu(self): self.Actice_Window = "MainMenu" ### moved from __init__() if self.MainMenu_Canvas is None: self.MainMenu_Canvas = Canvas(self, bg = self.bgcolor, highlightthickness = 0) ###self.MainMenu_Canvas.pack(fill = BOTH, expand = True) self.MainMenu_Canvas.place(relwidth=1, relheight=1) ### self.MainMenu_Canvas.create_image(0, 0, anchor = NW, image = self.background1) self.gameTitle(self.MainMenu_Canvas) self.MainMenu_Frame = Frame(self.MainMenu_Canvas) self.MainMenu_Frame.grid(row = 1, column = 1, pady = 10, ipadx = 20) self.MainMenu_Label = Label(self.MainMenu_Frame, text = "Main Menu", font = self.font2, bg = self.bgcolor, fg = 'orange') self.MainMenu_Label.pack(fill = X, pady = (0,0)) self.Options_Frame = Frame(self.MainMenu_Frame, bg = 'gray10', bd = 4, relief = GROOVE) self.Options_Frame.pack(fill = X, ipady = 5, ipadx = 60) mainLabels = [] Labeltexts = ["New Game", "Load Game", "Hall of Fame", "Options", "Credits", "Exit Game"] self.createLabels(self.Options_Frame, mainLabels, Labeltexts) mainLabels[0].bind('<Button-1>', self.NewGame_Menu) self.raise_canvas(self.MainMenu_Canvas) ### def NewGame_Menu(self, event): self.Actice_Window = "NewGame Menu" ###self.MainMenu_Canvas.pack_forget() if self.NewGameMenu_Canvas is None: self.NewGameMenu_Canvas = Canvas(self, bg = self.bgcolor, highlightthickness = 0) ###self.NewGameMenu_Canvas.pack(fill = BOTH, expand = True) self.NewGameMenu_Canvas.place(relwidth=1, relheight=1) ### self.NewGameMenu_Canvas.create_image(0, 0, anchor = NW, image = self.background1) self.gameTitle(self.NewGameMenu_Canvas) self.NewGame_Frame = Frame(self.NewGameMenu_Canvas, bg = self.bgcolor) self.NewGame_Frame.grid(row = 1, column = 1, pady = 10) self.selection_Label = Label(self.NewGame_Frame, text = "Select Game Type", font = self.font3, fg = "Silver", bg = self.bgcolor) self.selection_Label.pack() self.Matchtype_Frame = Frame(self.NewGame_Frame, bg = 'gray10', bd = 4, relief = GROOVE) self.Matchtype_Frame.pack(ipadx = 60, ipady = 10, pady = 15) newGameLabels = [] newGameLabelsText = ["Quick Match", "Bilateral Series", "Tournament", "Practice"] self.createLabels(self.Matchtype_Frame, newGameLabels, newGameLabelsText) self.back1 = self.backbutton(self.NewGameMenu_Canvas) self.back1.grid(row = 2, column = 1, sticky = W, padx = 190, pady = 10) self.back1.bind('<Button-1>', self.Go_Back) self.raise_canvas(self.NewGameMenu_Canvas) ### def Go_Back(self, event): if self.Actice_Window == "NewGame Menu": ###self.NewGameMenu_Canvas.pack_forget() ###self.MainMenu_Canvas.pack(fill = BOTH, expand = True) self.raise_canvas(self.MainMenu_Canvas) ### dice = DiceGame() dice.mainloop()
unknown
d7915
train
No, you can't. File cannot be uploaded or even downloaded in iOS safari. In iCab you can upload by <input type = 'file'> but you can't access filesystem. Acessing entire filesystem from browser will be a security disaster. And also java plugin can't acess entire filesystem. A: It depends what do you want to do. If you just want allow user to navigate to interesting file(s) and then upload it to server for processing you can use <input type='file'> in your HTML. If you need more functionality you have to implement native plug-in to browser or use Flash.
unknown
d7916
train
Why don't you use the FormView or DetailsView? They are meant to display one item (at the time).
unknown
d7917
train
CreditTransactionRequest in CreditCardProxy does not take any arguments but CreditTransactionRequest in BankSubject does. This is why you can not override the method the signatures do not match. A: In your proxy, you are not specifying the amount as a parameter to the method: public override void CreditTransactionRequest(); So it cannot override public abstract void CreditTransactionRequest(double amount); as the method signature doesn't not match
unknown
d7918
train
You need to declare a key property in UserDetails with the same name that you declare in the ForeignKey attribute: public class UsrDetails { [Key] public int UsrID{ get; set; } [ForeignKey("UsrID")] public virtual Usr Usr { get; set; } } All your entities must have a PK property. In this case where you are representing a one to one relationship, the PK of the dependent entity also is the FK. You can check this tutorial in case you need more info.
unknown
d7919
train
Move int size = Integer.parseInt(number); inside actionPerformed: public void actionPerformed(ActionEvent e){ number = NumtextField.getNumtextField().getText(); int size = Integer.parseInt(number); } When the program starts, its trying to parse "", which is not a valid number string hence why you are getting an exception. Also maybe you should put that inside a try{}catch{} block, so in case you get an exception in real time you can handle it: try { int size = Integer.parseInt(number); } catch (NumberFormatException e) { System.out.println("Thats not a valid number"); }
unknown
d7920
train
The problem is that you have Main with a capital letter. Java is case-sensitive. The full method signature is: public static void main(String [] args) A: Your main method needs to be a lowercase "main". A: "main" must be in lowercase only. Java method names are case-sensitive.
unknown
d7921
train
What database driver are you using? ArrayField requires postgresql.
unknown
d7922
train
There is nothing like this build in. That said you can do this by yourself. Just add a ChannelInboundHandlerAdapter to the childHandler method that overrides channelActive(...). Then schedule a timer that will check if this method was called within time X and if not close the Channel.
unknown
d7923
train
Twilio developer evangelist here. I'm afraid there is no bulk SMS message endpoint. For each message you send you need to make a new request to the API. I'd recommend doing this using a background process so that it doesn't tie up server processes as that can take quite a long time if you are trying to send a lot of messages. Edit This answer was correct at the time, however recently the Passthrough API was announced in which you can send messages to up to 10,000 numbers at the same time. Check out the details in this blog post here: https://www.twilio.com/blog/2017/08/bulk-sms-with-one-api-request.html
unknown
d7924
train
One should use gtk_disable_setlocale() or whatever the language analogue is to bypass locales from GTK. Should be called prior to any subsequent calls of functions that enter the gtk main loop. That is the intended behavior of GTK, because it supports internationalization, but I am not sure why it changes the locale globally.
unknown
d7925
train
A jar file is immutable, for security reasons. You cannot save data back to a file stored in a jar file. Data saved from a Java program must be stored outside the classpath. Where that is, is up to you. If you program must ship with a sample/default file, to get started, you code can try reading the file from the external location. If not found there, read from the sample/default file in the jar file. After updating content in memory, save to external location, where it will be read from on next execution. A: You can make use of Classloader to read the file present in jar, but ofcourse you will not be able to write to it. To be able to read and write both file should be present in filesystem, you may want to have a look at Read and Write to Java file via Resource
unknown
d7926
train
This reason that this hasn't been answered is because you're actually asking for quite a lot of work to be done to make this happen. In essence, you're looking to pass data from your table into a modal dialog <div class="dialog" id="loslegen-dialog">. Most likely onclick. There are many ways to do this, the way I would personally do it would be to use the dialogOeffnen function which causes the dialog (popup) to open. Create span elements around the data you want to use in your dialog i.e. <td> <span id="id_element"><?php echo $row["ID"];?></span><br> </td> and <td> <span id="title_element"><?php echo $row["Titel"];?></span><br> </td> Then ensure you have elements with specific ID attributes where you'd like to display this data i.e. <h1 id="dialog_title"><?php //echo $row["Titel"]; //You can remove this ?></h1> Then inside dialogOeffnen before you display the modal/popup: document.getElementById("dialog_title").innerText = document.getElementById("title_element").innerText;
unknown
d7927
train
In TFS 2012, you should be able to go the same screen you create the areas and double click (or right click on select edit) on the area you want to rename. At that point, you should be able to modify the name accordingly.
unknown
d7928
train
You should use the EJB embedded container: http://www.adam-bien.com/roller/abien/entry/embedding_ejb_3_1_container
unknown
d7929
train
build this using only background instead of inner divs and rely on percentage values: .tree { border:1px solid; width:100px; display:inline-block; background: radial-gradient(circle at 36% 51%,green 22%,transparent 23%), radial-gradient(circle at 52% 37%,green 22%,transparent 23%), radial-gradient(circle at 64% 52%,green 22%,transparent 23%), linear-gradient(brown,brown) bottom/15% 50%; background-repeat:no-repeat; } .tree:before { content:""; display:block; padding-top:150%; } <div class="tree"></div> <div class="tree" style="width:200px;"></div> <div class="tree" style="width:250px;"></div> <div class="tree" style="width:50px;"></div> A: I am not sure why you cannot do it: Also keep the css code separate it is easy to manage, I have modified for you. <style> .tree { border: 1px solid black; position: relative; left: 20px; right: 20px; height: 300px; /* you can do it here */ width: 300px; /* you can do it here */ } #leaf1 { height: 90px; width: 90px; background-color: green; border-radius: 60px; position: absolute; left: 40px; top: 80px; } #leaf2 { height: 90px; width: 90px; background-color: green; border-radius: 60px; position: absolute; left: 100px; top: 85px; } #leaf3 { height: 90px; width: 90px; background-color: green; border-radius: 60px; position: absolute; left: 80px; top: 40px; } #stem { height: 150px; width: 30px; background-color: brown; position: absolute; left: 100px; top: 100px; z-index: -1; } </style> <div class="tree">Parent Div <div id="leaf1"></div> <div id="leaf2"></div> <div id="leaf3"></div> <div id="stem"></div> </div>
unknown
d7930
train
By adding just act.fct = "tanh" parameter in the model, everything runs smoothly. Here is the working version: library(neuralnet) Main <- read.table("miRNAs200TypesofCancerData.txt", header = TRUE,stringsAsFactors = T ) # reading the dataset for(i in 1:ncol(Main)){ Main[is.na(Main[,i]), i] <- mean(Main[,i], na.rm = TRUE) } set.seed(123) # in the following line, if you replace p=0.55 by p=0.5, no problem is reported and everything works smoothly indexes = createDataPartition(Main$Type, p=0.55, list = F) # Creating test and train sets. train = Main[indexes, ] test = Main[-indexes, ] xtest = test[, -1] ytest = test[, 1] nnet = neuralnet(Type~., train, hidden = 5, act.fct="tanh", linear.output = FALSE) # Plotting plot(nnet, rep = "best") # Predictions ypred = neuralnet::compute(nnet, xtest) yhat = ypred$net.result yhat=data.frame("yhat"=ifelse(max.col(yhat[ ,1:4])==1, "Mesenchymal", ifelse(max.col(yhat[ ,1:4])==2, "Proneural", ifelse(max.col(yhat[ ,1:4])==3, "Classical","Neural")))) # Confusion matrix cm = confusionMatrix(as.factor(yhat$yhat),as.factor(ytest)) print(cm)
unknown
d7931
train
The getchar behavior For linux the EOF char is written with ctrl + d, while on Windows it is written by the console when you press enter after changing an internal status of the CRT library through ctrl + z (this behaviour is kept for retrocompatibility with very old systems). If I'm not wrong it is called soft end of file. I don't think you can bypass it, since the EOF char is actually consumed by your getchar when you press enter, not when you press ctrl + z. As reported here: In Microsoft's DOS and Windows (and in CP/M and many DEC operating systems), reading from the terminal will never produce an EOF. Instead, programs recognize that the source is a terminal (or other "character device") and interpret a given reserved character or sequence as an end-of-file indicator; most commonly this is an ASCII Control-Z, code 26. Some MS-DOS programs, including parts of the Microsoft MS-DOS shell (COMMAND.COM) and operating-system utility programs (such as EDLIN), treat a Control-Z in a text file as marking the end of meaningful data, and/or append a Control-Z to the end when writing a text file. This was done for two reasons: * *Backward compatibility with CP/M. The CP/M file system only recorded the lengths of files in multiples of 128-byte "records", so by convention a Control-Z character was used to mark the end of meaningful data if it ended in the middle of a record. The MS-DOS filesystem has always recorded the exact byte-length of files, so this was never necessary on MS-DOS. *It allows programs to use the same code to read input from both a terminal and a text file. Other information are also reported here: Some modern text file formats (e.g. CSV-1203[6]) still recommend a trailing EOF character to be appended as the last character in the file. However, typing Control+Z does not embed an EOF character into a file in either MS-DOS or Microsoft Windows, nor do the APIs of those systems use the character to denote the actual end of a file. Some programming languages (e.g. Visual Basic) will not read past a "soft" EOF when using the built-in text file reading primitives (INPUT, LINE INPUT etc.), and alternate methods must be adopted, e.g. opening the file in binary mode or using the File System Object to progress beyond it. Character 26 was used to mark "End of file" even if the ASCII calls it Substitute, and has other characters for this. If you modify your code like that: #include <stdio.h> int main() { while(1) { char c = getchar(); printf("%d\n", c); if (c == EOF) // tried with also -1 and 26 break; } return 0; } and you test it, on Windows you will see that the EOF (-1) it is not written in console until you press enter. Beore of that a ^Z is printed by the terminal emulator (I suspect). From my test, this behavior is repeated if: * *you compile using the Microsoft Compiler *you compile using GCC *you run the compiled code in CMD window *you run the compiled code in bash emulator in windows Update using Windows Console API Following the suggestion of @eryksun, I successfully written a (ridiculously complex for what it can do) code for Windows that changes the behavior of conhost to actually get the "exit when pressing ctrl + d". It does not handle everything, it is only an example. IMHO, this is something to avoid as much as possible, since the portability is less than 0. Also, to actually handle correctly other input cases a lot more code should be written, since this stuff detaches the stdin from the console and you have to handle it by yourself. The methods works more or less as follows: * *get the current handler for the standard input *create an array of input records, a structure that contains information about what happens in the conhost window (keyboard, mouse, resize, etc.) *read what happens in the window (it can handle the number of events) *iterate over the event vector to handle the keyboard event and intercept the required EOF (that is a 4, from what I've tested) for exiting, or prints any other ascii character. This is the code: #include <windows.h> #include <stdio.h> #define Kev input_buffer[i].Event.KeyEvent // a shortcut int main(void) { HANDLE h_std_in; // Handler for the stdin DWORD read_count, // number of events intercepted by ReadConsoleInput i; // iterator INPUT_RECORD input_buffer[128]; // Vector of events h_std_in = GetStdHandle( // Get the stdin handler STD_INPUT_HANDLE // enumerator for stdin. Others exist for stdout and stderr ); while(1) { ReadConsoleInput( // Read the input from the handler h_std_in, // our handler input_buffer, // the vector in which events will be saved 128, // the dimension of the vector &read_count); // the number of events captured and saved (always < 128 in this case) for (i = 0; i < read_count; i++) { // and here we iterate from 0 to read_count switch(input_buffer[i].EventType) { // let's check the type of event case KEY_EVENT: // to intercept the keyboard ones if (Kev.bKeyDown) { // and refine only on key pressed (avoid a second event for key released) // Intercepts CTRL + D if (Kev.uChar.AsciiChar != 4) printf("%c", Kev.uChar.AsciiChar); else return 0; } break; default: break; } } } return 0; } A: while(getchar() != EOF) { if( getchar() == EOF ) break; } return 0; Here it is inconsistent. If getchar() != EOF it will enter the loop, otherwise (if getchar() == EOF) it will not enter the loop. So, there is no reason to check getchar() == EOF inside the loop. On the other hand, you call getchar() 2 times, you wait to enter 2 characters instead of only 1. What did you try to do ?
unknown
d7932
train
the postgresql.conf setting will log all queries on all databases. You must restart (or at least reload) PostgreSQL after editing that setting (out of habit I always do a restart). Other options are available though which are not such of a broad stroke (and these override that setting so may be also causing your issue: ALTER USER foo SET log_statements = 'all'; This will log all statements by database user foo. ALTER DATABASE foo SET log_statements = 'all'; This will log all statements in the foo database. Iirc the order of precidence is user, database, postgresql.conf value.
unknown
d7933
train
Are you using the REPL or IJulia? If you close the figure then it won't show you the plot. Is that what you want? a = rand(50,40) ioff() #turns off interactive plotting fig = figure() imshow(a) close(fig) If that doesn't work you might need to turn off interactive plotting using ioff() or change the matplotlib backend (pygui(:Agg)) (see here: Calling pylab.savefig without display in ipython) Remember that most questions about plotting using PyPlot can be worked out by reading answers from the python community. And also using the docs at https://github.com/JuliaPy/PyPlot.jl to translate between the two :) A: close() doesn't require any arguments so you can just call close() after saving the figure and create a new figure using PyPlot a = rand(50,40) imshow(a) savefig("a.png") # call close close()
unknown
d7934
train
The aggregation operation in shell: db.collection.aggregate([ {$sort:{"nMapRun.hosts.distance.value":-1}}, {$limit:10}, {$group:{"_id":null,"values":{$push:"$nMapRun.hosts.distance.value"}}}, {$project:{"_id":0,"values":1}} ]) You need to build the corresponding DBObjects for each stage as below: DBObject sort = new BasicDBObject("$sort", new BasicDBObject("nMapRun.hosts.distance.value", -1)); DBObject limit = new BasicDBObject("$limit", 10); DBObject groupFields = new BasicDBObject( "_id", null); groupFields.put("values", new BasicDBObject( "$push","$nMapRun.hosts.distance.value")); DBObject group = new BasicDBObject("$group", groupFields); DBObject fields = new BasicDBObject("values", 1); fields.put("_id", 0); DBObject project = new BasicDBObject("$project", fields ); Running the aggregation pipeline: List<DBObject> pipeline = Arrays.asList(sort, limit, group, project); AggregationOutput output = coll.aggregate(pipeline); output.results().forEach(i -> System.out.println(i));
unknown
d7935
train
You can return the number of rows in your query as another column: SELECT id, name, pass, count(*) over () as rows FROM users Keep in mind that this is telling you the number of rows returned by the query, not the number of rows in the table. However, if you specify a "TOP n" in your select, the rows column will give you the number of rows that would have been returned if you didn't have "Top n" A: If you're trying to paginate the trick is to query one more record than you actually need for the current page. By counting the result (mysql_num_rows) and comparing that to your page size, you can then decide if there is a 'next page'. If you were using mysql you could also use SQL_CALC_FOUND_ROWS() in your query, which calculates the number of rows that would be returned without the LIMIT clause. Maybe there is an equivalent for that in MsSQL? A: I assume that you are inserting manually the first 2 rows of your table. According to that, my idea is to just do a select where the id is more than 2 like this: SELECT * FROM users WHERE id > 2; I also assume that you are using PHP so mysql_num_rows will return you 0 if no data is found, otherwise it will return you the number of rows from your query and now you know that you need to do a while or some loop to retrieve the data after id number 2.
unknown
d7936
train
$slices = json_decode(file_get_contents('http://27.109.19.234/decoraidnew/wp-json/custom/v1/all-posts'),true); if ($slices) { foreach ($slices as $slice) { $title = $slice[1]; } } $my_post = array( 'post_title' => $title, 'post_content' => 'This is my content', 'post_status' => 'publish', 'post_author' => 1, 'post_category' => array(8,39) ); $post_id = wp_insert_post( $my_post, $wp_error );
unknown
d7937
train
The elements should have an id="email" to allow the selector: $('.' + parentname.attr('class') + ' #email')
unknown
d7938
train
Please check this Link: You can add in your menifest for the activity you want to prevent such issue. Also make sure if you are having a bit more content use scrollView as a parent. And soft input mode as "adjustResize" android:windowSoftInputMode="adjustResize" or android:windowSoftInputMode="adjustPan" you can use as per your need. adjustResize to ensure that the system resizes your layout to the available space—which ensures that all of your layout content is accessible (even though it probably requires scrolling)—use this one. adjustPan The activity's main window is not resized to make room for the soft keyboard, and the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. adjustNothing Do nothing with layouts
unknown
d7939
train
When crafting a file like this it's always good to do so using Explorer or Notepad first, then write/adjust your code to match whatever was produced. Otherwise, it's harder to figure out if the problem is with your file or your code. I believe the minimum requirements to make this work is Desktop.ini must be marked System and the parent directory must be marked ReadOnly (System may work there as well, but I know ReadOnly definitely does). So, your code is working with the right attributes, but there are still a few problems. Your if ... else ... block is saying "If a file exists at this path, create a directory at that path, then delete the file at that path, then create a file at that path." Of course, the directory should not and cannot have the same path as the file. I assume you are deleting and recreating the file to clear the contents when it already exists, however File.Create() overwrites (truncates) existing files, making the calls to both File.Delete() and File.Exists() unnecessary. More importantly is this line... di.Attributes &= ~FileAttributes.ReadOnly; ...with which there are two problems. First, you are ANDing the directory's attributes with the negation of ReadOnly, which has the effect of removing ReadOnly and keeping the other attributes the same. You want to ensure ReadOnly is set on the directory, so you want to do the opposite of the code you used: OR the directory's attributes with ReadOnly (not negated)... di.Attributes |= FileAttributes.ReadOnly; Also, you need that attribute set regardless of whether you created the directory or not, so that line should be moved outside of the if ... else .... Another issue is the successive calls to File.SetAttributes(). After those three calls the file's attributes will be only Hidden, since that was the value of the last call. Instead, you need to combine (bitwise OR) those attributes in a single call. A couple of other minor tweaks... * *As you know since you are calling Dispose() on it, File.Create() returns a FileStream to that file. Instead of throwing it away, you could use it to create your StreamWriter, which will have to create one, anyways, under the covers. Better yet, call File.CreateText() instead and it will create the StreamWriter for you. *Environment variables are supported in Desktop.ini files, so you don't have to expand them yourself. This would make the file portable between systems if, say, you copied it from one system to another, or the directory is on a network share accessed by multiple systems with different %SystemRoot% values. Incorporating all of the above changes your code becomes... // Create a new directory, or get the existing one if it exists DirectoryInfo directory = Directory.CreateDirectory(@"C:\Users\np\Desktop\PUTEST"); directory.Attributes |= FileAttributes.ReadOnly; string filePath = Path.Combine(directory.FullName, "desktop.ini"); string iconPath = @"%SystemRoot%\system32\SHELL32.dll"; string iconIndex = "-183"; using (TextWriter tw = File.CreateText(filePath)) { tw.WriteLine("[.ShellClassInfo]"); tw.WriteLine("IconResource=" + iconPath + "," + iconIndex); //tw.WriteLine("IconFile=" + iconPath); //tw.WriteLine("IconIndex=" + iconIndex); } File.SetAttributes(filePath, FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden); One catch is that the above code throws an exception if you run it twice in succession. This is because the File.Create*() methods fail if the input file is Hidden or ReadOnly. We could use new FileStream() as an alternative, but that still throws an exception if the file is ReadOnly. Instead, we'll just have to remove those attributes from any existing input file before opening it... // Create a new directory, or get the existing one if it exists DirectoryInfo directory = Directory.CreateDirectory(@"C:\Users\np\Desktop\PUTEST"); directory.Attributes |= FileAttributes.ReadOnly; string filePath = Path.Combine(directory.FullName, "desktop.ini"); FileInfo file = new FileInfo(filePath); try { // Remove the Hidden and ReadOnly attributes so file.Create*() will succeed file.Attributes = FileAttributes.Normal; } catch (FileNotFoundException) { // The file does not yet exist; no extra handling needed } string iconPath = @"%SystemRoot%\system32\SHELL32.dll"; string iconIndex = "-183"; using (TextWriter tw = file.CreateText()) { tw.WriteLine("[.ShellClassInfo]"); tw.WriteLine("IconResource=" + iconPath + "," + iconIndex); //tw.WriteLine("IconFile=" + iconPath); //tw.WriteLine("IconIndex=" + iconIndex); } file.Attributes = FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden; I changed from using File to FileInfo since that makes this a little easier.
unknown
d7940
train
Using apply with a custom function. Ex: import ast breakfastMenu=['Pancake', 'Coffee', 'Eggs', 'Cereal'] dinnerMenu=['Salmon', 'Fish&Chips', 'Pasta', 'Shrimp'] lunchMenu=['Steak', 'Fries', 'Burger', 'Chicken', 'Salad'] check_val = {'Breakfast': breakfastMenu, 'Dinner': dinnerMenu, "Lunch": lunchMenu} data = [['ORDB10489', 'Lunch', "[('Coffee', 4), ('Salad', 10), ('Chicken', 8)]"], ['ORDZ00319', 'Dinner', "[('Fish&Chips', 9), ('Pasta', 5), ('Egg', 3)]"], ['ORDB00980', 'Dinner', "[('Pasta', 6), ('Fish&Chips', 10)]"], ['ORDY10003', 'Breakfast', "[('Coffee', 2), ('Cereal', 1)]"], ['ORDK04121', 'Lunch', "[('Steak', 9), ('Chicken', 5)]"]] df = pd.DataFrame(data, columns=['order_id', 'order_type', 'order_items']) df["order_items"] = df["order_items"].apply(ast.literal_eval) df["order_items"] = df.apply(lambda x: [i for i in x["order_items"] if i[0] in check_val.get(x["order_type"], [])], axis=1) print(df) Output: order_id order_type order_items 0 ORDB10489 Lunch [(Salad, 10), (Chicken, 8)] 1 ORDZ00319 Dinner [(Fish&Chips, 9), (Pasta, 5)] 2 ORDB00980 Dinner [(Pasta, 6), (Fish&Chips, 10)] 3 ORDY10003 Breakfast [(Coffee, 2), (Cereal, 1)] 4 ORDK04121 Lunch [(Steak, 9), (Chicken, 5)] A: So, I think there is a solution without any essential for loops. Just using some joins. But before we can achieve that, we have to bring the data to a more suitable shape. flattened_items = df.order_items.apply(pd.Series).stack().reset_index().assign( **{"order_item": lambda x:x[0].str[0], "item_count": lambda x:x[0].str[1]}) print(flattened_items.head()) level_0 level_1 0 order_item item_count 0 0 0 (Coffee, 4) Coffee 4 1 0 1 (Salad, 10) Salad 10 2 0 2 (Chicken, 8) Chicken 8 3 1 0 (Fish&Chips, 9) Fish&Chips 9 4 1 1 (Pasta, 5) Pasta 5 So essentially, I just flattened the list of tuple into two columns. Note, for your setup to work, you might need to run reset_index one on the original Dataframe df (otherwise it's like your sample from Dataframe) Next we create a Dataframe that apps meals to items via flattend_orders = pd.merge(df[["order_id", "order_type"]], flattened_items[["level_0","order_item", "item_count"]], left_index=True, right_on="level_0").drop("level_0", axis=1) meal_dct = {"Breakfast": breakfastMenu, "Lunch": lunchMenu, "Dinner": dinnerMenu} meal_df = pd.DataFrame.from_dict(meal_dct, orient="index").stack().reset_index( ).drop("level_1", axis=1).rename(columns={"level_0": "Meal", 0: "Item"}) which looks like print(meal_df.head()) Meal Item 0 Breakfast Pancake 1 Breakfast Coffee 2 Breakfast Eggs 3 Breakfast Cereal 4 Lunch Steak Now, we can just do an inner join on the order_type and order_item merged = pd.merge(flattend_orders, meal_df, left_on=["order_type", "order_item"], right_on=["Meal", "Item"]).drop(["Meal", "Item"], axis=1) and we obtain order_id order_type order_item item_count 0 ORDB10489 Lunch Salad 10 1 ORDB10489 Lunch Chicken 8 2 ORDK04121 Lunch Chicken 5 3 ORDZ00319 Dinner Fish&Chips 9 4 ORDB00980 Dinner Fish&Chips 10 5 ORDZ00319 Dinner Pasta 5 6 ORDB00980 Dinner Pasta 6 7 ORDY10003 Breakfast Coffee 2 8 ORDY10003 Breakfast Cereal 1 9 ORDK04121 Lunch Steak 9 Now, this is maybe already good enough, but you might prefer to have a list of tuples back. To this end: merged.groupby(["order_id", "order_type"]).apply(lambda x: list(zip(x["order_item"], x["item_count"]))).reset_index().rename(columns={0:"order_items"}) gives order_id order_type order_items 0 ORDB00980 Dinner [(Fish&Chips, 10), (Pasta, 6)] 1 ORDB10489 Lunch [(Salad, 10), (Chicken, 8)] 2 ORDK04121 Lunch [(Chicken, 5), (Steak, 9)] 3 ORDY10003 Breakfast [(Coffee, 2), (Cereal, 1)] 4 ORDZ00319 Dinner [(Fish&Chips, 9), (Pasta, 5)] Note that the ugliness here is due to converting data from (maybe) insufficient formats. Also all for loops and apples just come from data transformation. Essentially, my answer can be summarized as: pd.merge(df, df_meal) if we assume just the right data format. Btw, I just chose item_count as a name as a best guess. A: This is something you probably want to do in an Apply-function. Given that the breakfastMenu, dinnerMenu and lunchMenu are defined on the top of the script, the following function would work: def check_correct(x): if x['order_type'] == 'lunch': current_menu = lunchMenu elif x['order_type'] == 'dinner': current_menu = dinnerMenu else: current_menu= breakfastMenu current_menu = [x.lower() for x in current_menu] return_list = [] for item, _ in x['order_items']: return_list.append(item.lower() in current_menu) return return_list You can create a new column inside the DataFrame with: df.apply(check_correct, axis = 1). It will give you a list with the True and False mathes. The first line would result in the following output: [False, True, True] A: for index, row in df.iterrows(): new = [] if row["order_type"] == "Breakfast": order_type = breakfastMenu elif row["order_type"] == "Dinner": order_type = dinnerMenu elif row["order_type"] == "Lunch": order_type = lunchMenu else: continue a = row["order_items"][1:-1] b = a.split(",") for i in range(0,len(b),2): meal = b[i].strip()[2:-1] if meal in order_type: new.append([meal, b[i+1]]) row["order_items_new"] = new print(df["order_items_new"]) 0 [[Salad, 10)], [Chicken, 8)]] 1 [[Fish&Chips, 9)], [Pasta, 5)]] 2 [[Pasta, 6)], [Fish&Chips, 10)]] 3 [[Coffee, 2)], [Cereal, 1)]] 4 [[Steak, 9)], [Chicken, 5)]]
unknown
d7941
train
To prevent matplotlib from stealing the focus of your Window you need to tell it to do so for some strange reason (maybe because of high usage of MPL in IPython notebook?) import matplotlib matplotlib.use('Agg') After those lines the window should stop stealing. The updating on the other hand is something way different and that's why there's garden.graph and garden.matplotlib. If you intend to just draw some simple plots, just use the Graph. If you really need MPL and/or you want to do something complex, use the MPL backend (garden.matplotlib).
unknown
d7942
train
The List.containsAll method behaves just as documented: it returns true if all the elements of the given collection belong to this collection, false otherwise. The docs say nothing about the order or cardinality of the elements. The documentation for containsAll does not explicitly say how it determines whether an element belongs to the Collection. But the documentation for contains (which is implicitly specifying the semantics of "contains") does: it uses equals. Again, no mention of cardinality. The containsAll method is declared in the Collection interface and re-declared in the List and Set interfaces, but it's first implemented in the Collection hierarchy by the AbstractCollection class, as follows: public boolean containsAll(Collection<?> c) { for (Object e : c) if (!contains(e)) return false; return true; } As far as I know, this implementation is inherited by most common classes that implement the Collection interface in the Java Collections framework, except for the CopyOnWriteArrayList class and other specialized classes, such as empty lists and checked and immutable wrappers, etc. So, if you look at the code, you'll see that it fulfils the docs you quoted: Returns true if this list contains all of the elements of the specified collection. In the docs of the AbstractList.containsAll method, there's also an @implSpec tag, which says the following: @implSpec This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned, otherwise false. With regard to possible optimizations, they're all relayed to the different implementations of the contains method, which is also implemented by AbstractCollection in a naive, brute-force-like way. However, contains is overriden in i.e. HashSet to take advantage of hashing, and also in ArrayList, where it uses indexes, etc. A: You can iterate over one list and remove elements by value from another, then check if another list size == 0. If it is, then that means all second list elements were present in first list at least as many times as in the second list. public boolean containsAll(List<Character> source, List<Character> target) { for (Character character : source) { target.remove(character); if (target.isEmpty()) { return true; } } return target.size() == 0; } HashMap will be more efficient if lists are huge public static boolean containsAll(List<Character> source, List<Character> target) { Map<Character, Long> targetMap = target.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); for (Character character : source) { Long count = targetMap.get(character); if (count != null) { if (count > 1) { targetMap.put(character, --count); } else { targetMap.remove(character); } } } return targetMap.isEmpty(); }
unknown
d7943
train
Ok, I'm not sure if this is exactly what you wanted, but I'm posting my modified query below. First of all, I got rid of the implicit join and changed it with an explicit INNER JOIN. I also moved your subquerys with LEFT JOINs for better performance. And I deleted the DISTINCT and the GROUP BY because I couldn't really understand why you needed them. SELECT `g`.`id` , `g`.`steam_id` , `g`.`type` , `g`.`title` , `g`.`price` , `g`.`metascore` , `g`.`image`, `gp`.`id` AS `promotion_id`, `gp`.`price` AS `promotion_price`, `bg`.`copies` FROM `games` AS `g` INNER JOIN `game_genres` AS `gg` ON `gg`.`game_id` = `g`.`id` LEFT JOIN `game_promotions` as `gp` ON `g`.`id` = `gp`.`game_id` LEFT JOIN ( SELECT `game_id`, COUNT(`id`) `copies` FROM `bot_games` WHERE `buyer` IS NULL GROUP BY `game_id`) `bg` ON `bg`.`game_id` = `g`.`id` WHERE `g`.`title` LIKE "Counter%" LIMIT 0 , 30 A: Do you mean the result is 24.9899997711182? That's within the single precision float margin of error. You get the expected result, you just have to round it to two decimals for display.
unknown
d7944
train
Try the form with this instead, passing in the $contact->id as a param rather than directly in the URL: {{ Form::open(array('method' => 'DELETE', 'action' => array('ContactController@destroy', $contact->id )) }}
unknown
d7945
train
I would closely follow the relationship patterns in the documentation: https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html As an example assuming you wanted a one-to-one relationship between owners and owndnis... One to One class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child = relationship("Child", uselist=False, back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent", back_populates="child") Untested but following this pattern and in your case treating owners as the parent: # Treated as Parent of One to One class owners(db.Model): __tablename__ = 'owners' ownerid = db.Column('ownerid', db.String(60), primary_key=True) <--- changed primary key name = db.Column('ownerdomainname', db.String(60), nullable=False) spownerid = db.Column('spownerid', db.String(60)) dnis = db.relationship("owndnis", uselist=False, back_populates="owners") <--- note change # child = relationship("Child", uselist=False, back_populates="parent") # Treated as Child of One to One class owndnis(db.Model): __tablename__ = 'owndnis' ownerid = db.Column('ownerid', db.String(60), primary_key=True, db.ForeignKey('owners.ownerid')) <-- both a PK and FK dnisstart = db.Column('dnisstart', db.String(20), nullable=False) dnisend = db.Column('dnisend', db.String(20)) owner = relationship("owners", back_populates="owndnis") <--- added # parent = relationship("Parent", back_populates="child") I've used back_populates but per the docs: As always, the relationship.backref and backref() functions may be used in lieu of the relationship.back_populates approach; to specify uselist on a backref, use the backref() function: class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) child_id = Column(Integer, ForeignKey('child.id')) child = relationship("Child", backref=backref("parent", uselist=False))
unknown
d7946
train
which is the default data grouping(default unit option) in highstock There's a little flaw in the API (https://api.highcharts.com/highstock/series.column.dataGrouping.units) in units section. First it says that it defaults to: units: [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1] ], [ 'week', [1] ], [ 'month', [1, 3, 6] ], [ 'year', null ]] and after that "Defaults to undefined." line appears. The first one is correct. Highcharts automatically finds the best grouping unit from units array. So, in other words: units specifies which groupings can be applied if Highcharts decides that applying data grouping is a good idea. Enable dataGrouping.forced and use only one key-value pair in units array if you want to make sure that this grouping will be used no matter what e.g.: units: [[ 'hour', [3] ] // Data will always be grouped into 3 hours periods These're just general rules - they should be enough to use data grouping successfully.
unknown
d7947
train
You should not cache access tokens on the backend of a web application ,if you can store them client side and send them with each request. In case you don't have possibility to store it at client side (possible case your API is talking to some message client like USSD,SMS etc),It will be expensive to get an OAuth access token, because it requires an HTTP request to the token endpoint. This case is a good example where you can cache tokens whenever possible. You can make use of REDIS if you have multiple instances. REMEMBER : Tokens are sensitive data, because they grant access to a user's resources. (Moreover, unlike a user's password, you can't just store a hash of the token.) Therefore, it's critical to protect tokens from being compromised. You can make use of encryption.Do check below links for more details : https://auth0.com/docs/best-practices/token-best-practices. https://github.com/auth0/express-openid-connect/blob/master/EXAMPLES.md#5-obtaining-and-storing-access-tokens-to-call-external-apis https://learn.microsoft.com/en-us/azure/architecture/multitenant-identity/token-cache As per Auth0 Token Best Practices Store and reuse. Reduce unnecessary roundtrips that extend your application's attack surface, and optimize plan token limits (where applicable) by storing access tokens obtained from the authorization server. Rather than requesting a new token, use the stored token during future calls until it expires. How you store tokens will depend on the characteristics of your application: typical solutions include databases (for apps that need to perform API calls regardless of the presence of a session) and HTTP sessions (for apps that have an activity window limited to an interactive session). For an example of server-side storage and token reuse, see Obtaining and Storing Access Tokens to Call External APIs in our Github repo
unknown
d7948
train
The problem is most likely this line if ((N11 = N6 = N7)) = in C# is assignment; you're most likely looking for equality, which is == Changing the above to this should fix it for you. if (N11 == N6 && N11 == N7) A: To handle your comparison, you need: if ((N11 == N6) && (N11 == N7)) Or, simplified: if (N11 == N6 && N11 == N7) Note the == (comparison) instead of = (assignment). Also, you need to do two separate comparisons to check to see if the three values are equal. In addition, right now you're using int.Parse, but assigning to a double. You should likely use double.Parse instead: double N1 = double.Parse(TB_S1.Text); You may also want to consider using double.TryParse, as this will better handle errors in user input: double N1; if(!double.TryParse(TB_S1.Text, out N1)) { MessageBox.Show("Please enter a valid value in TB_S1"); return; } A: Try this:- if ((N11 == N6) && (N11 == N7)) instead of if ((N11 = N6 = N7))
unknown
d7949
train
try below: $billings = DB::table("billings") ->select("billings.plan", "billings.email", DB::raw("COUNT(billings.plan) as total_plans"), DB::raw("SUM(billings.amount) as total_amount")) ->join("users", function ($join) { $join->on("users.email", "=", "billings.email") ->orOn("users.phone", "=", "billings.phone") }) ->groupBy("billings.plan") ->orderByRaw('billings.plan ASC'); A: $billings = DB::table("billings") ->select("billings.plan", "billings.email",DB::raw("COUNT(billings.plan) as total_plans") ,DB::raw("SUM(billings.amount) as total_amount")) ->join("users",function($join){ $join->on("users.email","=","billings.email"); $join->orOn("users.phone","=","billings.phone"); }) ->groupBy("billings.plan") ->orderByRaw('billings.plan ASC'); A: I think for this u need to use advanced join clause. Something like this:- DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id')->orOn(...); }) ->get();
unknown
d7950
train
as you're trying to use UserService in another module other than where it was registered (which was UserModule), you need to expose it, like this: @Module({ imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])], controllers: [UserController], providers: [UserService] exports: [UserService], // <<<< }) export class UserModule {} then remove UserService from EmailModule.
unknown
d7951
train
First of all, why do you need Hilt? What are you trying to Inject and where? ExampleApplication() is just a place where you configure app-wide settings, you are never supposed to call it from somewhere else, so you don't need that line. Furthermore, Which activity are you trying to start? MainActivity or ExampleActivity()? Calling ExampleActivity within MainActivity won't have any effect. SetContent { ... } is the place where you create the UI. If you want to open another activity from MainActivity then you need to implement navigation or use Intents.
unknown
d7952
train
I'm not sure your question has the right details. If these buttons are indeed Form Controls - and I think they must be because I believe ActiveX controls don't return a Caller - then their parent object is Shapes, and you would call the Text property from the Shape.TextFrame.Characters object. I wonder if your original worksheet had aCollection object called Buttons which contained, perhaps, a list of the buttons in the form of a class object, called Button (hence your error message) and which exposes the properties that are called in your code. Without that collection and class, the code would be more like this: Public Sub ChangeSomething() Dim btn As Shape With Application 'Check for correct data types. If Not TypeOf .ActiveSheet Is Worksheet Then Exit Sub If IsObject(.Caller) Then Exit Sub 'Acquire button On Error Resume Next Set btn = .ActiveSheet.Shapes(.Caller) On Error GoTo 0 'Check for a found button If btn Is Nothing Then Exit Sub End With 'Check for non-actionable button. With btn.TextFrame.Characters If .Count = 0 Then .Text = "x" Exit Sub End If End With 'If we've reached here, it's an actionable button. Debug.Print "Do something." 'Clear the button text. btn.TextFrame.Characters.Text = "" End Sub I rather suspect some half-copied code here, and the rest of the project remains elsewhere.
unknown
d7953
train
You must change the mapping for your property to use image type in the database. You can do that either with data annotations: [Column(TypeName = "image")] public Byte[] Image { get; set; } or with fluent API: modelBuilder.Entity<...>().Property(e => e.Image).HasColumnType("image");
unknown
d7954
train
Hi you have to go in the Play console, in "Store presence" section of your app, and in "Store listing", here you can change the listing of your app : the description, screenshots,... and all the information
unknown
d7955
train
To share code between the two projects create a Portable Class Library (PCL) project and reference it in the two projects. Make sure you choose the right .Net framework (for compatibility with WCF project).
unknown
d7956
train
This is probably because you haven't imported FlutterFragment in your activity, please add this line in your import statements. import io.flutter.embedding.android.FlutterFragment; Also, make sure to extend your activity from FlutterFragmentActivity. You will have to import it, add this line at the top of your file along with the other import statements. Like so: ... import io.flutter.app.FlutterFragmentActivity; ... Hope this helps :)
unknown
d7957
train
The DatePicker gives you a date object. Instead of storing the entire value string just grab the day month and year Date(value).getYear() + '-' + Date(value).getMonth() + '-' + Date(value).getDate(). As for the times do the same as the dates. Store those values in the DB and then when you get them back you will have to convert them back to a date object so that the date picker can understand them. Ultimately with this solution your just trying to store dates without the timezones. Make sure to state in your app that the times are for those areas. A: You have to distinguish between the format the date/time is transported, saved vs. how the date will be shown to the user. * *For transportation and saving use UTC in a format that is easy computable (eg. ISO8601). *For visualization to the user convert this value to the timezone and desired user format by using some helper library.
unknown
d7958
train
ZF use object for store session. When start session, php try unserialize $_SESSION variable and if not found object's class PHP create __PHP_Incomplete_Class Object. You should start session after classes autoload Set session.auto_start=0 for fix it.
unknown
d7959
train
to go to check from onlyWebsite, you may try the below xpath : //input[@name='onlyWebsite']/following-sibling::span/descendant::i if there are multiple span's as a following-sibling, you can try this : //input[@name='onlyWebsite']/following-sibling::span[1]/descendant::i
unknown
d7960
train
if(reverse.charAt(i)== reverse.charAt(j)){ return true; } You are returning true if the first and the last character are the same without going on to check any other character. I'd say the better approach is to continue stepping through the word until you find a character that does not match or until you finish. If you find a character that does not match, return false. If you finish, return true.
unknown
d7961
train
I think you can vectorize your function like this: import numpy as np def func_vec(a, b): ar = np.roll(a, 1, axis=0) ar[0] = 0 ac = np.cumsum(ar, axis=0) bc = np.maximum(b - ac, 0) return np.maximum(a - bc, 0) Quick test: import numpy as np def func(a, b): n = np.copy(a) m = np.copy(b) for i in range(len(n)): n[i] = np.where(n[i] >= m, n[i] - m, 0) m = np.maximum(0, m - a[i]) if not m.any(): return n return n np.random.seed(100) n = 100000 m = 10 num_max = 100 a = np.random.randint(num_max, size=(m, n)) b = np.random.randint(num_max, size=(1, n)) print(np.all(func(a, b) == func_vec(a, b))) # True However, your algorithm has an important advantage over the vectorized algorithm, which is that it stops the iteration when it finds that there is nothing else to subtract. This means that, depending on the size of the problem and the specific values (which is what determines when does the early stop happens, if at all), the vectorized solution may actually be slower. See for the above example: %timeit func(a, b) # 5.09 ms ± 78.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit func_vec(a, b) # 12.4 ms ± 939 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) You can, however, get something of a "best of both worlds" solution using Numba: import numpy as np import numba as nb @nb.njit def func_nb(a, b): n = np.copy(a) m = np.copy(b) zero = np.array(0, dtype=a.dtype) for i in range(len(n)): n[i] = np.maximum(n[i] - m, zero) m = np.maximum(zero, m - a[i]) if not m.any(): return n return n print(np.all(func(a, b) == func_nb(a, b))) # True %timeit func_nb(a, b) # 3.36 ms ± 461 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
unknown
d7962
train
This function is working in classic ASP: Function isGUID(byval strGUID) if isnull(strGUID) then isGUID = false exit function end if dim regEx set regEx = New RegExp regEx.Pattern = "^({|\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\))?$" isGUID = regEx.Test(strGUID) set RegEx = nothing End Function A: This is similar to the same question in c#. Here is the regex you will need... ^[A-Fa-f0-9]{32}$|^({|()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$ But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. To get an idea of just how complex it is to test for a valid GUID, look at the source code for one of the Guid constructors. A: In VBScript you can use the RegExp object to match the string using regular expressions. A: Techek's function did not work for me in classic ASP (vbScript). It always returned True for some odd reason. With a few minor changes it did work. See below Function isGUID(byval strGUID) if isnull(strGUID) then isGUID = false exit function end if dim regEx set regEx = New RegExp regEx.Pattern = "{[0-9A-Fa-f-]+}" isGUID = regEx.Test(strGUID) set RegEx = nothing End Function A: there is another solution: try { Guid g = new Guid(stringGuid); safeUseGuid(stringGuid); //this statement will execute only if guid is correct }catch(Exception){}
unknown
d7963
train
Have a look at something like this (full example) DECLARE @Store_Sales TABLE( Store INT, Date DATETIME, Sales FLOAT ) INSERT INTO @Store_Sales SELECT 1,'23 Apr 2010',10000 INSERT INTO @Store_Sales SELECT 2,'23 Apr 2010',11000 INSERT INTO @Store_Sales SELECT 1,'22 Apr 2010',10000 INSERT INTO @Store_Sales SELECT 2,'22 Apr 2010',10500 INSERT INTO @Store_Sales SELECT 1,'21 Apr 2010',10000 INSERT INTO @Store_Sales SELECT 2,'21 Apr 2010',10550 SELECT ss.Store, MIN(ss.Date) StartDate, MAX(ssNext.Date) EndDate, ss.Sales FROM @Store_Sales ss INNER JOIN @Store_Sales ssNext ON ss.Store = ssNext.Store AND ss.Date + 1 = ssNext.Date AND ss.Sales = ssNext.Sales GROUP BY ss.Store, ss.Sales
unknown
d7964
train
The problem is you're adding constraints to a button that already has been properly constrained. While you could remove all the constraints and recreate them, that is really inefficient and would not be recommended. I would recommend simply keeping a reference to the leading constraint, which will allow you to access it every time the button is tapped to modify the constant. To do this, implement a property for your leading constraint, like so: var leadingConstraint: NSLayoutConstraint! When you create this button, you'll want to properly constrain it as well. Here is where you'll be creating that special leading constraint. This is done outside of the button action function, perhaps in viewDidLoad: button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false //... leadingConstraint = button.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 0) NSLayoutConstraint.activateConstraints([ leadingConstraint, button.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 390), button.widthAnchor.constraintEqualToConstant(75), button.heightAnchor.constraintEqualToConstant(75) ]) Now when the button is tapped, you won't need to set translatesAutoresizingMaskIntoConstraints, and you can simply update the constant of the existing leading constraint. @IBAction func start(sender: UIButton) { button.hidden = false let randomNumber = Int(arc4random_uniform(180) + 30) leadingConstraint.constant = CGFloat(randomNumber) }
unknown
d7965
train
You have to go trough analyzer tool like this. Quoting introduction: The purpose of this tool is to analyze Java™ class files in order to learn more about the dependencies between those classes.
unknown
d7966
train
One option would be countrycode::countryname to convert the country names. Note: countrycode::countryname throws a warning so it will probably not work in all cases. But at least to me the cases where it fails are rather exotic and small countries or islands. library(ggplot2) library(countrycode) library(dplyr) library(tidyverse) worldmap <- map_data("world") # Set colors vec_AMIS_Market <- c("Canada", "China","United States of America", "Republic of Korea", "Russian Federation") worldmap_AMIS_Market <- mutate(worldmap, region = countryname(region), fill = ifelse(region %in% countryname(vec_AMIS_Market), "green", "lightgrey")) #> Warning in countrycode_convert(sourcevar = sourcevar, origin = origin, destination = dest, : Some values were not matched unambiguously: Ascension Island, Azores, Barbuda, Canary Islands, Chagos Archipelago, Grenadines, Heard Island, Madeira Islands, Micronesia, Saba, Saint Martin, Siachen Glacier, Sint Eustatius, Virgin Islands # Use scale_fiil_identity to set correct colors ggplot(worldmap_AMIS_Market, aes(long, lat, fill = fill, group=group)) + geom_polygon(colour="gray") + ggtitle("Map of World") + ggtitle("Availability of AMIS Supply and Demand Data - Monthly") + scale_fill_identity()
unknown
d7967
train
The issue was that in my Product class, I did not have the appropriate getters and setters. My getters in this case were case sensitive. Example of "bad code": public class Product { private int productID; public int getID() { return productID; } } Example of working code: public int getProductID() { return productID; } A small difference, but important.
unknown
d7968
train
I'm not an expert on StructureMap, but from the error I guess, you're creating a single instance (Singleton) from the DBContext. which will give you this error. Once you start a transaction, the context will be aware of it and handle your work, but after the transaction is complete you can't resuse the same dbcontext instance, you need to create a new one. A preferred method in web apps is to use a Context Per Request. Here is an example I found on SO.
unknown
d7969
train
Not sure exactly how but Mockito can be a good choice. Check this link for details.
unknown
d7970
train
Your problem is this message from VACUUM (VERBOSE): INFO: "test": found 0 removable, 10000 nonremovable row versions in 84 pages DETAIL: 9000 dead row versions cannot be removed yet. That probably means that there ia a long running concurrent transaction that might still need the old row versions from before you issued the DELETE. Terminate all log running transactions and it will work fine.
unknown
d7971
train
x is an unsigned char, meaning it is between 0 and 256. Since an int is bigger than a char, casting unsigned char to signed int still retains the chars original value. Since this value is always >= 0, your if is always true. A: All the values of an unsigned char can fir perfectly in your int, so even with the cast you will never get a negative value. The cast you need is to signed char - however, in that case you should declare x as signed in the function signature. There is no point lying to the clients that you need an unsigned value while in fact you need a signed one. A: Even with the cast, the comparison is still true in all cases of defined behavior. The compiler still determines that (signed int)0 has the value 0, and still determines that (signed int)x) is non-negative if your program has defined behavior (casting from unsigned to signed is undefined if the value is out of range for the signed type). So the compiler continues warning because it continues to eliminate the else case altogether. Edit: To silence the warning, write your code as #define VALUE 0 int test(unsigned char x) { #if VALUE==0 return 1; #else return x>=VALUE; #endif } A: The #define of VALUE to 0 means that your function is reduced to this: int test(unsigned char x) { if (x>=0) return 0; else return 1; } Since x is always passed in as an unsigned char, then it will always have a value between 0 and 255 inclusive, regardless of whether you cast x or 0 to a signed int in the if statement. The compiler therefore warns you that x will always be greater than or equal to 0, and that the else clause can never be reached.
unknown
d7972
train
You forgot to pass the func predicate along, and don't name your function filter, that clashes with a built-in procedure. Try this: (define (my-filter func lst) (countNumber (filter func lst))
unknown
d7973
train
@decorator(request_id=get_request_id()) <- this line is executed when your module is imported. Which means your getter function is called only once, when the module is imported, not each time your decorated function is called. To fix it, just pass the getter function, not its result, to the decorator, and make the call inside the wrapper function, inside the decorator. (For that, just leave the parentheses out): def decorator(request_id_getter=None, *d_args, **d_kw): def logger(func): # other arguments than the first positional arg here are not used at all. @wraps(func, *d_args, **d_kw) def wrapper(*args, **kwargs): request_id = request_id_getter() # and here the value is retrieved when the function is actually called try: res = func() print() return res except Exception: pass return wrapper return logger @app.get('/test') @decorator(request_id=get_request_id) # <- here is the change - do not _call_ the function! def test_purpose(request_id=get_request_id()): print('get_correlation_id() start', get_request_id()) return 'ok'
unknown
d7974
train
You may want to try live binding the event and see if that makes a difference. The other issue may be your css as the italic tag is an inline element you may not have a decent target area for the click event (this space can vary from browser to browser). You may want to try binding to the parent button tag instead as this should contain the child element. Also since there is no default action to an italic tag or button there is no reason to include a preventDefault() or return false. $(function(){ $(document).on("click", "#serach-button", function() { if($("#head-form").is(":visible")){ $("#head-form").fadeOut(); }else{ $(".menu").hide(); $("#head-form").show(); } }); }); Also take note of how you are spelling your class names and id's as pointed out by other people in this thread there are several misspellings and several answers have tried correcting that spelling for you. A: Actually I will upvote your question because it leads to an issue I didn't know before : elements embedded inside a buttton in FF will lose their click event. $("#p").click(function() { alert('hello'); }); document.getElementById('i').addEventListener('click', function(e) { alert('hello2'); }, false); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="b"> <img id="i" src="http://lorempixel.com/25/20" /> <em id="em">elements embedded inside a buttton in FF will lose their click event.</em> </button> I don't know if it's a bug as specs only state that It is illegal to associate an image map with an IMG that appears as the contents of a BUTTON element. So for you the solution is to reattach the event to the button (either by giving the serach-button id to your real button element, or with $("#serach-btn").parent().click(function() {. jQuery(document).ready(function($) { $("#serach-button").parent().click(function() { alert('hello'); }); $("#real-button").click(function() { alert('hello'); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="button-responsiv-list"> <button class="button-responsiv"><i id="serach-button" class="glyphicon glyphicon-search"></i> </button> <button class="button-responsiv" id="real-button"><i id="navbar-button" class="glyphicon glyphicon-align-justify"></i> </button> <button class="button-responsiv"><i id="sidebar-button-show" class="glyphicon glyphicon-indent-right"></i> <i id="sidebar-button-hide" style="display:none;" class="glyphicon glyphicon-indent-left"></i> </button> </div> A: Your button has this class .search-btn so, you can try this: $(function(){ $(".search-btn").click(function() { if($("#head-form").is(":visible")){ $("#head-form").fadeOut(); }else{ $(".menu").hide(); $("#head-form").show(); } }); }); A: Try changing "serach" to "search". Also you can change jQuery to $: $(document).ready(function () { $("#search-button").click(function () { var display = $("#head-form").css("display"); if (display != "none") { $("#head-form").fadeOut(); } else { $(".menu").hide(); $("#head-form").show(); } }); });
unknown
d7975
train
Oh, you're trying to rename the files? You can't use sed for that; that changes the contents of the files, without renaming them. Here's how I might do the renaming: for a in Dog_1*.csv; do mv "$a" "Dog_2${a#Dog_1}" done A: Since the question regards renaming of files, you may be better off renameing them. This application has syntax quite similar to sed's: rename 's/Dog_1/Dog_2/' *.csv And you may as well perform global renamings, if that is the case: rename 's/Dog_1/Dog_2/g' *.csv
unknown
d7976
train
Solved. Installed 32-bit Python by mistake, should be 64-bit for this.
unknown
d7977
train
If the entries in the table should be "expired" (and removed) at certain times, then here is a possible solution, using only a single timer: First of all use a priority queue where the "priority" is the expiration time. You can of course use any other table-like structure, but keep it sorted on the expiration time (it simplify things later). Then have your single recurring timer, which is triggered ten, twenty or maybe more times per second. When the timer is triggered, you get the current time, and simply remove all elements in the table whose expiration time have passed (comparing its expiration time with the current time). If the table is sorted on expiration date, it's a very simple loop where you compare the time from the "top" element, and if expired then "pop" the top element. You can use the same or similar techniques for just about any timing-related issue.
unknown
d7978
train
Well this is quite old question, I answer it because I run to it when looking for the same problem. Actually Mootools Acordion adds this much inline CSS: padding-top: 0px; border-top-style: none; padding-bottom: 0px; border-bottom-style: none; overflow: hidden; opacity: 1; The solutions I found for this are fixes that have to be applied after calling the new Fx.Accordion. I also agree that feels wrong to fix with !important CSS fixing. So I also looked for other options. Option 1, set back the css as you want: $$('.acordion3_content').setStyles({ border: '3px solid #0F0', 'overflow-y': 'auto', }); Option 2, create one more div inside or outside it. I did this option to get a scroll div I could have events connected to. Like this I could have a scroll inside the accordion's content without it being affected of Fx.Acordion's CSS.
unknown
d7979
train
Use :first selector with .find() to get input descendants. $('tr').find(':text:first').css('background-color','#C0C0C0'); Demo $("tr:text:first") in your code, finds tr with :text(type="text") which is invalid. <tr> does not have :text A: Have you tried $("tr input:first-child").css('background-color','#C0C0C0'); ? A: Also, if you can't get jQuery to work, it would be simple enough to add a class to the first table cell in each table row and style it that way, forgoing the time it would take to load jQuery(if that is an issue, as I have sometimes found it to be).
unknown
d7980
train
No, it is not possible. On Mac, if you want to access Kudu Console, you could use a browser open http://<yoursite>.scm.azurewebsites.net. But you could not do it on mac terminal. On Mac terminal, you could call Kudu API to manage your web app, see this link. On Mac terminal, you also could use Azure CLI 2.0 to manage your web app. A: You're trying to do something web apps are not designed to do. You cannot rdp/ssh into a web app. That's what the kudu web console / powershell is for, if you need a command-line for something. If you need to move specific app or data content to a web app, it's done through the version control provider you wire up to it (e.g. git), or ftp.
unknown
d7981
train
How about adding this to the where clause: and not (date_ind = 'no' and video_ind = 'no') Or, assuming that the values are binary: and (data_ind = 'yes' or video_ind = 'yes')
unknown
d7982
train
First of all, you should decide if dependency injection is really what you need. Basic idea of DI: instead of factories or objects themselves creating new objects, you externally pass the dependencies, and pass the instantiation problem to someone else. You suppose to go all in with it if you rely on framework, that is why no way of using new along with DI. You cannot pass/inject a class into the scala object, here is a draft of what you can do: Play/guice require some preparation. Injection Module to tell guice how to create objects (if you cannot do this if annotations, or want to do it in one place). class InjectionModule extends AbstractModule { override def configure() = { // ... bind(classOf[MyClass]) bind(classOf[GlobalContext]).asEagerSingleton() } } Inject the injector to be able to access it. class GlobalContext @Inject()(playInjector: Injector) { GlobalContext.injectorRef = playInjector } object GlobalContext { private var injectorRef: Injector = _ def injector: Injector = injectorRef } Specify which modules to enable, because there can be more than one. // application.conf play.modules.enabled += "modules.InjectionModule" And finally the client code. object Toyota extends Car { import GlobalContext.injector // at this point Guice figures out how to instantiate MyClass, create and inject all the required dependencies val myClass = injector.instanceOf[MyClass] ... } A simple situation expanded with a frameworks help. So, you should really consider other possibilities. Maybe it would be better to pass the configs as an implicit parameter in your case? For dependency injection with guice take a look at: ScalaDependencyInjection with play and Guice wiki
unknown
d7983
train
Same way you Bind the Text field. <TextBox Header="{Binding myBinding}" Text="{Binding textboxtext}" x:Name="TextBox"/> If you want to point it to a Resource then <Page.Resources> <x:String x:Key="myTextBoxHeader">this is a textbox header</x:String> </Page.Resources> <TextBox Text="{Binding textboxtest}" Header="{StaticResource myTextBoxHeader}"></TextBox> If you pointing to a .resw file then in most cases you will need a x:Uid like this <TextBox x:Uid="MyLocalizeTextBox"></TextBox> Then you need to edit the strings for the stuff you want to display, in this case your Header + Text Look at the highlighted section very carefully, you see the pattern? It won't show up on the designer and will show up when you deploy [See Image Below] So by now you may be wondering if you combine both methods? (one to show in the designer and one to show while deploy because you're localizing). This is actually the prefer method. 2 in 1 (Both methods) <TextBox x:Uid="MyLocalizeTextBox" Text="{Binding textboxtest}" Header="{StaticResource myBinding}"></TextBox> During design time it will use your local resouces, when deploy it will use the resources in the resw file.
unknown
d7984
train
Why not simply add a handler to the Closing or Closed event: private void ShowChildWindow() { Window childWindow = new ChildWindow(); childWindow.Closed += ChildWindowClosed; childWindow.Show(); } private void ChildWindowClosed(object sender, EventArgs e) { ((Window)sender).Closed -= ChildWindowClosed; RepeaterRefresh(); }
unknown
d7985
train
Well the first thing you should do is remove the code you added and get back to a version that complies. Then try again. You should also supply some code because the errors are not enough to answer this problem on their own. You should also know that the R.java file is created each time you compile the app. The error from the R.java file probably indicates that there is a problem with the way you have coded the fragment navigation drawer. Check to see if you have used any spaces in the name, the R.java error shows an underscore and a hyphen. This may indicate that there is a problem with the name. I would also recommend looking up some youtube videos explaining how to use the LogCat output to identify errors. You should also read through the Google documentation on navigation drawer http://developer.android.com/training/implementing-navigation/nav-drawer.html and compare the example code with the code you have written. A: Its smart answer is that there is some syntax error in your Code may be in Java file or XML. Fix them first. Error will gone. work 100 percent for me every time Here is my Error! I found it & remove then this compile time error resolve.
unknown
d7986
train
What you have is not YAML with embedded JSON, it is YAML with some the value for annotations being in YAML flow style (which is a superset of JSON and thus closely resembles it). This would be YAML with embedded JSON: api: v1 hostname: abc metadata: name: test annotations: | { "ip" : "1.1.1.1", "login" : "fad-login", "vip" : "1.1.1.1", "interface" : "port1", "port" : "443" } Here the value for annotations is a string that you can hand to a JSON parser. You can just load the file, modify it and dump. This will change the layout of the flow-style part, but that will not influence any following parsers: import sys import ruamel.yaml file_in = Path('input.yaml') yaml = ruamel.yaml.YAML() yaml.preserve_quotes = True yaml.width = 1024 data = yaml.load(file_in) annotations = data['metadata']['annotations'] annotations['ip'] = type(annotations['ip'])('4.3.2.1') annotations['vip'] = type(annotations['vip'])('1.2.3.4') yaml.dump(data, sys.stdout) which gives: api: v1 hostname: abc metadata: name: test annotations: {"ip": "4.3.2.1", "login": "fad-login", "vip": "1.2.3.4", "interface": "port1", "port": "443"} The type(annotations['vip'])() establishes that the replacement string in the output has the same quotes as the original. ruamel.yaml currently doesn't preserve newlines in a flow style mapping/sequence. If this has to go back into some repository with minimal chances, you can do: import sys import ruamel.yaml file_in = Path('input.yaml') def rewrite_closing_curly_brace(s): res = [] for line in s.splitlines(): if line and line[-1] == '}': res.append(line[:-1]) idx = 0 while line[idx] == ' ': idx += 1 res.append(' ' * (idx - 2) + '}') continue res.append(line) return '\n'.join(res) + '\n' yaml = ruamel.yaml.YAML() yaml.preserve_quotes = True yaml.width = 15 data = yaml.load(file_in) annotations = data['metadata']['annotations'] annotations['ip'] = type(annotations['ip'])('4.3.2.1') annotations['vip'] = type(annotations['vip'])('1.2.3.4') yaml.dump(data, sys.stdout, transform=rewrite_closing_curly_brace) which gives: api: v1 hostname: abc metadata: name: test annotations: { "ip": "4.3.2.1", "login": "fad-login", "vip": "1.2.3.4", "interface": "port1", "port": "443" } Here the 15 for width is of course highly dependent on your file and might influence other lines if they were longer. In that case you could leave that out, and make the wrapping that rewrite_closing_curly_brace() does split and indent the whole flow style part. Please note that your original, and the transformed output are, invalid YAML, that is accepted by ruamel.yaml for backward compatibility. According to the YAML specification the closing curly brace should be indented more than the start of annotation
unknown
d7987
train
Your root element on the xml is a custom element. If the graphical layout cannot render that first element, it won't be able to render the rest of them either. A: "com.example.parallax_sample" is the problem, previews for custom view can't be created, though possibly it will work fine when you run it.
unknown
d7988
train
I'm not sure if the WSDL is valid or not but what you are trying to do won't work. Svcutil can generate code only for WSDL files of version 1.1. Yours is a WSDL version 2.0. The WSDL validator you pointed in your question returns the following message when given your WSDL: faultCode=INVALID_WSDL: Expected element 'http://schemas.xmlsoap.org/wsdl/:definitions'. It parses the file as WSDL 1.1. and expects the root to be definitions, but that changed in WSDL 2.0 to description. If you have a valid WSDL 2.0 file, Svcutil2 might be able to generate the code for you, but this tool isn't stable yet. To validate the WSDL, I guess you could use the validator from The Woden project, which isn't stable either, but is basically the only one that I know that has moved passed the "toy project" status. The idea is this: version 1.1 is still the "de facto" language when taking WSDL. Not many WS frameworks have adopted WSDL 2.0 so (just my 2 cents!) I think it's better to stick with "the standard" untill support is fully matured for WSDL 2.0. A: try to add reference References > Add Reference > COM > System.ServiceModel
unknown
d7989
train
In general to concatenate two variables you can just write them one after another: a='C' b='20140728' c=$a$b edit: to get the current date b = $(date +'%Y%m%d')
unknown
d7990
train
OK if you find this error is because of the way the data is being passing Ex: ?page=1&sort=name&direction:asc is not a CakePHP way of handling params. A right format url in cake should be nice looking like this: domain.com/2/name/asc The way I end it up passing the params in routes.php: $routes->connect('/productoptions/:page/:sort/:direction', ['controller' => 'Productoptions', 'action' => 'index'], ['param' => ['page'], 'param2' => ['sort'], 'param3' => ['direction'] ]); So I can use $this->request->params['page] , $this->request->params['direction] etc... In this way, I use CakePHP way of passing and handling params instead of $_GET
unknown
d7991
train
Apparently there is an issue with the JDK and OSX where the hostname does not recognize localhost. The solution is to add localhost to /etc/hosts A: You need to pass the capabilities to the driver: WebDriver driver = new FirefoxDriver(capabilities);
unknown
d7992
train
$ab = 0; $xy = 1; echo "<table>"; $i = 0; while ($i < 5) { echo "<tr><td>$ab</td><td>$xy</td></tr>"; $ab += $xy; $xy += $ab; $i++; } echo "</table>"; For explanation : Compared to the "for" loop, you have to initialize the "counter" before opening the loop [ $i = 0 ] Inside the loop, you specify the condition to continue the loop [ $i < 5 ] And somewhere into the loop, you increase your "counter" [ $i++ ] Your "counter" can be increased or decreased, or directly set ; it's all about your code logic and what are your needs. You can also break the loop whenever you want in case you need to, see an example : while ($i < 5) { echo "<tr><td>$ab</td><td>$xy</td></tr>"; $ab += $xy; $xy += $ab; if ($ab == 22) { // If $ab is equal to a specific value /* Do more stuff here if you want to */ break; // stop the loop here } $i++; } This example also work with the "for" loop. And there is also another keyword, "continue", used to tell to "jump" to the next loop iteration : while ($i < 5) { $i++; // Don't forget to increase "counter" first, to avoid infinite loop if ($ab == 22) { // If $ab is equal to a specific value /* Do more stuff here if you want to */ continue; // ignore this iteration } /* The following will be ignored if $ab is equal to 22 */ echo "<tr><td>$ab</td><td>$xy</td></tr>"; $ab += $xy; $xy += $ab; } A: To replace a for loop with a while loop, you can declare a variable before you initiate the while loop which will indicate the current iteration of the loop. Then you can decrement/increment this variable upon each iteration of the while loop. So you would have something like this: $counter = 0; while ($counter < 5) { echo ""; echo "<td>" . $ab . "</td><td>" . $xy . "</td>"; $ab += $xy; $xy += $ab; echo "</tr>"; $counter++; } in general: for ($i = 0; $i < x; $i++) { do stuff } is equivalent to: $counter = 0; while ($counter < x){ do stuff counter++; }
unknown
d7993
train
There are various ways of doing this, but I don't think you can guarantee a valid result depending on what steps people go through to hide it. Check out PEiD, it can to do this automatically (along with detecting packers, etc).
unknown
d7994
train
That quote is talking about a scenario where you can return a meaningful response without actually finishing all the work required by the request. For instance you might upload a file to be processed and respond immediately with a processing ID, but pass the processing to another thread. Later on the client could make another request with that ID to find out if processing completed. An asynchronous servlet scenario would hand off processing to another thread to do the work while blocking the request. But the blocked request would not tie up a servlet request thread during processing like a normal synchronous servlet request. Suppose you had a single threaded processor and 10 requests were made at the same time. With a synchronous servlet that waited for the processing to finish, you'd have 10 blocked request threads + 1 processor thread. But with an asynchronous servlet, you'd have 0 blocked threads + 1 processor thread. That's a pretty significant gain.
unknown
d7995
train
One of the simplest way to use scoped variables within another function is to simply pass them in as arguments of the function. e.g. const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout, }) readline.question('Enter number 1', function (a) { readline.question('Enter number 2', function (b) { //`i want to store user entered vaule in some variable and use in another function like sum` const result = sum(a, b); console.log(`The result of running my function is ${result}`); readline.close() }) }) function sum(first,second) { return first + second; }
unknown
d7996
train
Following https://developers.facebook.com/docs/technical-guides/opengraph/publishing-with-app-token/: import requests r = requests.get('https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=123&client_secret=XXX') access_token = r.text.split('=')[1] print access_token (using the correct values for client_id and client_secret) gives me something that looks like an access token. A: If you just need a quick/small request, you can manually cut and paste the access token from here into you code: https://developers.facebook.com/tools/explorer Note: Unlike Richard Barnett's answer, you'll need to regenerate the code manually from the graph api explorer every time you use it.
unknown
d7997
train
I think adding duplicate keys is a bad idea. You should use json array (QJsonArray) in this case. QJsonArray array; array.append("test_data_1"); array.append("test_data_2"); array.append("test_data_3"); array.append("test_data_4"); QJsonObject o; o["myArray"] = array; QJsonDocument doc(o); qDebug() << doc.toJson(); Output will be { "myArray": [ "test_data_1", "test_data_2", "test_data_3", "test_data_4" ] }
unknown
d7998
train
* *BufferStrategy doesn't play well with Swing, as you've taken control of the painting process *Canvas can't be transparent, so it will hide anything beneath it... *When you use frame.add(game) you are replaceing what ever use to be at BorderLayout.CENTER Instead of mixing lightweight (Swing) and heavy weight (AWT) components, paint the background image as part of your render process public void render() { BufferStrategy bs = this.getBufferStrategy(); if(bs == null) { createBufferStrategy(3); //Use 5 at most return; } Graphics g = bs.getDrawGraphics(); //RENDER HERE // Paint background here... player.render(g); healthBars.render(g); //END RENDER g.dispose(); bs.show(); }
unknown
d7999
train
One way to do that would be to add to the same group every method you want testA to execute. In the following example, testY and testZ are added to the "myGroup" group so the testA after method, which also belongs to this group, will only be executed for those tests. @Test public void testX(){ } @Test(groups = { "myGroup" }) public void testY(){ } @Test(groups = { "myGroup" }) public void testZ(){ } @AfterMethod(groups = { "myGroup" }) public void testA(){ }
unknown
d8000
train
I faced the same problem once and solved it by creating a function (or a class static method) to handle my option lists. To print out your options you will have to cycle through them anyway, so while you cycle there is nothing bad in checking for each one if it must be the currently selected. Just create a function like: function printSelectOptions($dataArray, $currentSelection) { foreach ($dataArray as $key => $value) { echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } Giving $dataArray as your key/value options array, and $currentSelection as the key of the selected option. So in your code you will have just calls to this function, like: <select id='mySelect' name='mySelect'> <?php echo printSelectOptions($gifts, $gift); ?> </select> This should do the work! EDIT: Adding sample to work with select multiple... <?php $options = array( 1 => "Test 1", 2 => "Test 2", 3 => "Test 3"); $selected = array(1, 3); function printSelectOptions($dataArray, $selectionArray) { foreach ($dataArray as $key => $value) { echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } ?> <select multiple> <?php echo printSelectOptions($options, $selected); ?> </select> The trick is passing the selected values as an array of keys, instead of a single key. In the sample I provided dummy arrays, but obviously you'll have to build yours from database... :) EDIT: Select multi with arrays taken from the question... <?php $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll"); $gift = array($row['gift_privacy']); function printSelectOptions($dataArray, $selectionArray) { foreach ($dataArray as $key => $value) { echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } ?> <select multiple> <?php echo printSelectOptions($gifts, $gift); ?> </select> EDIT: Explode multiple selected values If you have mutliple selected values as a comma separated string, you just have to explode it before passing to the function I provided... $selectedOptionsArray = explode(',', $selectedOptionsString); So the ending code will look like... <?php $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll"); $gift = explode(',', $row['gift_privacy']); function printSelectOptions($dataArray, $selectionArray) { foreach ($dataArray as $key => $value) { echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } ?> <select multiple> <?php echo printSelectOptions($gifts, $gift); ?> </select> A: You could use a function like this to simplify it: <?php function renderOption($key, $value, $current) { echo '<option value="' . $key . '"' . ($key == $current ? ' selected="selected"' : '') . '>' . $value. '</option>'; } ?> <select name="gift_privacy"> <?php $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll"); $gift = $row['gift_privacy']; foreach($gifts as $key => $value) renderOption($key, $value, $gift); ?> </select> A: Use simpler method: <?php echo '<option '.($key == $gift ? 'selected="selected" ' : '').'value="'. $key .'">'. $value .'</option>'; ?> Edit: second option echo '<option '.selected_option($key, $gift).'value="'. $key .'">'. $value .'</option>'; function selected_option($val1, $val2){ if($val1 == $val2){ return 'selected="selected" '; }else{ return ''; } } A: There is nothing wrong with what you have, and this, or something very similar is the typical approach to this problem. You would/could wrap it in an actual function, say print_select( $array, $selected ); which would/could print out the entire <select> including the select themselves. The final code might be: print_select( $gifts, $selected_gift ); print_select( $colors, $selected_color ); // etc
unknown